content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
@lightspeed/cirrus-badge Cirrus Badge Component Stats StarsIssuesVersionUpdatedCreatedSize @lightspeed/cirrus-badge 7.0.0-beta.13 years ago5 years agoMinified + gzip package size for @lightspeed/cirrus-badge in KB Readme Badge Our basic badge component. Installation 1. Since we use peer dependencies to minimize library duplication, ensure you have the following dependencies loaded within your project yarn add @lightspeed/cirrus-tokens emotion@9 react-emotion@9 styled-system@3 polished@2 1. Install the component library yarn add @lightspeed/cirrus-badge 1. Hook the <ThemeProvider> and the theme in your app. // 1. Import the theme provider from emotion-theming // This is needed to forward all our tokens to the components import { ThemeProvider } from 'emotion-theming'; // 2. Import the base theme from cirrus-tokens // There's nothing magical about this file. it's literally // a plain old javascript object with keys and values that // map to the tokens/design-system import cirrusTheme from '@lightspeed/cirrus-tokens/theme/default'; /* Within your root app component */ class App extends React.Component { render() { return ( {/* 3. Wrap the children with ThemeProvider and pass in the cirrus theme into the theme prop. */} <ThemeProvider theme={cirrusTheme}> {/* Whatever children */ } </ThemeProvider> ); } } 1. Import { Badge } and use right away! React Components <Badge> Prop Type Description children React.ReactNode The content to display inside the button type 'default', 'info', 'success', 'info', 'important', 'warning', 'danger' Style of badge size 'small', 'medium' Change size of badge bg string Custom background color. Accepts any valid CSS color, i.e: #000 color string Custom text color. Accepts any valid CSS color, i.e: #fff <PillBadge> extends <Badge> Example import React from 'react'; import { Badge, PillBadge } from '@lightspeed/cirrus-badge'; const MyComponent = () => <div> <Badge>My Badge</Badge> <PillBadge>My PillBadge</PillBadge> </div>; export default MyComponent; If you find any bugs or have a feature request, please open an issue on github! The npm package download data comes from npm's download counts api and package details come from npms.io.
__label__pos
0.647049
Post a New Question maths posted by on . In Newtopia, inflation runs at 15%. A home entertainment unit currently sells for $2000 A)How much would you expect it to cost in a year`s time? B) How much would you expect it to cost in two years time? • maths - , A) Sam jogs 6 laps around a circular running track which has a radius of 30 metres. How far does she jog in total? B) Tom and Jerry decide to find the perimeter of their garden. Tom measures the length as 5.2 metres while Jerry measures the width as 370cm. What is the perimeter? • maths - , Chris wants to put a concrete path and a fence around his rectangular garden. The concrete path will be 1 meter wide and the fence will go around the edge of the path. The garden itself measures 5meter by 8 meters. A) calculate the perimeter of thr fence. B)Calculate the area of the concrete path. C) If the thickness of the concrete path is 60mm, calculate the volume of the concrete needed. PLEASE HELP !!! :) • maths - , A farmer needs to spread fertiliser over a paddock measuring 40m by 80m. The instructions on the fertiliser bag say to use 80grams per square meter. How many kilograms of fertiliser will be needed? • math (Leah & S.P) - , If you have a question, it is much better to put it in as a separate post in <Post a New Question> rather than attaching it to a previous question, where it is more likely to be overlooked. Also, many tutors will assume the previous question has already been answered. Answer This Question First Name: School Subject: Answer: Related Questions More Related Questions Post a New Question
__label__pos
0.999908
SQL SERVER – Simple Puzzle with UNION – Part 2 Yesterday we had very easy kind of Back to Basics Puzzle with UNION and I have received tremendous response to the simple puzzle. Even though there is no giveaway due to sheer interest in the subject, I have received many replies. Due to all the request, here is another back to the basic question with UNION again. Let us execute following three query one by one. Please make sure to enable Execution Plan in SQL Server Management Studio (SSMS). Query 1 SELECT 1 UNION ALL SELECT 2 The query above will return following result The query above will return following execution plan Query 2 SELECT 1 UNION ALL SELECT 2 ORDER BY 1 The query above will return following result The query above will return following execution plan Query 3 SELECT DISTINCT 1 UNION ALL SELECT DISTINCT 2 ORDER BY 1 The query above will return following result The query above will return following execution plan Now let us look at all the execution plans together. When you look at closely at all the resultset – they all returns the same result. When we see their execution plan they are very different from each other. Now here is the question back to you. Question: When we add DISTINCT in Query 3 it is technically more work for SQL Server to do than Query 2. However, the execution plan demonstrates that Query 3 is using much lesser resources than Query 2. WHY? Please leave your answer in the comment section. I will publish all the valid answer in the blog next week with due credit. Do not miss to checkout the part 1 of this puzzle. Reference: Pinal Dave (http://blog.sqlauthority.com) About these ads 32 thoughts on “SQL SERVER – Simple Puzzle with UNION – Part 2 1. Hi Pinal, Query 2 : In this case all the select statements are combined to form a table and a constant scan goes for entire table,followed by sorting. Query 3: while in this case each select statement itself goes for constant scan and then combined to form a table .So in this case entire constant scan is avoided. So the query 3 is using lesser resource than Query 2. • Sanjay, When executing all three together, the breakdown is 0/67/33 — the numbers will always total 100%, regardless of the number of queries. The query cost percentage can only show the time in relationship to the other queries in the batch. Hence, when a query is run by itself, it’s query cost will always be 100%. I got this info. from James Curran. 2. Using your execution plan figure we can say that no need of sorting in query 3 thats why its using less resources than Query 2. 3. Query 2 lists all available records including duplicates which could increase the output list size and the sorting time while the presence of distinct in query 3 decreases the length of output list and helps to minimize sorting time. I think distinct is taking less time than sort because it has to work on less data while sort has to arrange the output of both part of the query. 4. The distinct causes the two sets to be sorted as a side-effect. Since the sets are one row each in this case, that sorting is really fast. Then taking two sorted lists (even sets with one than one row), and making one big sorted list out of them requires just merging them — going through them linearly, and taking whichever is the next lowest. 5. Hi, If you execute all the three queries together in a single session, then 100%,67%,33% cost comes. If you execute the 3rd query separately, 100% cost comes. That means when executing in the same session, the query uses the previously executed plan for the current execution. Correct if my answer is wrong. • No. When executing all three together, the breakdown is 0/67/33 — the numbers will always total 100%, regardless of the number of queries. The query cost percentage can only show the time in relationship to the other queries in the batch. Hence, when a query is run by itself, it’s query cost will always be 100%. 6. Hey Pinal, Query 3 uses the Merge Join operator while Query 2 uses the sort operator. A merge join operator is used on the two tables whose output columns have been presorted. The sort operator uses the concept of looping to get its output which requires an extra thread to perform what we call ‘Rebinding’. This increases the I/O Cost drastically. Hence the difference. Regards, Kunal Rawal 7. Hey Pinal, Here, query 3 taking lower cost than 2 as there is only 1 row for selection. Sorting individual rows in q3 is not taking any cost. Now, q3 uses merge and q2 uses sorting for ordering the result and merging is faster than sorting as merge is being applied on presorted lists. If we select from a un-indexed table with 10 rows. then results are 13/30/57 (my sample), which are consistent. Since, q3 includes sorting individual results first so q3 cost is high. 8. Pingback: SQL SERVER – Simple Puzzle with UNION – Part 3 | Journey to SQL Authority with Pinal Dave 9. Pingback: SQL SERVER – Simple Puzzle with UNION – Part 4 | Journey to SQL Authority with Pinal Dave 10. Pingback: SQL SERVER – Simple Puzzle with UNION – Part 5 | Journey to SQL Authority with Pinal Dave 11. Query (3) , using Distinct so its already sorting the records, thats why its showing the lowest query cost I have checked one more scenario, in this both query is showing the same cost, ie 50% each —inserting records into a temporary table SELECT 1 ID INTO #T1 UNION ALL SELECT 2 SELECT ID FROM #T1 ORDER BY ID SELECT DISTINCT ID FROM #T1 ORDER BY ID 12. I believe it is because query 2 uses a sort while query 3 uses the merge join operator “exploiting their sort order”. I found it a little surprising that this uses two merge joins and not a sort ([1], [2]) and a merge join ([1,2], [3]). SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT distinct 3 ORDER BY 1 13. I have to guess that there is a big difference between the Sort operator and the Merge Join operator. Looking at the properties of both I see an IO cost and a rebind associated with the sort operator that does not exist for the Merge Join. I have to guess that the Sort is internally doing some kind of loop that requires IO. 14. I want consolidate of numbers in SQL …For an example I having number like 1,2,3,4,.6.7.8.9,12,13,14,16,18,20 then I want the result as 1-4,6-9,12-14,16,18,20 How to achieve it please help me • –>–First of all create one table valued function & use it in code block… create FUNCTION [dbo].[Split] ( @string AS VARCHAR(8000), @splitAt AS VARCHAR(8000) ) RETURNS @strings TABLE (Strings VARCHAR(8000)) AS BEGIN DECLARE @splitLen AS INT DECLARE @index AS INT SET @splitLen = LEN(@splitAt) – SET @string = LTRIM(RTRIM(@string)) SET @splitAt = ‘%’ + @splitAt + ‘%’ SET @index = PATINDEX(@splitAt, @string) WHILE(@index > 0) BEGIN INSERT INTO @strings VALUES(SUBSTRING(@string, 1, @index-1)) SET @string = SUBSTRING(@string, @index + 1, LEN(@string)) SET @index = PATINDEX(@splitAt, @string) END IF LEN(@string) > 0 INSERT INTO @strings VALUES(@string) RETURN END –======================================================================= DECLARE @string nvarchar(max) DECLARE @Input nvarchar(max) DECLARE @old int SET @Input = ’1,2,3,4,6,7,8,9,12,13,14,16,18,20′ SET @string = ” SELECT @string = @string + case when Strings = @old + 1 THEN ” when @string = ” then Strings ELSE ‘-’ + cast(@old as nvarchar) + ‘,’ + Strings end, @old = Strings FROM dbo.split(@Input,’,’) select @string as result 15. Pingback: SQL SERVER – Five Puzzles around UNION – Participate in All Five | Journey to SQL Authority with Pinal Dave 16. HI PINAL, IN the SECOND query,”SORT” operation takes place and we get estimated I/O cost is “0.0112613″ IN the THIRD query,”MERGE JOIN” operation takes place i.e.., it takes two already sorted input tables exploitting the sort order.and we get estimated I/O cost is “0″ in other word ,in the second query both physical and logical operations are “SORTING” whereas,IN the third query physical operation=MERGE JOIN(takes already sorted input table) and logical operation=CONCATINATION 17. Hi Pinal, Because of explicit SORT operation on final result set causes second query more expensive … Whereas 3rd query doesn’t require any SORT operation externally… Note that “Merge join itself is very fast, but it can be an expensive choice if sort operations are required.” means if there is no sort operation required then MERGE JOIN is very fast… The above two are the reasons to have less cost for 2nd query 18. If I look at the plan carefully, the Query 2 uses the Sort operation and the Query 3 uses the Merge Join. There is an extra cost on performing Sort operation as it does sorting at both Physical and Logical operations. The Merger Join operator matches the rows from two sorted input tables thus at physical level its merging and logical level its concatenating the operation thus exploiting the sort order. 19. MERGE JOIN internally use SORTING technique while merging the input data. Also DISTINCT itself sorts the data internally, so SORT operation time is reduced here. 20. HI PINAL, the SECOND query,”SORT” operation takes place, hence the sorting took place in tempdb and we got the estimated I/O cost which is greater than 0 this make the query use little more resource than other query In the THIRD query the select statement is already sorted with distinct operator and then the sorted result set is merged using merge JOIN concatenation, since there is no any writes or reads required here so this query take little amount of resource Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out / Change ) Twitter picture You are commenting using your Twitter account. Log Out / Change ) Facebook photo You are commenting using your Facebook account. Log Out / Change ) Google+ photo You are commenting using your Google+ account. Log Out / Change ) Connecting to %s
__label__pos
0.789588
The tag has no wiki summary. learn more… | top users | synonyms 2 votes 0answers 81 views A question about fractional integrals I am starting from Theorem 3.4 in Struwe's book Variational methods. The authors proves an existence result for a problem with critical growth. I would like to replace the laplacian with the ... 1 vote 0answers 116 views A fractional calculus eigenvalue problem One set of eigenfunction for the following fractional integral operator is $f(z)=e^{-bz}$ for any constant Re$b>0$, with eigenvalue $\lambda=\frac{\Gamma(\alpha)}{b^\alpha}$, $$\int_z^\infty ... 1 vote 0answers 299 views Relation between interpolation spaces and besov spaces Consider the following two norms: The interpolation norm: 1) $\|u; [L_2,\dot H_1^{\infty}]_{1/3,\infty}\| := \sup_{s > 0} \inf_{u=u_0+u_1} \frac{\|u_0\|_{L^2}}{s^{1/2}} + s \|\partial_x ... 0 votes 0answers 22 views Diffusion maps for non-Markov Diffusion maps based on the work of Coifman and Lafon use concepts from Markov chains and heat diffusions. Have there been work to extend diffusion maps to non-Markovian or fractional heat ... 0 votes 0answers 135 views Natural integration constant for normal and discrete integration: is there a connection? It is often assumed that integration, unlike differentiation is defined only to an arbitrary constant. So the antiderivative function is often left undefined or postulated to be zero in zero. But I ... 0 votes 0answers 133 views Fractional Derivative of A specific function I've tried and tried to do this problem myself, but I've hit some snags on the way. I'm trying to take the fractional derivative of: $f(x)=1+n^{-x}$ where n is an integer and $n\geq2$ and $x>1$. ... 0 votes 0answers 146 views Fractional Derivatives Of Sums I have a question regarding the definition of a fractional derivative. I've searched, but I can't find a definition of fractional derivatives that explain the concept in terms of an operator on some ... 0 votes 0answers 70 views Fractional/complex powers of integrals I'm wondering if there is a way to represent a fractional power of an integral as a function of the integrand in the following sense: The binomial theorem for complex/fractional exponents represents a ... 0 votes 0answers 338 views Chain rule for fractional derivative defined via Fourier transform It is well known that in the case of integer order differentiation the formula $\partial_{x}f(x,u(x))=\partial_{u}f\cdot \partial_{x}u+\partial_{x}f\cdot u$ holds. If we define fractional derivative ...
__label__pos
0.694696
Robson » Little Red Book » Eight Queens Chapter 9 - Question 5 The chess board and pieces are a source of many intriguing problems. One such is: Eight queens are to be placed on a chess board in such a way that no queen could capture any of the others. Solution 1 I'm going to work this out by feeding some simple rules into a script and then making the script do the hard work. Horizontal matching is sorted by only placing one queen on each row. Vertical matching is sorted by taking any array of the values 0 to 7 and shuffling it, then placing the queen for each row on the corresponding square across. So all solutions generated will be fine horizontal and vertical. This means the actual work is taken up by generating solutions until one works for diagonals as well. PHP: <?    // all queens must be on a different vertical line    $pos = array(0, 1, 2, 3, 4, 5, 6, 7);        // loop at least once    do    {        // use a random order each time        shuffle($pos);            // loop through each row        for ($n = 0; $n < 8; $n++)        {            // write empty squares across            $board[$n] = array_fill(0, 8, 0);            // place a queen in one square            // this takes care of horizontal matching            $board[$n][$pos[$n]] = 1;        }                // reset the invalid variable        $invalid = false;        // loop through each row        for ($a = 0; $a < 8 && !$invalid; $a++)        {            // loop through each potential column            for ($b = 0; $b < 12 && !$invalid; $b++)            {                // determine the difference between each row                // this is then used to calculate the position of all the potential hits                $diff = ($b - $a) + 1;                // check the diagonal rule                $invalid =                    // check it's inside the board and not the same square                    $a-$diff >= 0 && $a-$diff <= 7 && $diff &&                    (                        // check if the square is inside the board                        // and check if it's occupied                        ($pos[$a]-$diff >= 0 && $pos[$a]-$diff < 8 && $board[$a-$diff][$pos[$a]-$diff] == 1)                        ||                        ($pos[$a]+$diff >= 0 && $pos[$a]+$diff < 8 && $board[$a-$diff][$pos[$a]+$diff] == 1)                    );            }        }        // increment the attempts        $counter++;    }    // loop until a valid solution is found    // or until too many attempts have been made    while ($invalid && $counter < 1000);      // check if the loop terminated because it took too long    if ($invalid)        // just fail with a message        echo 'The script has stopped early because a solution was not found in time. '           . 'Try refreshing this page to find a solution.';    else    {            // output the board        for ($n = 0; $n < 8; $n++)            // show the empty and filled squares            echo implode('', $board[$n]) . '<br/>';                    // show how many tries it took to find a solution        echo 'Attempts: ' . $counter . '.';    } ?> Which produces: 00100000 00000100 00000001 10000000 00010000 00000010 00001000 01000000 Attempts: 196. Log © 2004-17 robson | cc unless stated
__label__pos
0.967633
top of page 展會會議 EVENT & NEWS The Advantages of Biometric Identification System biometric identification system With the development of information technology, social management has become increasingly electronic and automated. In such a huge social network system, system security is very important. Accurate identification of personal identity is a necessary prerequisite for the security of each system. At present, most of the various management in our country use certificates, magnetic cards, IC cards and passwords. These methods cannot avoid forgery or loss, and passwords are also easy to be stolen or forgotten. All these bring great inconvenience to managers and users. Biometric identification system can avoid these troubles. Therefore, biometric technology has become a research hotspot in the field of identity authentication. Biometric technology mainly refers to a kind of technology of identity authentication through human biometrics. Human biometrics usually have the characteristics of uniqueness, measurability or automatic identification and verification, heredity or lifetime invariability. Therefore, biometric authentication technology has greater advantages than traditional authentication technology. The biometric identification system samples the biometric features, extracts the unique features and converts them into digital codes, and further forms these codes into feature templates. As the cost of microprocessors and various electronic components continues to decline and the accuracy gradually improves, biometric identification system is gradually applied to the authorization control in business, such as access control, enterprise attendance management system security authentication and other fields. Biometrics used in biometrics include hand shape, fingerprint, face shape, iris, retina, pulse, auricle, etc. behavioral features include signature, voice, key strength, etc. Based on these features, people have developed a variety of biometric technologies, such as hand shape recognition, fingerprint recognition, face recognition, pronunciation recognition, iris recognition, signature recognition and so on. Biometric identification system has the following advantages: Security Human characteristics are the best proof of personal identity, and meet higher security needs. Each person has different biological characteristics and cannot be easily lost, forgotten, copied and embezzled. Convenience Biometrics do not need to remember passwords and carry additional tools (such as keys and cards), and will not be lost. Accurate identification Multi mode biometric recognition ensures 100% accuracy. Easy to use Usually it takes a simple scan or photo. Difficult to forge Biometric properties are almost impossible to forge or steal. Save time Biometric recognition is very fast, and one can be identified or rejected in seconds. Scalability Biometric system can be very flexible and easy to expand. 179 次查看
__label__pos
0.594472
 Reference documentation for deal.II version 9.3.3 \(\newcommand{\dealvcentcolon}{\mathrel{\mathop{:}}}\) \(\newcommand{\dealcoloneq}{\dealvcentcolon\mathrel{\mkern-1.2mu}=}\) \(\newcommand{\jump}[1]{\left[\!\left[ #1 \right]\!\right]}\) \(\newcommand{\average}[1]{\left\{\!\left\{ #1 \right\}\!\right\}}\) matrix_free.h Go to the documentation of this file. 1// --------------------------------------------------------------------- 2// 3// Copyright (C) 2011 - 2021 by the deal.II authors 4// 5// This file is part of the deal.II library. 6// 7// The deal.II library is free software; you can use it, redistribute 8// it, and/or modify it under the terms of the GNU Lesser General 9// Public License as published by the Free Software Foundation; either 10// version 2.1 of the License, or (at your option) any later version. 11// The full text of the license can be found in the file LICENSE.md at 12// the top level directory of deal.II. 13// 14// --------------------------------------------------------------------- 15 16 17#ifndef dealii_matrix_free_h 18#define dealii_matrix_free_h 19 20#include <deal.II/base/config.h> 21 28 30 31#include <deal.II/fe/fe.h> 32#include <deal.II/fe/mapping.h> 34 36 40 45 51 52#include <cstdlib> 53#include <limits> 54#include <list> 55#include <memory> 56 57 59 60 61 113template <int dim, 114 typename Number = double, 115 typename VectorizedArrayType = VectorizedArray<Number>> 117{ 118 static_assert( 119 std::is_same<Number, typename VectorizedArrayType::value_type>::value, 120 "Type of Number and of VectorizedArrayType do not match."); 121 122public: 127 using value_type = Number; 128 using vectorized_value_type = VectorizedArrayType; 129 133 static const unsigned int dimension = dim; 134 182 { 189 { 209 }; 210 211 // remove with level_mg_handler 213 219 const unsigned int tasks_block_size = 0, 225 const unsigned int mg_level = numbers::invalid_unsigned_int, 226 const bool store_plain_indices = true, 227 const bool initialize_indices = true, 228 const bool initialize_mapping = true, 229 const bool overlap_communication_computation = true, 230 const bool hold_all_faces_to_owned_cells = false, 231 const bool cell_vectorization_categories_strict = false) 247 , communicator_sm(MPI_COMM_SELF) 248 {} 249 262 , mg_level(other.mg_level) 274 {} 275 276 // remove with level_mg_handler 278 284 { 293 mg_level = other.mg_level; 304 305 return *this; 306 } 307 345 355 unsigned int tasks_block_size; 356 369 390 411 439 448 unsigned int mg_level; 449 456 464 475 484 498 507 524 std::vector<unsigned int> cell_vectorization_category; 525 536 541 }; 542 551 556 560 ~MatrixFree() override = default; 561 574 template <typename QuadratureType, typename number2, typename MappingType> 575 void 576 reinit(const MappingType & mapping, 577 const DoFHandler<dim> & dof_handler, 578 const AffineConstraints<number2> &constraint, 579 const QuadratureType & quad, 580 const AdditionalData & additional_data = AdditionalData()); 581 588 template <typename QuadratureType, typename number2> 590 reinit(const DoFHandler<dim> & dof_handler, 591 const AffineConstraints<number2> &constraint, 592 const QuadratureType & quad, 593 const AdditionalData & additional_data = AdditionalData()); 594 616 template <typename QuadratureType, typename number2, typename MappingType> 617 void 618 reinit(const MappingType & mapping, 619 const std::vector<const DoFHandler<dim> *> & dof_handler, 620 const std::vector<const AffineConstraints<number2> *> &constraint, 621 const std::vector<QuadratureType> & quad, 622 const AdditionalData &additional_data = AdditionalData()); 623 629 template <typename QuadratureType, 630 typename number2, 631 typename DoFHandlerType, 632 typename MappingType> 634 reinit(const MappingType & mapping, 635 const std::vector<const DoFHandlerType *> & dof_handler, 636 const std::vector<const AffineConstraints<number2> *> &constraint, 637 const std::vector<QuadratureType> & quad, 638 const AdditionalData &additional_data = AdditionalData()); 639 646 template <typename QuadratureType, typename number2> 648 reinit(const std::vector<const DoFHandler<dim> *> & dof_handler, 649 const std::vector<const AffineConstraints<number2> *> &constraint, 650 const std::vector<QuadratureType> & quad, 651 const AdditionalData &additional_data = AdditionalData()); 652 658 template <typename QuadratureType, typename number2, typename DoFHandlerType> 660 reinit(const std::vector<const DoFHandlerType *> & dof_handler, 661 const std::vector<const AffineConstraints<number2> *> &constraint, 662 const std::vector<QuadratureType> & quad, 663 const AdditionalData &additional_data = AdditionalData()); 664 672 template <typename QuadratureType, typename number2, typename MappingType> 673 void 674 reinit(const MappingType & mapping, 675 const std::vector<const DoFHandler<dim> *> & dof_handler, 676 const std::vector<const AffineConstraints<number2> *> &constraint, 677 const QuadratureType & quad, 678 const AdditionalData &additional_data = AdditionalData()); 679 685 template <typename QuadratureType, 686 typename number2, 687 typename DoFHandlerType, 688 typename MappingType> 690 reinit(const MappingType & mapping, 691 const std::vector<const DoFHandlerType *> & dof_handler, 692 const std::vector<const AffineConstraints<number2> *> &constraint, 693 const QuadratureType & quad, 694 const AdditionalData &additional_data = AdditionalData()); 695 702 template <typename QuadratureType, typename number2> 704 reinit(const std::vector<const DoFHandler<dim> *> & dof_handler, 705 const std::vector<const AffineConstraints<number2> *> &constraint, 706 const QuadratureType & quad, 707 const AdditionalData &additional_data = AdditionalData()); 708 714 template <typename QuadratureType, typename number2, typename DoFHandlerType> 716 reinit(const std::vector<const DoFHandlerType *> & dof_handler, 717 const std::vector<const AffineConstraints<number2> *> &constraint, 718 const QuadratureType & quad, 719 const AdditionalData &additional_data = AdditionalData()); 720 726 void 728 const MatrixFree<dim, Number, VectorizedArrayType> &matrix_free_base); 729 739 void 741 745 void 746 update_mapping(const std::shared_ptr<hp::MappingCollection<dim>> &mapping); 747 752 void 754 756 769 { 776 none, 777 788 values, 789 798 values_all_faces, 799 810 gradients, 811 820 gradients_all_faces, 821 828 unspecified 829 }; 830 875 template <typename OutVector, typename InVector> 876 void 877 cell_loop(const std::function<void( 879 OutVector &, 880 const InVector &, 881 const std::pair<unsigned int, unsigned int> &)> &cell_operation, 882 OutVector & dst, 883 const InVector & src, 884 const bool zero_dst_vector = false) const; 885 932 template <typename CLASS, typename OutVector, typename InVector> 933 void 934 cell_loop(void (CLASS::*cell_operation)( 935 const MatrixFree &, 936 OutVector &, 937 const InVector &, 938 const std::pair<unsigned int, unsigned int> &) const, 939 const CLASS * owning_class, 940 OutVector & dst, 941 const InVector &src, 942 const bool zero_dst_vector = false) const; 943 947 template <typename CLASS, typename OutVector, typename InVector> 948 void 949 cell_loop(void (CLASS::*cell_operation)( 950 const MatrixFree &, 951 OutVector &, 952 const InVector &, 953 const std::pair<unsigned int, unsigned int> &), 954 CLASS * owning_class, 955 OutVector & dst, 956 const InVector &src, 957 const bool zero_dst_vector = false) const; 958 1043 template <typename CLASS, typename OutVector, typename InVector> 1044 void 1045 cell_loop(void (CLASS::*cell_operation)( 1046 const MatrixFree &, 1047 OutVector &, 1048 const InVector &, 1049 const std::pair<unsigned int, unsigned int> &) const, 1050 const CLASS * owning_class, 1051 OutVector & dst, 1052 const InVector &src, 1053 const std::function<void(const unsigned int, const unsigned int)> 1054 &operation_before_loop, 1055 const std::function<void(const unsigned int, const unsigned int)> 1056 & operation_after_loop, 1057 const unsigned int dof_handler_index_pre_post = 0) const; 1058 1062 template <typename CLASS, typename OutVector, typename InVector> 1063 void 1064 cell_loop(void (CLASS::*cell_operation)( 1065 const MatrixFree &, 1066 OutVector &, 1067 const InVector &, 1068 const std::pair<unsigned int, unsigned int> &), 1069 CLASS * owning_class, 1070 OutVector & dst, 1071 const InVector &src, 1072 const std::function<void(const unsigned int, const unsigned int)> 1073 &operation_before_loop, 1074 const std::function<void(const unsigned int, const unsigned int)> 1075 & operation_after_loop, 1076 const unsigned int dof_handler_index_pre_post = 0) const; 1077 1082 template <typename OutVector, typename InVector> 1083 void 1084 cell_loop(const std::function<void( 1086 OutVector &, 1087 const InVector &, 1088 const std::pair<unsigned int, unsigned int> &)> &cell_operation, 1089 OutVector & dst, 1090 const InVector & src, 1091 const std::function<void(const unsigned int, const unsigned int)> 1092 &operation_before_loop, 1093 const std::function<void(const unsigned int, const unsigned int)> 1094 & operation_after_loop, 1095 const unsigned int dof_handler_index_pre_post = 0) const; 1096 1172 template <typename OutVector, typename InVector> 1173 void 1174 loop(const std::function< 1176 OutVector &, 1177 const InVector &, 1178 const std::pair<unsigned int, unsigned int> &)> &cell_operation, 1179 const std::function< 1181 OutVector &, 1182 const InVector &, 1183 const std::pair<unsigned int, unsigned int> &)> &face_operation, 1184 const std::function<void( 1186 OutVector &, 1187 const InVector &, 1188 const std::pair<unsigned int, unsigned int> &)> &boundary_operation, 1189 OutVector & dst, 1190 const InVector & src, 1191 const bool zero_dst_vector = false, 1192 const DataAccessOnFaces dst_vector_face_access = 1194 const DataAccessOnFaces src_vector_face_access = 1196 1282 template <typename CLASS, typename OutVector, typename InVector> 1283 void 1285 void (CLASS::*cell_operation)(const MatrixFree &, 1286 OutVector &, 1287 const InVector &, 1288 const std::pair<unsigned int, unsigned int> &) 1289 const, 1290 void (CLASS::*face_operation)(const MatrixFree &, 1291 OutVector &, 1292 const InVector &, 1293 const std::pair<unsigned int, unsigned int> &) 1294 const, 1295 void (CLASS::*boundary_operation)( 1296 const MatrixFree &, 1297 OutVector &, 1298 const InVector &, 1299 const std::pair<unsigned int, unsigned int> &) const, 1300 const CLASS * owning_class, 1301 OutVector & dst, 1302 const InVector & src, 1303 const bool zero_dst_vector = false, 1304 const DataAccessOnFaces dst_vector_face_access = 1306 const DataAccessOnFaces src_vector_face_access = 1308 1312 template <typename CLASS, typename OutVector, typename InVector> 1313 void 1314 loop(void (CLASS::*cell_operation)( 1315 const MatrixFree &, 1316 OutVector &, 1317 const InVector &, 1318 const std::pair<unsigned int, unsigned int> &), 1319 void (CLASS::*face_operation)( 1320 const MatrixFree &, 1321 OutVector &, 1322 const InVector &, 1323 const std::pair<unsigned int, unsigned int> &), 1324 void (CLASS::*boundary_operation)( 1325 const MatrixFree &, 1326 OutVector &, 1327 const InVector &, 1328 const std::pair<unsigned int, unsigned int> &), 1329 CLASS * owning_class, 1330 OutVector & dst, 1331 const InVector & src, 1332 const bool zero_dst_vector = false, 1333 const DataAccessOnFaces dst_vector_face_access = 1335 const DataAccessOnFaces src_vector_face_access = 1337 1402 template <typename CLASS, typename OutVector, typename InVector> 1403 void 1404 loop_cell_centric(void (CLASS::*cell_operation)( 1405 const MatrixFree &, 1406 OutVector &, 1407 const InVector &, 1408 const std::pair<unsigned int, unsigned int> &) const, 1409 const CLASS * owning_class, 1410 OutVector & dst, 1411 const InVector & src, 1412 const bool zero_dst_vector = false, 1413 const DataAccessOnFaces src_vector_face_access = 1415 1419 template <typename CLASS, typename OutVector, typename InVector> 1420 void 1421 loop_cell_centric(void (CLASS::*cell_operation)( 1422 const MatrixFree &, 1423 OutVector &, 1424 const InVector &, 1425 const std::pair<unsigned int, unsigned int> &), 1426 CLASS * owning_class, 1427 OutVector & dst, 1428 const InVector & src, 1429 const bool zero_dst_vector = false, 1430 const DataAccessOnFaces src_vector_face_access = 1432 1436 template <typename OutVector, typename InVector> 1437 void 1439 const std::function<void(const MatrixFree &, 1440 OutVector &, 1441 const InVector &, 1442 const std::pair<unsigned int, unsigned int> &)> 1443 & cell_operation, 1444 OutVector & dst, 1445 const InVector & src, 1446 const bool zero_dst_vector = false, 1447 const DataAccessOnFaces src_vector_face_access = 1449 1457 std::pair<unsigned int, unsigned int> 1458 create_cell_subrange_hp(const std::pair<unsigned int, unsigned int> &range, 1459 const unsigned int fe_degree, 1460 const unsigned int dof_handler_index = 0) const; 1461 1468 std::pair<unsigned int, unsigned int> 1470 const std::pair<unsigned int, unsigned int> &range, 1471 const unsigned int fe_index, 1472 const unsigned int dof_handler_index = 0) const; 1473 1477 unsigned int 1479 1483 unsigned int 1485 const std::pair<unsigned int, unsigned int> range) const; 1486 1490 unsigned int 1491 get_face_active_fe_index(const std::pair<unsigned int, unsigned int> range, 1492 const bool is_interior_face = true) const; 1493 1495 1520 template <typename VectorType> 1521 void 1522 initialize_dof_vector(VectorType & vec, 1523 const unsigned int dof_handler_index = 0) const; 1524 1545 template <typename Number2> 1546 void 1548 const unsigned int dof_handler_index = 0) const; 1549 1560 const std::shared_ptr<const Utilities::MPI::Partitioner> & 1561 get_vector_partitioner(const unsigned int dof_handler_index = 0) const; 1562 1566 const IndexSet & 1567 get_locally_owned_set(const unsigned int dof_handler_index = 0) const; 1568 1572 const IndexSet & 1573 get_ghost_set(const unsigned int dof_handler_index = 0) const; 1574 1584 const std::vector<unsigned int> & 1585 get_constrained_dofs(const unsigned int dof_handler_index = 0) const; 1586 1597 void 1598 renumber_dofs(std::vector<types::global_dof_index> &renumbering, 1599 const unsigned int dof_handler_index = 0); 1600 1602 1610 template <int spacedim> 1611 static bool 1613 1617 unsigned int 1619 1624 unsigned int 1625 n_base_elements(const unsigned int dof_handler_index) const; 1626 1634 unsigned int 1636 1640 DEAL_II_DEPRECATED unsigned int 1642 1652 unsigned int 1654 1661 unsigned int 1663 1671 unsigned int 1673 1682 unsigned int 1684 1689 unsigned int 1691 1699 get_boundary_id(const unsigned int macro_face) const; 1700 1705 std::array<types::boundary_id, VectorizedArrayType::size()> 1706 get_faces_by_cells_boundary_id(const unsigned int cell_batch_index, 1707 const unsigned int face_number) const; 1708 1713 const DoFHandler<dim> & 1714 get_dof_handler(const unsigned int dof_handler_index = 0) const; 1715 1726 template <typename DoFHandlerType> 1727 DEAL_II_DEPRECATED const DoFHandlerType & 1728 get_dof_handler(const unsigned int dof_handler_index = 0) const; 1729 1743 get_cell_iterator(const unsigned int cell_batch_index, 1744 const unsigned int lane_index, 1745 const unsigned int dof_handler_index = 0) const; 1746 1752 std::pair<int, int> 1753 get_cell_level_and_index(const unsigned int cell_batch_index, 1754 const unsigned int lane_index) const; 1755 1768 std::pair<typename DoFHandler<dim>::cell_iterator, unsigned int> 1769 get_face_iterator(const unsigned int face_batch_index, 1770 const unsigned int lane_index, 1771 const bool interior = true, 1772 const unsigned int fe_component = 0) const; 1773 1780 get_hp_cell_iterator(const unsigned int cell_batch_index, 1781 const unsigned int lane_index, 1782 const unsigned int dof_handler_index = 0) const; 1783 1796 bool 1797 at_irregular_cell(const unsigned int cell_batch_index) const; 1798 1802 DEAL_II_DEPRECATED unsigned int 1803 n_components_filled(const unsigned int cell_batch_number) const; 1804 1814 unsigned int 1815 n_active_entries_per_cell_batch(const unsigned int cell_batch_index) const; 1816 1826 unsigned int 1827 n_active_entries_per_face_batch(const unsigned int face_batch_index) const; 1828 1832 unsigned int 1833 get_dofs_per_cell(const unsigned int dof_handler_index = 0, 1834 const unsigned int hp_active_fe_index = 0) const; 1835 1839 unsigned int 1840 get_n_q_points(const unsigned int quad_index = 0, 1841 const unsigned int hp_active_fe_index = 0) const; 1842 1847 unsigned int 1848 get_dofs_per_face(const unsigned int dof_handler_index = 0, 1849 const unsigned int hp_active_fe_index = 0) const; 1850 1855 unsigned int 1856 get_n_q_points_face(const unsigned int quad_index = 0, 1857 const unsigned int hp_active_fe_index = 0) const; 1858 1862 const Quadrature<dim> & 1863 get_quadrature(const unsigned int quad_index = 0, 1864 const unsigned int hp_active_fe_index = 0) const; 1865 1869 const Quadrature<dim - 1> & 1870 get_face_quadrature(const unsigned int quad_index = 0, 1871 const unsigned int hp_active_fe_index = 0) const; 1872 1879 unsigned int 1880 get_cell_category(const unsigned int cell_batch_index) const; 1881 1886 std::pair<unsigned int, unsigned int> 1887 get_face_category(const unsigned int macro_face) const; 1888 1892 bool 1894 1899 bool 1901 1906 unsigned int 1908 1913 std::size_t 1915 1920 template <typename StreamType> 1921 void 1922 print_memory_consumption(StreamType &out) const; 1923 1928 void 1929 print(std::ostream &out) const; 1930 1932 1944 1945 /* 1946 * Return geometry-dependent information on the cells. 1947 */ 1948 const internal::MatrixFreeFunctions:: 1949 MappingInfo<dim, Number, VectorizedArrayType> & 1951 1956 get_dof_info(const unsigned int dof_handler_index_component = 0) const; 1957 1961 unsigned int 1963 1968 const Number * 1969 constraint_pool_begin(const unsigned int pool_index) const; 1970 1976 const Number * 1977 constraint_pool_end(const unsigned int pool_index) const; 1978 1983 get_shape_info(const unsigned int dof_handler_index_component = 0, 1984 const unsigned int quad_index = 0, 1985 const unsigned int fe_base_element = 0, 1986 const unsigned int hp_active_fe_index = 0, 1987 const unsigned int hp_active_quad_index = 0) const; 1988 1993 VectorizedArrayType::size()> & 1994 get_face_info(const unsigned int face_batch_index) const; 1995 1996 2004 2020 2024 void 2026 2038 2042 void 2044 const AlignedVector<Number> *memory) const; 2045 2047 2048private: 2053 template <typename number2, int q_dim> 2054 void 2056 const std::shared_ptr<hp::MappingCollection<dim>> & mapping, 2057 const std::vector<const DoFHandler<dim, dim> *> & dof_handlers, 2058 const std::vector<const AffineConstraints<number2> *> &constraint, 2059 const std::vector<IndexSet> & locally_owned_set, 2060 const std::vector<hp::QCollection<q_dim>> & quad, 2061 const AdditionalData & additional_data); 2062 2069 template <typename number2> 2070 void 2072 const std::vector<const AffineConstraints<number2> *> &constraint, 2073 const std::vector<IndexSet> & locally_owned_set, 2074 const AdditionalData & additional_data); 2075 2079 void 2081 const std::vector<const DoFHandler<dim, dim> *> &dof_handlers, 2082 const AdditionalData & additional_data); 2083 2087 std::vector<SmartPointer<const DoFHandler<dim>>> dof_handlers; 2088 2093 std::vector<internal::MatrixFreeFunctions::DoFInfo> dof_info; 2094 2101 std::vector<Number> constraint_pool_data; 2102 2107 std::vector<unsigned int> constraint_pool_row_index; 2108 2115 2121 2128 std::vector<std::pair<unsigned int, unsigned int>> cell_level_index; 2129 2130 2138 2145 2150 internal::MatrixFreeFunctions::FaceInfo<VectorizedArrayType::size()> 2152 2157 2162 2171 std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>> 2173 2178 mutable std::list<std::pair<bool, AlignedVector<Number>>> 2180 2184 unsigned int mg_level; 2185}; 2186 2187 2188 2189/*----------------------- Inline functions ----------------------------------*/ 2190 2191#ifndef DOXYGEN 2192 2193 2194 2195template <int dim, typename Number, typename VectorizedArrayType> 2196template <typename VectorType> 2197inline void 2199 VectorType & vec, 2200 const unsigned int comp) const 2201{ 2203 vec.reinit(dof_info[comp].vector_partitioner->size()); 2204} 2205 2206 2207 2208template <int dim, typename Number, typename VectorizedArrayType> 2209template <typename Number2> 2210inline void 2213 const unsigned int comp) const 2214{ 2216 vec.reinit(dof_info[comp].vector_partitioner, task_info.communicator_sm); 2217} 2218 2219 2220 2221template <int dim, typename Number, typename VectorizedArrayType> 2222inline const std::shared_ptr<const Utilities::MPI::Partitioner> & 2224 const unsigned int comp) const 2225{ 2227 return dof_info[comp].vector_partitioner; 2228} 2229 2230 2231 2232template <int dim, typename Number, typename VectorizedArrayType> 2233inline const std::vector<unsigned int> & 2235 const unsigned int comp) const 2236{ 2238 return dof_info[comp].constrained_dofs; 2239} 2240 2241 2242 2243template <int dim, typename Number, typename VectorizedArrayType> 2244inline unsigned int 2246{ 2247 AssertDimension(dof_handlers.size(), dof_info.size()); 2248 return dof_handlers.size(); 2249} 2250 2251 2252 2253template <int dim, typename Number, typename VectorizedArrayType> 2254inline unsigned int 2256 const unsigned int dof_no) const 2257{ 2258 AssertDimension(dof_handlers.size(), dof_info.size()); 2259 AssertIndexRange(dof_no, dof_handlers.size()); 2260 return dof_handlers[dof_no]->get_fe().n_base_elements(); 2261} 2262 2263 2264 2265template <int dim, typename Number, typename VectorizedArrayType> 2268{ 2269 return task_info; 2270} 2271 2272 2273 2274template <int dim, typename Number, typename VectorizedArrayType> 2275inline unsigned int 2277{ 2278 return *(task_info.cell_partition_data.end() - 2); 2279} 2280 2281 2282 2283template <int dim, typename Number, typename VectorizedArrayType> 2284inline unsigned int 2286{ 2288} 2289 2290 2291 2292template <int dim, typename Number, typename VectorizedArrayType> 2293inline unsigned int 2295{ 2296 return *(task_info.cell_partition_data.end() - 2); 2297} 2298 2299 2300 2301template <int dim, typename Number, typename VectorizedArrayType> 2302inline unsigned int 2304{ 2305 return *(task_info.cell_partition_data.end() - 1) - 2306 *(task_info.cell_partition_data.end() - 2); 2307} 2308 2309 2310 2311template <int dim, typename Number, typename VectorizedArrayType> 2312inline unsigned int 2314{ 2315 if (task_info.face_partition_data.size() == 0) 2316 return 0; 2317 return task_info.face_partition_data.back(); 2318} 2319 2320 2321 2322template <int dim, typename Number, typename VectorizedArrayType> 2323inline unsigned int 2325{ 2326 if (task_info.face_partition_data.size() == 0) 2327 return 0; 2328 return task_info.boundary_partition_data.back() - 2330} 2331 2332 2333 2334template <int dim, typename Number, typename VectorizedArrayType> 2335inline unsigned int 2337{ 2338 if (task_info.face_partition_data.size() == 0) 2339 return 0; 2340 return face_info.faces.size() - task_info.boundary_partition_data.back(); 2341} 2342 2343 2344 2345template <int dim, typename Number, typename VectorizedArrayType> 2346inline types::boundary_id 2348 const unsigned int macro_face) const 2349{ 2350 Assert(macro_face >= task_info.boundary_partition_data[0] && 2351 macro_face < task_info.boundary_partition_data.back(), 2352 ExcIndexRange(macro_face, 2355 return types::boundary_id(face_info.faces[macro_face].exterior_face_no); 2356} 2357 2358 2359 2360template <int dim, typename Number, typename VectorizedArrayType> 2361inline std::array<types::boundary_id, VectorizedArrayType::size()> 2363 const unsigned int cell_batch_index, 2364 const unsigned int face_number) const 2365{ 2366 AssertIndexRange(cell_batch_index, n_cell_batches()); 2370 std::array<types::boundary_id, VectorizedArrayType::size()> result; 2371 result.fill(numbers::invalid_boundary_id); 2372 for (unsigned int v = 0; 2373 v < n_active_entries_per_cell_batch(cell_batch_index); 2374 ++v) 2375 result[v] = 2376 face_info.cell_and_face_boundary_id(cell_batch_index, face_number, v); 2377 return result; 2378} 2379 2380 2381 2382template <int dim, typename Number, typename VectorizedArrayType> 2383inline const internal::MatrixFreeFunctions:: 2384 MappingInfo<dim, Number, VectorizedArrayType> & 2386{ 2387 return mapping_info; 2388} 2389 2390 2391 2392template <int dim, typename Number, typename VectorizedArrayType> 2395 const unsigned int dof_index) const 2396{ 2397 AssertIndexRange(dof_index, n_components()); 2398 return dof_info[dof_index]; 2399} 2400 2401 2402 2403template <int dim, typename Number, typename VectorizedArrayType> 2404inline unsigned int 2406{ 2407 return constraint_pool_row_index.size() - 1; 2408} 2409 2410 2411 2412template <int dim, typename Number, typename VectorizedArrayType> 2413inline const Number * 2415 const unsigned int row) const 2416{ 2418 return constraint_pool_data.empty() ? 2419 nullptr : 2421} 2422 2423 2424 2425template <int dim, typename Number, typename VectorizedArrayType> 2426inline const Number * 2428 const unsigned int row) const 2429{ 2431 return constraint_pool_data.empty() ? 2432 nullptr : 2434} 2435 2436 2437 2438template <int dim, typename Number, typename VectorizedArrayType> 2439inline std::pair<unsigned int, unsigned int> 2441 const std::pair<unsigned int, unsigned int> &range, 2442 const unsigned int degree, 2443 const unsigned int dof_handler_component) const 2444{ 2445 if (dof_info[dof_handler_component].cell_active_fe_index.empty()) 2446 { 2448 dof_info[dof_handler_component].fe_index_conversion.size(), 1); 2450 dof_info[dof_handler_component].fe_index_conversion[0].size(), 1); 2451 if (dof_info[dof_handler_component].fe_index_conversion[0][0] == degree) 2452 return range; 2453 else 2454 return {range.second, range.second}; 2455 } 2456 2457 const unsigned int fe_index = 2458 dof_info[dof_handler_component].fe_index_from_degree(0, degree); 2459 if (fe_index >= dof_info[dof_handler_component].max_fe_index) 2460 return {range.second, range.second}; 2461 else 2463 fe_index, 2464 dof_handler_component); 2465} 2466 2467 2468 2469template <int dim, typename Number, typename VectorizedArrayType> 2470inline bool 2472 const unsigned int cell_batch_index) const 2473{ 2474 AssertIndexRange(cell_batch_index, task_info.cell_partition_data.back()); 2475 return VectorizedArrayType::size() > 1 && 2476 cell_level_index[(cell_batch_index + 1) * VectorizedArrayType::size() - 2477 1] == cell_level_index[(cell_batch_index + 1) * 2478 VectorizedArrayType::size() - 2479 2]; 2480} 2481 2482 2483 2484template <int dim, typename Number, typename VectorizedArrayType> 2485unsigned int 2487{ 2488 return shape_info.size(2); 2489} 2490 2491 2492template <int dim, typename Number, typename VectorizedArrayType> 2493unsigned int 2495 const std::pair<unsigned int, unsigned int> range) const 2496{ 2497 const auto &fe_indices = dof_info[0].cell_active_fe_index; 2498 2499 if (fe_indices.empty() == true) 2500 return 0; 2501 2502 const auto index = fe_indices[range.first]; 2503 2504 for (unsigned int i = range.first; i < range.second; ++i) 2505 AssertDimension(index, fe_indices[i]); 2506 2507 return index; 2508} 2509 2510 2511 2512template <int dim, typename Number, typename VectorizedArrayType> 2513unsigned int 2515 const std::pair<unsigned int, unsigned int> range, 2516 const bool is_interior_face) const 2517{ 2518 const auto &fe_indices = dof_info[0].cell_active_fe_index; 2519 2520 if (fe_indices.empty() == true) 2521 return 0; 2522 2523 if (is_interior_face) 2524 { 2525 const unsigned int index = 2526 fe_indices[face_info.faces[range.first].cells_interior[0] / 2527 VectorizedArrayType::size()]; 2528 2529 for (unsigned int i = range.first; i < range.second; ++i) 2530 AssertDimension(index, 2531 fe_indices[face_info.faces[i].cells_interior[0] / 2532 VectorizedArrayType::size()]); 2533 2534 return index; 2535 } 2536 else 2537 { 2538 const unsigned int index = 2539 fe_indices[face_info.faces[range.first].cells_exterior[0] / 2540 VectorizedArrayType::size()]; 2541 2542 for (unsigned int i = range.first; i < range.second; ++i) 2543 AssertDimension(index, 2544 fe_indices[face_info.faces[i].cells_exterior[0] / 2545 VectorizedArrayType::size()]); 2546 2547 return index; 2548 } 2549} 2550 2551 2552 2553template <int dim, typename Number, typename VectorizedArrayType> 2554inline unsigned int 2556 const unsigned int cell_batch_index) const 2557{ 2558 return n_active_entries_per_cell_batch(cell_batch_index); 2559} 2560 2561 2562 2563template <int dim, typename Number, typename VectorizedArrayType> 2564inline unsigned int 2566 const unsigned int cell_batch_index) const 2567{ 2568 AssertIndexRange(cell_batch_index, task_info.cell_partition_data.back()); 2569 unsigned int n_lanes = VectorizedArrayType::size(); 2570 while (n_lanes > 1 && 2571 cell_level_index[cell_batch_index * VectorizedArrayType::size() + 2572 n_lanes - 1] == 2573 cell_level_index[cell_batch_index * VectorizedArrayType::size() + 2574 n_lanes - 2]) 2575 --n_lanes; 2576 AssertIndexRange(n_lanes - 1, VectorizedArrayType::size()); 2577 return n_lanes; 2578} 2579 2580 2581 2582template <int dim, typename Number, typename VectorizedArrayType> 2583inline unsigned int 2585 const unsigned int face_batch_index) const 2586{ 2587 AssertIndexRange(face_batch_index, face_info.faces.size()); 2588 unsigned int n_lanes = VectorizedArrayType::size(); 2589 while (n_lanes > 1 && 2590 face_info.faces[face_batch_index].cells_interior[n_lanes - 1] == 2592 --n_lanes; 2593 AssertIndexRange(n_lanes - 1, VectorizedArrayType::size()); 2594 return n_lanes; 2595} 2596 2597 2598 2599template <int dim, typename Number, typename VectorizedArrayType> 2600inline unsigned int 2602 const unsigned int dof_handler_index, 2603 const unsigned int active_fe_index) const 2604{ 2605 return dof_info[dof_handler_index].dofs_per_cell[active_fe_index]; 2606} 2607 2608 2609 2610template <int dim, typename Number, typename VectorizedArrayType> 2611inline unsigned int 2613 const unsigned int quad_index, 2614 const unsigned int active_fe_index) const 2615{ 2616 AssertIndexRange(quad_index, mapping_info.cell_data.size()); 2617 return mapping_info.cell_data[quad_index] 2618 .descriptor[active_fe_index] 2619 .n_q_points; 2620} 2621 2622 2623 2624template <int dim, typename Number, typename VectorizedArrayType> 2625inline unsigned int 2627 const unsigned int dof_handler_index, 2628 const unsigned int active_fe_index) const 2629{ 2630 return dof_info[dof_handler_index].dofs_per_face[active_fe_index]; 2631} 2632 2633 2634 2635template <int dim, typename Number, typename VectorizedArrayType> 2636inline unsigned int 2638 const unsigned int quad_index, 2639 const unsigned int active_fe_index) const 2640{ 2641 AssertIndexRange(quad_index, mapping_info.face_data.size()); 2642 return mapping_info.face_data[quad_index] 2643 .descriptor[active_fe_index] 2644 .n_q_points; 2645} 2646 2647 2648 2649template <int dim, typename Number, typename VectorizedArrayType> 2650inline const IndexSet & 2652 const unsigned int dof_handler_index) const 2653{ 2654 return dof_info[dof_handler_index].vector_partitioner->locally_owned_range(); 2655} 2656 2657 2658 2659template <int dim, typename Number, typename VectorizedArrayType> 2660inline const IndexSet & 2662 const unsigned int dof_handler_index) const 2663{ 2664 return dof_info[dof_handler_index].vector_partitioner->ghost_indices(); 2665} 2666 2667 2668 2669template <int dim, typename Number, typename VectorizedArrayType> 2672 const unsigned int dof_handler_index, 2673 const unsigned int index_quad, 2674 const unsigned int index_fe, 2675 const unsigned int active_fe_index, 2676 const unsigned int active_quad_index) const 2677{ 2678 AssertIndexRange(dof_handler_index, dof_info.size()); 2679 const unsigned int ind = 2680 dof_info[dof_handler_index].global_base_element_offset + index_fe; 2681 AssertIndexRange(ind, shape_info.size(0)); 2682 AssertIndexRange(index_quad, shape_info.size(1)); 2683 AssertIndexRange(active_fe_index, shape_info.size(2)); 2684 AssertIndexRange(active_quad_index, shape_info.size(3)); 2685 return shape_info(ind, index_quad, active_fe_index, active_quad_index); 2686} 2687 2688 2689 2690template <int dim, typename Number, typename VectorizedArrayType> 2692 VectorizedArrayType::size()> & 2694 const unsigned int macro_face) const 2695{ 2696 AssertIndexRange(macro_face, face_info.faces.size()); 2697 return face_info.faces[macro_face]; 2698} 2699 2700 2701 2702template <int dim, typename Number, typename VectorizedArrayType> 2703inline const Table<3, unsigned int> & 2705 const 2706{ 2708} 2709 2710 2711 2712template <int dim, typename Number, typename VectorizedArrayType> 2713inline const Quadrature<dim> & 2715 const unsigned int quad_index, 2716 const unsigned int active_fe_index) const 2717{ 2718 AssertIndexRange(quad_index, mapping_info.cell_data.size()); 2719 return mapping_info.cell_data[quad_index] 2720 .descriptor[active_fe_index] 2721 .quadrature; 2722} 2723 2724 2725 2726template <int dim, typename Number, typename VectorizedArrayType> 2727inline const Quadrature<dim - 1> & 2729 const unsigned int quad_index, 2730 const unsigned int active_fe_index) const 2731{ 2732 AssertIndexRange(quad_index, mapping_info.face_data.size()); 2733 return mapping_info.face_data[quad_index] 2734 .descriptor[active_fe_index] 2735 .quadrature; 2736} 2737 2738 2739 2740template <int dim, typename Number, typename VectorizedArrayType> 2741inline unsigned int 2743 const unsigned int cell_batch_index) const 2744{ 2745 AssertIndexRange(0, dof_info.size()); 2746 AssertIndexRange(cell_batch_index, dof_info[0].cell_active_fe_index.size()); 2747 if (dof_info[0].cell_active_fe_index.empty()) 2748 return 0; 2749 else 2750 return dof_info[0].cell_active_fe_index[cell_batch_index]; 2751} 2752 2753 2754 2755template <int dim, typename Number, typename VectorizedArrayType> 2756inline std::pair<unsigned int, unsigned int> 2758 const unsigned int macro_face) const 2759{ 2760 AssertIndexRange(macro_face, face_info.faces.size()); 2761 if (dof_info[0].cell_active_fe_index.empty()) 2762 return std::make_pair(0U, 0U); 2763 2764 std::pair<unsigned int, unsigned int> result; 2765 for (unsigned int v = 0; v < VectorizedArrayType::size() && 2766 face_info.faces[macro_face].cells_interior[v] != 2768 ++v) 2769 result.first = std::max( 2770 result.first, 2771 dof_info[0] 2772 .cell_active_fe_index[face_info.faces[macro_face].cells_interior[v]]); 2773 if (face_info.faces[macro_face].cells_exterior[0] != 2775 for (unsigned int v = 0; v < VectorizedArrayType::size() && 2776 face_info.faces[macro_face].cells_exterior[v] != 2778 ++v) 2779 result.second = std::max( 2780 result.first, 2781 dof_info[0] 2782 .cell_active_fe_index[face_info.faces[macro_face].cells_exterior[v]]); 2783 else 2784 result.second = numbers::invalid_unsigned_int; 2785 return result; 2786} 2787 2788 2789 2790template <int dim, typename Number, typename VectorizedArrayType> 2791inline bool 2793{ 2795} 2796 2797 2798 2799template <int dim, typename Number, typename VectorizedArrayType> 2800inline bool 2802{ 2804} 2805 2806 2807template <int dim, typename Number, typename VectorizedArrayType> 2808inline unsigned int 2810{ 2811 return mg_level; 2812} 2813 2814 2815 2816template <int dim, typename Number, typename VectorizedArrayType> 2819{ 2820 using list_type = 2821 std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>; 2822 list_type &data = scratch_pad.get(); 2823 for (typename list_type::iterator it = data.begin(); it != data.end(); ++it) 2824 if (it->first == false) 2825 { 2826 it->first = true; 2827 return &it->second; 2828 } 2829 data.emplace_front(true, AlignedVector<VectorizedArrayType>()); 2830 return &data.front().second; 2831} 2832 2833 2834 2835template <int dim, typename Number, typename VectorizedArrayType> 2836void 2838 const AlignedVector<VectorizedArrayType> *scratch) const 2839{ 2840 using list_type = 2841 std::list<std::pair<bool, AlignedVector<VectorizedArrayType>>>; 2842 list_type &data = scratch_pad.get(); 2843 for (typename list_type::iterator it = data.begin(); it != data.end(); ++it) 2844 if (&it->second == scratch) 2845 { 2846 Assert(it->first == true, ExcInternalError()); 2847 it->first = false; 2848 return; 2849 } 2850 AssertThrow(false, ExcMessage("Tried to release invalid scratch pad")); 2851} 2852 2853 2854 2855template <int dim, typename Number, typename VectorizedArrayType> 2859{ 2860 for (typename std::list<std::pair<bool, AlignedVector<Number>>>::iterator it = 2862 it != scratch_pad_non_threadsafe.end(); 2863 ++it) 2864 if (it->first == false) 2865 { 2866 it->first = true; 2867 return &it->second; 2868 } 2869 scratch_pad_non_threadsafe.push_front( 2870 std::make_pair(true, AlignedVector<Number>())); 2871 return &scratch_pad_non_threadsafe.front().second; 2872} 2873 2874 2875 2876template <int dim, typename Number, typename VectorizedArrayType> 2877void 2880 const AlignedVector<Number> *scratch) const 2881{ 2882 for (typename std::list<std::pair<bool, AlignedVector<Number>>>::iterator it = 2884 it != scratch_pad_non_threadsafe.end(); 2885 ++it) 2886 if (&it->second == scratch) 2887 { 2888 Assert(it->first == true, ExcInternalError()); 2889 it->first = false; 2890 return; 2891 } 2892 AssertThrow(false, ExcMessage("Tried to release invalid scratch pad")); 2893} 2894 2895 2896 2897// ------------------------------ reinit functions --------------------------- 2898 2899namespace internal 2900{ 2901 namespace MatrixFreeImplementation 2902 { 2903 template <int dim, int spacedim> 2904 inline std::vector<IndexSet> 2905 extract_locally_owned_index_sets( 2906 const std::vector<const ::DoFHandler<dim, spacedim> *> &dofh, 2907 const unsigned int level) 2908 { 2909 std::vector<IndexSet> locally_owned_set; 2910 locally_owned_set.reserve(dofh.size()); 2911 for (unsigned int j = 0; j < dofh.size(); j++) 2913 locally_owned_set.push_back(dofh[j]->locally_owned_dofs()); 2914 else 2915 locally_owned_set.push_back(dofh[j]->locally_owned_mg_dofs(level)); 2916 return locally_owned_set; 2917 } 2918 } // namespace MatrixFreeImplementation 2919} // namespace internal 2920 2921 2922 2923template <int dim, typename Number, typename VectorizedArrayType> 2924template <typename QuadratureType, typename number2> 2925void 2927 const DoFHandler<dim> & dof_handler, 2928 const AffineConstraints<number2> &constraints_in, 2929 const QuadratureType & quad, 2931 &additional_data) 2932{ 2933 std::vector<const DoFHandler<dim, dim> *> dof_handlers; 2934 std::vector<const AffineConstraints<number2> *> constraints; 2935 std::vector<QuadratureType> quads; 2936 2937 dof_handlers.push_back(&dof_handler); 2938 constraints.push_back(&constraints_in); 2939 quads.push_back(quad); 2940 2941 std::vector<IndexSet> locally_owned_sets = 2942 internal::MatrixFreeImplementation::extract_locally_owned_index_sets( 2943 dof_handlers, additional_data.mg_level); 2944 2945 std::vector<hp::QCollection<dim>> quad_hp; 2946 quad_hp.emplace_back(quad); 2947 2951 constraints, 2952 locally_owned_sets, 2953 quad_hp, 2954 additional_data); 2955} 2956 2957 2958 2959template <int dim, typename Number, typename VectorizedArrayType> 2960template <typename QuadratureType, typename number2, typename MappingType> 2961void 2963 const MappingType & mapping, 2964 const DoFHandler<dim> & dof_handler, 2965 const AffineConstraints<number2> &constraints_in, 2966 const QuadratureType & quad, 2968 &additional_data) 2969{ 2970 std::vector<const DoFHandler<dim, dim> *> dof_handlers; 2971 std::vector<const AffineConstraints<number2> *> constraints; 2972 2973 dof_handlers.push_back(&dof_handler); 2974 constraints.push_back(&constraints_in); 2975 2976 std::vector<IndexSet> locally_owned_sets = 2977 internal::MatrixFreeImplementation::extract_locally_owned_index_sets( 2978 dof_handlers, additional_data.mg_level); 2979 2980 std::vector<hp::QCollection<dim>> quad_hp; 2981 quad_hp.emplace_back(quad); 2982 2983 internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), 2985 constraints, 2986 locally_owned_sets, 2987 quad_hp, 2988 additional_data); 2989} 2990 2991 2992 2993template <int dim, typename Number, typename VectorizedArrayType> 2994template <typename QuadratureType, typename number2> 2995void 2997 const std::vector<const DoFHandler<dim> *> & dof_handler, 2998 const std::vector<const AffineConstraints<number2> *> &constraint, 2999 const std::vector<QuadratureType> & quad, 3001 &additional_data) 3002{ 3003 std::vector<IndexSet> locally_owned_set = 3004 internal::MatrixFreeImplementation::extract_locally_owned_index_sets( 3005 dof_handler, additional_data.mg_level); 3006 std::vector<hp::QCollection<dim>> quad_hp; 3007 for (unsigned int q = 0; q < quad.size(); ++q) 3008 quad_hp.emplace_back(quad[q]); 3009 3012 dof_handler, 3013 constraint, 3014 locally_owned_set, 3015 quad_hp, 3016 additional_data); 3017} 3018 3019 3020 3021template <int dim, typename Number, typename VectorizedArrayType> 3022template <typename QuadratureType, 3023 typename number2, 3024 typename DoFHandlerType, 3025 typename MappingType> 3026void 3028 const MappingType & mapping, 3029 const std::vector<const DoFHandlerType *> & dof_handler, 3030 const std::vector<const AffineConstraints<number2> *> &constraint, 3031 const std::vector<QuadratureType> & quad, 3032 const AdditionalData & additional_data) 3033{ 3034 static_assert(dim == DoFHandlerType::dimension, 3035 "Dimension dim not equal to DoFHandlerType::dimension."); 3036 3037 std::vector<const DoFHandler<dim> *> dof_handlers; 3038 3039 for (const auto dh : dof_handler) 3040 dof_handlers.push_back(dh); 3041 3042 this->reinit(mapping, dof_handlers, constraint, quad, additional_data); 3043} 3044 3045 3046 3047template <int dim, typename Number, typename VectorizedArrayType> 3048template <typename QuadratureType, typename number2> 3049void 3051 const std::vector<const DoFHandler<dim> *> & dof_handler, 3052 const std::vector<const AffineConstraints<number2> *> &constraint, 3053 const QuadratureType & quad, 3055 &additional_data) 3056{ 3057 std::vector<IndexSet> locally_owned_set = 3058 internal::MatrixFreeImplementation::extract_locally_owned_index_sets( 3059 dof_handler, additional_data.mg_level); 3060 std::vector<hp::QCollection<dim>> quad_hp; 3061 quad_hp.emplace_back(quad); 3062 3065 dof_handler, 3066 constraint, 3067 locally_owned_set, 3068 quad_hp, 3069 additional_data); 3070} 3071 3072 3073 3074template <int dim, typename Number, typename VectorizedArrayType> 3075template <typename QuadratureType, typename number2, typename DoFHandlerType> 3076void 3078 const std::vector<const DoFHandlerType *> & dof_handler, 3079 const std::vector<const AffineConstraints<number2> *> &constraint, 3080 const std::vector<QuadratureType> & quad, 3081 const AdditionalData & additional_data) 3082{ 3083 static_assert(dim == DoFHandlerType::dimension, 3084 "Dimension dim not equal to DoFHandlerType::dimension."); 3085 3086 std::vector<const DoFHandler<dim> *> dof_handlers; 3087 3088 for (const auto dh : dof_handler) 3089 dof_handlers.push_back(dof_handler); 3090 3091 this->reinit(dof_handlers, constraint, quad, additional_data); 3092} 3093 3094 3095 3096template <int dim, typename Number, typename VectorizedArrayType> 3097template <typename QuadratureType, typename number2, typename MappingType> 3098void 3100 const MappingType & mapping, 3101 const std::vector<const DoFHandler<dim> *> & dof_handler, 3102 const std::vector<const AffineConstraints<number2> *> &constraint, 3103 const QuadratureType & quad, 3105 &additional_data) 3106{ 3107 std::vector<IndexSet> locally_owned_set = 3108 internal::MatrixFreeImplementation::extract_locally_owned_index_sets( 3109 dof_handler, additional_data.mg_level); 3110 std::vector<hp::QCollection<dim>> quad_hp; 3111 quad_hp.emplace_back(quad); 3112 3113 internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), 3114 dof_handler, 3115 constraint, 3116 locally_owned_set, 3117 quad_hp, 3118 additional_data); 3119} 3120 3121 3122 3123template <int dim, typename Number, typename VectorizedArrayType> 3124template <typename QuadratureType, typename number2, typename MappingType> 3125void 3127 const MappingType & mapping, 3128 const std::vector<const DoFHandler<dim> *> & dof_handler, 3129 const std::vector<const AffineConstraints<number2> *> &constraint, 3130 const std::vector<QuadratureType> & quad, 3132 &additional_data) 3133{ 3134 std::vector<IndexSet> locally_owned_set = 3135 internal::MatrixFreeImplementation::extract_locally_owned_index_sets( 3136 dof_handler, additional_data.mg_level); 3137 std::vector<hp::QCollection<dim>> quad_hp; 3138 for (unsigned int q = 0; q < quad.size(); ++q) 3139 quad_hp.emplace_back(quad[q]); 3140 3141 internal_reinit(std::make_shared<hp::MappingCollection<dim>>(mapping), 3142 dof_handler, 3143 constraint, 3144 locally_owned_set, 3145 quad_hp, 3146 additional_data); 3147} 3148 3149 3150 3151template <int dim, typename Number, typename VectorizedArrayType> 3152template <typename QuadratureType, 3153 typename number2, 3154 typename DoFHandlerType, 3155 typename MappingType> 3156void 3158 const MappingType & mapping, 3159 const std::vector<const DoFHandlerType *> & dof_handler, 3160 const std::vector<const AffineConstraints<number2> *> &constraint, 3161 const QuadratureType & quad, 3162 const AdditionalData & additional_data) 3163{ 3164 static_assert(dim == DoFHandlerType::dimension, 3165 "Dimension dim not equal to DoFHandlerType::dimension."); 3166 3167 std::vector<const DoFHandler<dim> *> dof_handlers; 3168 3169 for (const auto dh : dof_handler) 3170 dof_handlers.push_back(dof_handler); 3171 3172 this->reinit(mapping, dof_handlers, constraint, quad, additional_data); 3173} 3174 3175 3176 3177template <int dim, typename Number, typename VectorizedArrayType> 3178template <typename QuadratureType, typename number2, typename DoFHandlerType> 3179void 3181 const std::vector<const DoFHandlerType *> & dof_handler, 3182 const std::vector<const AffineConstraints<number2> *> &constraint, 3183 const QuadratureType & quad, 3184 const AdditionalData & additional_data) 3185{ 3186 static_assert(dim == DoFHandlerType::dimension, 3187 "Dimension dim not equal to DoFHandlerType::dimension."); 3188 3189 std::vector<const DoFHandler<dim> *> dof_handlers; 3190 3191 for (const auto dh : dof_handler) 3192 dof_handlers.push_back(dof_handler); 3193 3194 this->reinit(dof_handlers, constraint, quad, additional_data); 3195} 3196 3197 3198 3199// ------------------------------ implementation of loops -------------------- 3200 3201// internal helper functions that define how to call MPI data exchange 3202// functions: for generic vectors, do nothing at all. For distributed vectors, 3203// call update_ghost_values_start function and so on. If we have collections 3204// of vectors, just do the individual functions of the components. In order to 3205// keep ghost values consistent (whether we are in read or write mode), we 3206// also reset the values at the end. the whole situation is a bit complicated 3207// by the fact that we need to treat block vectors differently, which use some 3208// additional helper functions to select the blocks and template magic. 3209namespace internal 3210{ 3214 template <int dim, typename Number, typename VectorizedArrayType> 3215 struct VectorDataExchange 3216 { 3217 // A shift for the MPI messages to reduce the risk for accidental 3218 // interaction with other open communications that a user program might 3219 // set up (parallel vectors support unfinished communication). We let 3220 // the other vectors use the first 20 assigned numbers and start the 3221 // matrix-free communication. 3222 static constexpr unsigned int channel_shift = 20; 3223 3224 3225 3230 VectorDataExchange( 3231 const ::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free, 3232 const typename ::MatrixFree<dim, Number, VectorizedArrayType>:: 3233 DataAccessOnFaces vector_face_access, 3234 const unsigned int n_components) 3235 : matrix_free(matrix_free) 3236 , vector_face_access( 3237 matrix_free.get_task_info().face_partition_data.empty() ? 3238 ::MatrixFree<dim, Number, VectorizedArrayType>:: 3239 DataAccessOnFaces::unspecified : 3240 vector_face_access) 3241 , ghosts_were_set(false) 3242# ifdef DEAL_II_WITH_MPI 3243 , tmp_data(n_components) 3244 , requests(n_components) 3245# endif 3246 { 3247 (void)n_components; 3248 if (this->vector_face_access != 3250 DataAccessOnFaces::unspecified) 3251 for (unsigned int c = 0; c < matrix_free.n_components(); ++c) 3253 matrix_free.get_dof_info(c).vector_exchanger_face_variants.size(), 3254 5); 3255 } 3256 3257 3258 3262 ~VectorDataExchange() // NOLINT 3263 { 3264# ifdef DEAL_II_WITH_MPI 3265 for (unsigned int i = 0; i < tmp_data.size(); ++i) 3266 if (tmp_data[i] != nullptr) 3267 matrix_free.release_scratch_data_non_threadsafe(tmp_data[i]); 3268# endif 3269 } 3270 3271 3272 3277 template <typename VectorType> 3278 unsigned int 3279 find_vector_in_mf(const VectorType &vec, 3280 const bool check_global_compatibility = true) const 3281 { 3282 // case 1: vector was set up with MatrixFree::initialize_dof_vector() 3283 for (unsigned int c = 0; c < matrix_free.n_components(); ++c) 3284 if (vec.get_partitioner().get() == 3285 matrix_free.get_dof_info(c).vector_partitioner.get()) 3286 return c; 3287 3288 // case 2: user provided own partitioner (compatibility mode) 3289 for (unsigned int c = 0; c < matrix_free.n_components(); ++c) 3290 if (check_global_compatibility ? 3291 vec.get_partitioner()->is_globally_compatible( 3292 *matrix_free.get_dof_info(c).vector_partitioner) : 3293 vec.get_partitioner()->is_compatible( 3294 *matrix_free.get_dof_info(c).vector_partitioner)) 3295 return c; 3296 3297 Assert(false, 3298 ExcNotImplemented("Could not find partitioner that fits vector")); 3299 3301 } 3302 3303 3304 3310 get_partitioner(const unsigned int mf_component) const 3311 { 3312 AssertDimension(matrix_free.get_dof_info(mf_component) 3313 .vector_exchanger_face_variants.size(), 3314 5); 3315 if (vector_face_access == 3318 return *matrix_free.get_dof_info(mf_component) 3319 .vector_exchanger_face_variants[0]; 3320 else if (vector_face_access == 3323 return *matrix_free.get_dof_info(mf_component) 3324 .vector_exchanger_face_variants[1]; 3325 else if (vector_face_access == 3328 return *matrix_free.get_dof_info(mf_component) 3329 .vector_exchanger_face_variants[2]; 3330 else if (vector_face_access == 3332 DataAccessOnFaces::values_all_faces) 3333 return *matrix_free.get_dof_info(mf_component) 3334 .vector_exchanger_face_variants[3]; 3335 else if (vector_face_access == 3337 DataAccessOnFaces::gradients_all_faces) 3338 return *matrix_free.get_dof_info(mf_component) 3339 .vector_exchanger_face_variants[4]; 3340 else 3341 return *matrix_free.get_dof_info(mf_component).vector_exchanger.get(); 3342 } 3343 3344 3345 3349 template <typename VectorType, 3350 typename std::enable_if<is_serial_or_dummy<VectorType>::value, 3351 VectorType>::type * = nullptr> 3352 void 3353 update_ghost_values_start(const unsigned int /*component_in_block_vector*/, 3354 const VectorType & /*vec*/) 3355 {} 3356 3357 3362 template <typename VectorType, 3363 typename std::enable_if< 3364 !has_update_ghost_values_start<VectorType>::value && 3365 !is_serial_or_dummy<VectorType>::value, 3366 VectorType>::type * = nullptr> 3367 void 3368 update_ghost_values_start(const unsigned int component_in_block_vector, 3369 const VectorType & vec) 3370 { 3371 (void)component_in_block_vector; 3372 bool ghosts_set = vec.has_ghost_elements(); 3373 if (ghosts_set) 3374 ghosts_were_set = true; 3375 3376 vec.update_ghost_values(); 3377 } 3378 3379 3380 3386 template <typename VectorType, 3387 typename std::enable_if< 3388 has_update_ghost_values_start<VectorType>::value && 3389 !has_exchange_on_subset<VectorType>::value, 3390 VectorType>::type * = nullptr> 3391 void 3392 update_ghost_values_start(const unsigned int component_in_block_vector, 3393 const VectorType & vec) 3394 { 3395 (void)component_in_block_vector; 3396 bool ghosts_set = vec.has_ghost_elements(); 3397 if (ghosts_set) 3398 ghosts_were_set = true; 3399 3400 vec.update_ghost_values_start(component_in_block_vector + channel_shift); 3401 } 3402 3403 3404 3411 template <typename VectorType, 3412 typename std::enable_if< 3413 has_update_ghost_values_start<VectorType>::value && 3414 has_exchange_on_subset<VectorType>::value, 3415 VectorType>::type * = nullptr> 3416 void 3417 update_ghost_values_start(const unsigned int component_in_block_vector, 3418 const VectorType & vec) 3419 { 3420 static_assert( 3421 std::is_same<Number, typename VectorType::value_type>::value, 3422 "Type mismatch between VectorType and VectorDataExchange"); 3423 (void)component_in_block_vector; 3424 bool ghosts_set = vec.has_ghost_elements(); 3425 if (ghosts_set) 3426 ghosts_were_set = true; 3427 3428 if (vec.size() != 0) 3429 { 3430# ifdef DEAL_II_WITH_MPI 3431 const unsigned int mf_component = find_vector_in_mf(vec); 3432 3433 const auto &part = get_partitioner(mf_component); 3434 3435 if (part.n_ghost_indices() == 0 && part.n_import_indices() == 0 && 3436 part.n_import_sm_procs() == 0) 3437 return; 3438 3439 tmp_data[component_in_block_vector] = 3440 matrix_free.acquire_scratch_data_non_threadsafe(); 3441 tmp_data[component_in_block_vector]->resize_fast( 3442 part.n_import_indices()); 3443 AssertDimension(requests.size(), tmp_data.size()); 3444 3445 part.export_to_ghosted_array_start( 3446 component_in_block_vector * 2 + channel_shift, 3447 ArrayView<const Number>(vec.begin(), part.locally_owned_size()), 3448 vec.shared_vector_data(), 3449 ArrayView<Number>(const_cast<Number *>(vec.begin()) + 3450 part.locally_owned_size(), 3451 matrix_free.get_dof_info(mf_component) 3452 .vector_partitioner->n_ghost_indices()), 3453 ArrayView<Number>(tmp_data[component_in_block_vector]->begin(), 3454 part.n_import_indices()), 3455 this->requests[component_in_block_vector]); 3456# endif 3457 } 3458 } 3459 3460 3461 3466 template < 3467 typename VectorType, 3468 typename std::enable_if<!has_update_ghost_values_start<VectorType>::value, 3469 VectorType>::type * = nullptr> 3470 void 3471 update_ghost_values_finish(const unsigned int /*component_in_block_vector*/, 3472 const VectorType & /*vec*/) 3473 {} 3474 3475 3476 3482 template <typename VectorType, 3483 typename std::enable_if< 3484 has_update_ghost_values_start<VectorType>::value && 3485 !has_exchange_on_subset<VectorType>::value, 3486 VectorType>::type * = nullptr> 3487 void 3488 update_ghost_values_finish(const unsigned int component_in_block_vector, 3489 const VectorType & vec) 3490 { 3491 (void)component_in_block_vector; 3492 vec.update_ghost_values_finish(); 3493 } 3494 3495 3496 3503 template <typename VectorType, 3504 typename std::enable_if< 3505 has_update_ghost_values_start<VectorType>::value && 3506 has_exchange_on_subset<VectorType>::value, 3507 VectorType>::type * = nullptr> 3508 void 3509 update_ghost_values_finish(const unsigned int component_in_block_vector, 3510 const VectorType & vec) 3511 { 3512 static_assert( 3513 std::is_same<Number, typename VectorType::value_type>::value, 3514 "Type mismatch between VectorType and VectorDataExchange"); 3515 (void)component_in_block_vector; 3516 3517 if (vec.size() != 0) 3518 { 3519# ifdef DEAL_II_WITH_MPI 3520 AssertIndexRange(component_in_block_vector, tmp_data.size()); 3521 AssertDimension(requests.size(), tmp_data.size()); 3522 3523 const unsigned int mf_component = find_vector_in_mf(vec); 3524 3525 const auto &part = get_partitioner(mf_component); 3526 3527 if (part.n_ghost_indices() != 0 || part.n_import_indices() != 0 || 3528 part.n_import_sm_procs() != 0) 3529 { 3530 part.export_to_ghosted_array_finish( 3531 ArrayView<const Number>(vec.begin(), part.locally_owned_size()), 3532 vec.shared_vector_data(), 3533 ArrayView<Number>(const_cast<Number *>(vec.begin()) + 3534 part.locally_owned_size(), 3535 matrix_free.get_dof_info(mf_component) 3536 .vector_partitioner->n_ghost_indices()), 3537 this->requests[component_in_block_vector]); 3538 3539 matrix_free.release_scratch_data_non_threadsafe( 3540 tmp_data[component_in_block_vector]); 3541 tmp_data[component_in_block_vector] = nullptr; 3542 } 3543# endif 3544 } 3545 // let vector know that ghosts are being updated and we can read from 3546 // them 3547 vec.set_ghost_state(true); 3548 } 3549 3550 3551 3555 template <typename VectorType, 3556 typename std::enable_if<is_serial_or_dummy<VectorType>::value, 3557 VectorType>::type * = nullptr> 3558 void 3559 compress_start(const unsigned int /*component_in_block_vector*/, 3560 VectorType & /*vec*/) 3561 {} 3562 3563 3564 3569 template <typename VectorType, 3570 typename std::enable_if<!has_compress_start<VectorType>::value && 3571 !is_serial_or_dummy<VectorType>::value, 3572 VectorType>::type * = nullptr> 3573 void 3574 compress_start(const unsigned int component_in_block_vector, 3575 VectorType & vec) 3576 { 3577 (void)component_in_block_vector; 3578 Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); 3579 vec.compress(::VectorOperation::add); 3580 } 3581 3582 3583 3589 template < 3590 typename VectorType, 3591 typename std::enable_if<has_compress_start<VectorType>::value && 3592 !has_exchange_on_subset<VectorType>::value, 3593 VectorType>::type * = nullptr> 3594 void 3595 compress_start(const unsigned int component_in_block_vector, 3596 VectorType & vec) 3597 { 3598 (void)component_in_block_vector; 3599 Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); 3600 vec.compress_start(component_in_block_vector + channel_shift); 3601 } 3602 3603 3604 3611 template < 3612 typename VectorType, 3613 typename std::enable_if<has_compress_start<VectorType>::value && 3614 has_exchange_on_subset<VectorType>::value, 3615 VectorType>::type * = nullptr> 3616 void 3617 compress_start(const unsigned int component_in_block_vector, 3618 VectorType & vec) 3619 { 3620 static_assert( 3621 std::is_same<Number, typename VectorType::value_type>::value, 3622 "Type mismatch between VectorType and VectorDataExchange"); 3623 (void)component_in_block_vector; 3624 Assert(vec.has_ghost_elements() == false, ExcNotImplemented()); 3625 3626 if (vec.size() != 0) 3627 { 3628# ifdef DEAL_II_WITH_MPI 3629 const unsigned int mf_component = find_vector_in_mf(vec); 3630 3631 const auto &part = get_partitioner(mf_component); 3632 3633 if (part.n_ghost_indices() == 0 && part.n_import_indices() == 0 && 3634 part.n_import_sm_procs() == 0) 3635 return; 3636 3637 tmp_data[component_in_block_vector] = 3638 matrix_free.acquire_scratch_data_non_threadsafe(); 3639 tmp_data[component_in_block_vector]->resize_fast( 3640 part.n_import_indices()); 3641 AssertDimension(requests.size(), tmp_data.size()); 3642 3643 part.import_from_ghosted_array_start( 3645 component_in_block_vector * 2 + channel_shift, 3646 ArrayView<Number>(vec.begin(), part.locally_owned_size()), 3647 vec.shared_vector_data(), 3648 ArrayView<Number>(vec.begin() + part.locally_owned_size(), 3649 matrix_free.get_dof_info(mf_component) 3650 .vector_partitioner->n_ghost_indices()), 3651 ArrayView<Number>(tmp_data[component_in_block_vector]->begin(), 3652 part.n_import_indices()), 3653 this->requests[component_in_block_vector]); 3654# endif 3655 } 3656 } 3657 3658 3659 3664 template <typename VectorType, 3665 typename std::enable_if<!has_compress_start<VectorType>::value, 3666 VectorType>::type * = nullptr> 3667 void 3668 compress_finish(const unsigned int /*component_in_block_vector*/, 3669 VectorType & /*vec*/) 3670 {} 3671 3672 3673 3679 template < 3680 typename VectorType, 3681 typename std::enable_if<has_compress_start<VectorType>::value && 3682 !has_exchange_on_subset<VectorType>::value, 3683 VectorType>::type * = nullptr> 3684 void 3685 compress_finish(const unsigned int component_in_block_vector, 3686 VectorType & vec) 3687 { 3688 (void)component_in_block_vector; 3689 vec.compress_finish(::VectorOperation::add); 3690 } 3691 3692 3693 3700 template < 3701 typename VectorType, 3702 typename std::enable_if<has_compress_start<VectorType>::value && 3703 has_exchange_on_subset<VectorType>::value, 3704 VectorType>::type * = nullptr> 3705 void 3706 compress_finish(const unsigned int component_in_block_vector, 3707 VectorType & vec) 3708 { 3709 static_assert( 3710 std::is_same<Number, typename VectorType::value_type>::value, 3711 "Type mismatch between VectorType and VectorDataExchange"); 3712 (void)component_in_block_vector; 3713 if (vec.size() != 0) 3714 { 3715# ifdef DEAL_II_WITH_MPI 3716 AssertIndexRange(component_in_block_vector, tmp_data.size()); 3717 AssertDimension(requests.size(), tmp_data.size()); 3718 3719 const unsigned int mf_component = find_vector_in_mf(vec); 3720 3721 const auto &part = get_partitioner(mf_component); 3722 3723 if (part.n_ghost_indices() != 0 || part.n_import_indices() != 0 || 3724 part.n_import_sm_procs() != 0) 3725 { 3726 part.import_from_ghosted_array_finish( 3728 ArrayView<Number>(vec.begin(), part.locally_owned_size()), 3729 vec.shared_vector_data(), 3730 ArrayView<Number>(vec.begin() + part.locally_owned_size(), 3731 matrix_free.get_dof_info(mf_component) 3732 .vector_partitioner->n_ghost_indices()), 3734 tmp_data[component_in_block_vector]->begin(), 3735 part.n_import_indices()), 3736 this->requests[component_in_block_vector]); 3737 3738 matrix_free.release_scratch_data_non_threadsafe( 3739 tmp_data[component_in_block_vector]); 3740 tmp_data[component_in_block_vector] = nullptr; 3741 } 3742 3744 MPI_Barrier(matrix_free.get_task_info().communicator_sm); 3745# endif 3746 } 3747 } 3748 3749 3750 3754 template <typename VectorType, 3755 typename std::enable_if<is_serial_or_dummy<VectorType>::value, 3756 VectorType>::type * = nullptr> 3757 void 3758 reset_ghost_values(const VectorType & /*vec*/) const 3759 {} 3760 3761 3762 3767 template < 3768 typename VectorType, 3769 typename std::enable_if<!has_exchange_on_subset<VectorType>::value && 3770 !is_serial_or_dummy<VectorType>::value, 3771 VectorType>::type * = nullptr> 3772 void 3773 reset_ghost_values(const VectorType &vec) const 3774 { 3775 if (ghosts_were_set == true) 3776 return; 3777 3778 vec.zero_out_ghost_values(); 3779 } 3780 3781 3782 3788 template <typename VectorType, 3789 typename std::enable_if<has_exchange_on_subset<VectorType>::value, 3790 VectorType>::type * = nullptr> 3791 void 3792 reset_ghost_values(const VectorType &vec) const 3793 { 3794 static_assert( 3795 std::is_same<Number, typename VectorType::value_type>::value, 3796 "Type mismatch between VectorType and VectorDataExchange"); 3797 if (ghosts_were_set == true) 3798 return; 3799 3800 if (vec.size() != 0) 3801 { 3802# ifdef DEAL_II_WITH_MPI 3803 AssertDimension(requests.size(), tmp_data.size()); 3804 3805 const unsigned int mf_component = find_vector_in_mf(vec); 3806 3807 const auto &part = get_partitioner(mf_component); 3808 3809 if (part.n_ghost_indices() > 0) 3810 { 3811 part.reset_ghost_values(ArrayView<Number>( 3813 .begin() + 3814 part.locally_owned_size(), 3815 matrix_free.get_dof_info(mf_component) 3816 .vector_partitioner->n_ghost_indices())); 3817 } 3818 3819# endif 3820 } 3821 // let vector know that it's not ghosted anymore 3822 vec.set_ghost_state(false); 3823 } 3824 3825 3826 3832 template <typename VectorType, 3833 typename std::enable_if<has_exchange_on_subset<VectorType>::value, 3834 VectorType>::type * = nullptr> 3835 void 3836 zero_vector_region(const unsigned int range_index, VectorType &vec) const 3837 { 3838 static_assert( 3839 std::is_same<Number, typename VectorType::value_type>::value, 3840 "Type mismatch between VectorType and VectorDataExchange"); 3841 if (range_index == numbers::invalid_unsigned_int) 3842 vec = Number(); 3843 else 3844 { 3845 const unsigned int mf_component = find_vector_in_mf(vec, false); 3847 matrix_free.get_dof_info(mf_component); 3848 Assert(dof_info.vector_zero_range_list_index.empty() == false, 3850 3851 Assert(vec.partitioners_are_compatible(*dof_info.vector_partitioner), 3853 AssertIndexRange(range_index, 3854 dof_info.vector_zero_range_list_index.size() - 1); 3855 for (unsigned int id = 3856 dof_info.vector_zero_range_list_index[range_index]; 3857 id != dof_info.vector_zero_range_list_index[range_index + 1]; 3858 ++id) 3859 std::memset(vec.begin() + dof_info.vector_zero_range_list[id].first, 3860 0, 3861 (dof_info.vector_zero_range_list[id].second - 3862 dof_info.vector_zero_range_list[id].first) * 3863 sizeof(Number)); 3864 } 3865 } 3866 3867 3868 3874 template < 3875 typename VectorType, 3876 typename std::enable_if<!has_exchange_on_subset<VectorType>::value, 3877 VectorType>::type * = nullptr, 3878 typename VectorType::value_type * = nullptr> 3879 void 3880 zero_vector_region(const unsigned int range_index, VectorType &vec) const 3881 { 3882 if (range_index == numbers::invalid_unsigned_int || range_index == 0) 3883 vec = typename VectorType::value_type(); 3884 } 3885 3886 3887 3892 void 3893 zero_vector_region(const unsigned int, ...) const 3894 { 3895 Assert(false, 3896 ExcNotImplemented("Zeroing is only implemented for vector types " 3897 "which provide VectorType::value_type")); 3898 } 3899 3900 3901 3902 const ::MatrixFree<dim, Number, VectorizedArrayType> &matrix_free; 3903 const typename ::MatrixFree<dim, Number, VectorizedArrayType>:: 3904 DataAccessOnFaces vector_face_access; 3905 bool ghosts_were_set; 3906# ifdef DEAL_II_WITH_MPI 3907 std::vector<AlignedVector<Number> *> tmp_data; 3908 std::vector<std::vector<MPI_Request>> requests; 3909# endif 3910 }; // VectorDataExchange 3911 3912 template <typename VectorStruct> 3913 unsigned int 3914 n_components(const VectorStruct &vec); 3915 3916 template <typename VectorStruct> 3917 unsigned int 3918 n_components_block(const VectorStruct &vec, 3919 std::integral_constant<bool, true>) 3920 { 3921 unsigned int components = 0; 3922 for (unsigned int bl = 0; bl < vec.n_blocks(); ++bl) 3923 components += n_components(vec.block(bl)); 3924 return components; 3925 } 3926 3927 template <typename VectorStruct> 3928 unsigned int 3929 n_components_block(const VectorStruct &, std::integral_constant<bool, false>) 3930 { 3931 return 1; 3932 } 3933 3934 template <typename VectorStruct> 3935 unsigned int 3936 n_components(const VectorStruct &vec) 3937 { 3938 return n_components_block( 3939 vec, std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); 3940 } 3941 3942 template <typename VectorStruct> 3943 inline unsigned int 3944 n_components(const std::vector<VectorStruct> &vec) 3945 { 3946 unsigned int components = 0; 3947 for (unsigned int comp = 0; comp < vec.size(); comp++) 3948 components += n_components_block( 3949 vec[comp], 3950 std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); 3951 return components; 3952 } 3953 3954 template <typename VectorStruct> 3955 inline unsigned int 3956 n_components(const std::vector<VectorStruct *> &vec) 3957 { 3958 unsigned int components = 0; 3959 for (unsigned int comp = 0; comp < vec.size(); comp++) 3960 components += n_components_block( 3961 *vec[comp], 3962 std::integral_constant<bool, IsBlockVector<VectorStruct>::value>()); 3963 return components; 3964 } 3965 3966 3967 3968 // A helper function to identify block vectors with many components where we 3969 // should not try to overlap computations and communication because there 3970 // would be too many outstanding communication requests. 3971 3972 // default value for vectors that do not have communication_block_size 3973 template < 3974 typename VectorStruct, 3975 typename std::enable_if<!has_communication_block_size<VectorStruct>::value, 3976 VectorStruct>::type * = nullptr> 3977 constexpr unsigned int 3978 get_communication_block_size(const VectorStruct &) 3979 { 3981 } 3982 3983 3984 3985 template < 3986 typename VectorStruct, 3987 typename std::enable_if<has_communication_block_size<VectorStruct>::value, 3988 VectorStruct>::type * = nullptr> 3989 constexpr unsigned int 3990 get_communication_block_size(const VectorStruct &) 3991 { 3992 return VectorStruct::communication_block_size; 3993 } 3994 3995 3996 3997 // -------------------------------------------------------------------------- 3998 // below we have wrappers to distinguish between block and non-block vectors. 3999 // -------------------------------------------------------------------------- 4000 4001 // 4002 // update_ghost_values_start 4003 // 4004 4005 // update_ghost_values for block vectors 4006 template <int dim, 4007 typename VectorStruct, 4008 typename Number, 4009 typename VectorizedArrayType, 4010 typename std::enable_if<IsBlockVector<VectorStruct>::value, 4011 VectorStruct>::type * = nullptr> 4012 void 4013 update_ghost_values_start( 4014 const VectorStruct & vec, 4015 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4016 const unsigned int channel = 0) 4017 { 4018 if (get_communication_block_size(vec) < vec.n_blocks()) 4019 { 4020 // don't forget to set ghosts_were_set, that otherwise happens 4021 // inside VectorDataExchange::update_ghost_values_start() 4022 exchanger.ghosts_were_set = vec.has_ghost_elements(); 4023 vec.update_ghost_values(); 4024 } 4025 else 4026 { 4027 for (unsigned int i = 0; i < vec.n_blocks(); ++i) 4028 update_ghost_values_start(vec.block(i), exchanger, channel + i); 4029 } 4030 } 4031 4032 4033 4034 // update_ghost_values for non-block vectors 4035 template <int dim, 4036 typename VectorStruct, 4037 typename Number, 4038 typename VectorizedArrayType, 4039 typename std::enable_if<!IsBlockVector<VectorStruct>::value, 4040 VectorStruct>::type * = nullptr> 4041 void 4042 update_ghost_values_start( 4043 const VectorStruct & vec, 4044 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4045 const unsigned int channel = 0) 4046 { 4047 exchanger.update_ghost_values_start(channel, vec); 4048 } 4049 4050 4051 4052 // update_ghost_values_start() for vector of vectors 4053 template <int dim, 4054 typename VectorStruct, 4055 typename Number, 4056 typename VectorizedArrayType> 4057 inline void 4058 update_ghost_values_start( 4059 const std::vector<VectorStruct> & vec, 4060 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4061 { 4062 unsigned int component_index = 0; 4063 for (unsigned int comp = 0; comp < vec.size(); comp++) 4064 { 4065 update_ghost_values_start(vec[comp], exchanger, component_index); 4066 component_index += n_components(vec[comp]); 4067 } 4068 } 4069 4070 4071 4072 // update_ghost_values_start() for vector of pointers to vectors 4073 template <int dim, 4074 typename VectorStruct, 4075 typename Number, 4076 typename VectorizedArrayType> 4077 inline void 4078 update_ghost_values_start( 4079 const std::vector<VectorStruct *> & vec, 4080 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4081 { 4082 unsigned int component_index = 0; 4083 for (unsigned int comp = 0; comp < vec.size(); comp++) 4084 { 4085 update_ghost_values_start(*vec[comp], exchanger, component_index); 4086 component_index += n_components(*vec[comp]); 4087 } 4088 } 4089 4090 4091 4092 // 4093 // update_ghost_values_finish 4094 // 4095 4096 // for block vectors 4097 template <int dim, 4098 typename VectorStruct, 4099 typename Number, 4100 typename VectorizedArrayType, 4101 typename std::enable_if<IsBlockVector<VectorStruct>::value, 4102 VectorStruct>::type * = nullptr> 4103 void 4104 update_ghost_values_finish( 4105 const VectorStruct & vec, 4106 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4107 const unsigned int channel = 0) 4108 { 4109 if (get_communication_block_size(vec) < vec.n_blocks()) 4110 { 4111 // do nothing, everything has already been completed in the _start() 4112 // call 4113 } 4114 else 4115 for (unsigned int i = 0; i < vec.n_blocks(); ++i) 4116 update_ghost_values_finish(vec.block(i), exchanger, channel + i); 4117 } 4118 4119 4120 4121 // for non-block vectors 4122 template <int dim, 4123 typename VectorStruct, 4124 typename Number, 4125 typename VectorizedArrayType, 4126 typename std::enable_if<!IsBlockVector<VectorStruct>::value, 4127 VectorStruct>::type * = nullptr> 4128 void 4129 update_ghost_values_finish( 4130 const VectorStruct & vec, 4131 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4132 const unsigned int channel = 0) 4133 { 4134 exchanger.update_ghost_values_finish(channel, vec); 4135 } 4136 4137 4138 4139 // for vector of vectors 4140 template <int dim, 4141 typename VectorStruct, 4142 typename Number, 4143 typename VectorizedArrayType> 4144 inline void 4145 update_ghost_values_finish( 4146 const std::vector<VectorStruct> & vec, 4147 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4148 { 4149 unsigned int component_index = 0; 4150 for (unsigned int comp = 0; comp < vec.size(); comp++) 4151 { 4152 update_ghost_values_finish(vec[comp], exchanger, component_index); 4153 component_index += n_components(vec[comp]); 4154 } 4155 } 4156 4157 4158 4159 // for vector of pointers to vectors 4160 template <int dim, 4161 typename VectorStruct, 4162 typename Number, 4163 typename VectorizedArrayType> 4164 inline void 4165 update_ghost_values_finish( 4166 const std::vector<VectorStruct *> & vec, 4167 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4168 { 4169 unsigned int component_index = 0; 4170 for (unsigned int comp = 0; comp < vec.size(); comp++) 4171 { 4172 update_ghost_values_finish(*vec[comp], exchanger, component_index); 4173 component_index += n_components(*vec[comp]); 4174 } 4175 } 4176 4177 4178 4179 // 4180 // compress_start 4181 // 4182 4183 // for block vectors 4184 template <int dim, 4185 typename VectorStruct, 4186 typename Number, 4187 typename VectorizedArrayType, 4188 typename std::enable_if<IsBlockVector<VectorStruct>::value, 4189 VectorStruct>::type * = nullptr> 4190 inline void 4191 compress_start( 4192 VectorStruct & vec, 4193 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4194 const unsigned int channel = 0) 4195 { 4196 if (get_communication_block_size(vec) < vec.n_blocks()) 4197 vec.compress(::VectorOperation::add); 4198 else 4199 for (unsigned int i = 0; i < vec.n_blocks(); ++i) 4200 compress_start(vec.block(i), exchanger, channel + i); 4201 } 4202 4203 4204 4205 // for non-block vectors 4206 template <int dim, 4207 typename VectorStruct, 4208 typename Number, 4209 typename VectorizedArrayType, 4210 typename std::enable_if<!IsBlockVector<VectorStruct>::value, 4211 VectorStruct>::type * = nullptr> 4212 inline void 4213 compress_start( 4214 VectorStruct & vec, 4215 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4216 const unsigned int channel = 0) 4217 { 4218 exchanger.compress_start(channel, vec); 4219 } 4220 4221 4222 4223 // for std::vector of vectors 4224 template <int dim, 4225 typename VectorStruct, 4226 typename Number, 4227 typename VectorizedArrayType> 4228 inline void 4229 compress_start( 4230 std::vector<VectorStruct> & vec, 4231 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4232 { 4233 unsigned int component_index = 0; 4234 for (unsigned int comp = 0; comp < vec.size(); comp++) 4235 { 4236 compress_start(vec[comp], exchanger, component_index); 4237 component_index += n_components(vec[comp]); 4238 } 4239 } 4240 4241 4242 4243 // for std::vector of pointer to vectors 4244 template <int dim, 4245 typename VectorStruct, 4246 typename Number, 4247 typename VectorizedArrayType> 4248 inline void 4249 compress_start( 4250 std::vector<VectorStruct *> & vec, 4251 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4252 { 4253 unsigned int component_index = 0; 4254 for (unsigned int comp = 0; comp < vec.size(); comp++) 4255 { 4256 compress_start(*vec[comp], exchanger, component_index); 4257 component_index += n_components(*vec[comp]); 4258 } 4259 } 4260 4261 4262 4263 // 4264 // compress_finish 4265 // 4266 4267 // for block vectors 4268 template <int dim, 4269 typename VectorStruct, 4270 typename Number, 4271 typename VectorizedArrayType, 4272 typename std::enable_if<IsBlockVector<VectorStruct>::value, 4273 VectorStruct>::type * = nullptr> 4274 inline void 4275 compress_finish( 4276 VectorStruct & vec, 4277 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4278 const unsigned int channel = 0) 4279 { 4280 if (get_communication_block_size(vec) < vec.n_blocks()) 4281 { 4282 // do nothing, everything has already been completed in the _start() 4283 // call 4284 } 4285 else 4286 for (unsigned int i = 0; i < vec.n_blocks(); ++i) 4287 compress_finish(vec.block(i), exchanger, channel + i); 4288 } 4289 4290 4291 4292 // for non-block vectors 4293 template <int dim, 4294 typename VectorStruct, 4295 typename Number, 4296 typename VectorizedArrayType, 4297 typename std::enable_if<!IsBlockVector<VectorStruct>::value, 4298 VectorStruct>::type * = nullptr> 4299 inline void 4300 compress_finish( 4301 VectorStruct & vec, 4302 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger, 4303 const unsigned int channel = 0) 4304 { 4305 exchanger.compress_finish(channel, vec); 4306 } 4307 4308 4309 4310 // for std::vector of vectors 4311 template <int dim, 4312 typename VectorStruct, 4313 typename Number, 4314 typename VectorizedArrayType> 4315 inline void 4316 compress_finish( 4317 std::vector<VectorStruct> & vec, 4318 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4319 { 4320 unsigned int component_index = 0; 4321 for (unsigned int comp = 0; comp < vec.size(); comp++) 4322 { 4323 compress_finish(vec[comp], exchanger, component_index); 4324 component_index += n_components(vec[comp]); 4325 } 4326 } 4327 4328 4329 4330 // for std::vector of pointer to vectors 4331 template <int dim, 4332 typename VectorStruct, 4333 typename Number, 4334 typename VectorizedArrayType> 4335 inline void 4336 compress_finish( 4337 std::vector<VectorStruct *> & vec, 4338 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4339 { 4340 unsigned int component_index = 0; 4341 for (unsigned int comp = 0; comp < vec.size(); comp++) 4342 { 4343 compress_finish(*vec[comp], exchanger, component_index); 4344 component_index += n_components(*vec[comp]); 4345 } 4346 } 4347 4348 4349 4350 // 4351 // reset_ghost_values: 4352 // 4353 // if the input vector did not have ghosts imported, clear them here again 4354 // in order to avoid subsequent operations e.g. in linear solvers to work 4355 // with ghosts all the time 4356 // 4357 4358 // for block vectors 4359 template <int dim, 4360 typename VectorStruct, 4361 typename Number, 4362 typename VectorizedArrayType, 4363 typename std::enable_if<IsBlockVector<VectorStruct>::value, 4364 VectorStruct>::type * = nullptr> 4365 inline void 4366 reset_ghost_values( 4367 const VectorStruct & vec, 4368 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4369 { 4370 // return immediately if there is nothing to do. 4371 if (exchanger.ghosts_were_set == true) 4372 return; 4373 4374 for (unsigned int i = 0; i < vec.n_blocks(); ++i) 4375 reset_ghost_values(vec.block(i), exchanger); 4376 } 4377 4378 4379 4380 // for non-block vectors 4381 template <int dim, 4382 typename VectorStruct, 4383 typename Number, 4384 typename VectorizedArrayType, 4385 typename std::enable_if<!IsBlockVector<VectorStruct>::value, 4386 VectorStruct>::type * = nullptr> 4387 inline void 4388 reset_ghost_values( 4389 const VectorStruct & vec, 4390 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4391 { 4392 exchanger.reset_ghost_values(vec); 4393 } 4394 4395 4396 4397 // for std::vector of vectors 4398 template <int dim, 4399 typename VectorStruct, 4400 typename Number, 4401 typename VectorizedArrayType> 4402 inline void 4403 reset_ghost_values( 4404 const std::vector<VectorStruct> & vec, 4405 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4406 { 4407 // return immediately if there is nothing to do. 4408 if (exchanger.ghosts_were_set == true) 4409 return; 4410 4411 for (unsigned int comp = 0; comp < vec.size(); comp++) 4412 reset_ghost_values(vec[comp], exchanger); 4413 } 4414 4415 4416 4417 // for std::vector of pointer to vectors 4418 template <int dim, 4419 typename VectorStruct, 4420 typename Number, 4421 typename VectorizedArrayType> 4422 inline void 4423 reset_ghost_values( 4424 const std::vector<VectorStruct *> & vec, 4425 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4426 { 4427 // return immediately if there is nothing to do. 4428 if (exchanger.ghosts_were_set == true) 4429 return; 4430 4431 for (unsigned int comp = 0; comp < vec.size(); comp++) 4432 reset_ghost_values(*vec[comp], exchanger); 4433 } 4434 4435 4436 4437 // 4438 // zero_vector_region 4439 // 4440 4441 // for block vectors 4442 template <int dim, 4443 typename VectorStruct, 4444 typename Number, 4445 typename VectorizedArrayType, 4446 typename std::enable_if<IsBlockVector<VectorStruct>::value, 4447 VectorStruct>::type * = nullptr> 4448 inline void 4449 zero_vector_region( 4450 const unsigned int range_index, 4451 VectorStruct & vec, 4452 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4453 { 4454 for (unsigned int i = 0; i < vec.n_blocks(); ++i) 4455 exchanger.zero_vector_region(range_index, vec.block(i)); 4456 } 4457 4458 4459 4460 // for non-block vectors 4461 template <int dim, 4462 typename VectorStruct, 4463 typename Number, 4464 typename VectorizedArrayType, 4465 typename std::enable_if<!IsBlockVector<VectorStruct>::value, 4466 VectorStruct>::type * = nullptr> 4467 inline void 4468 zero_vector_region( 4469 const unsigned int range_index, 4470 VectorStruct & vec, 4471 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4472 { 4473 exchanger.zero_vector_region(range_index, vec); 4474 } 4475 4476 4477 4478 // for std::vector of vectors 4479 template <int dim, 4480 typename VectorStruct, 4481 typename Number, 4482 typename VectorizedArrayType> 4483 inline void 4484 zero_vector_region( 4485 const unsigned int range_index, 4486 std::vector<VectorStruct> & vec, 4487 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4488 { 4489 for (unsigned int comp = 0; comp < vec.size(); comp++) 4490 zero_vector_region(range_index, vec[comp], exchanger); 4491 } 4492 4493 4494 4495 // for std::vector of pointers to vectors 4496 template <int dim, 4497 typename VectorStruct, 4498 typename Number, 4499 typename VectorizedArrayType> 4500 inline void 4501 zero_vector_region( 4502 const unsigned int range_index, 4503 std::vector<VectorStruct *> & vec, 4504 VectorDataExchange<dim, Number, VectorizedArrayType> &exchanger) 4505 { 4506 for (unsigned int comp = 0; comp < vec.size(); comp++) 4507 zero_vector_region(range_index, *vec[comp], exchanger); 4508 } 4509 4510 4511 4512 namespace MatrixFreeFunctions 4513 { 4514 // struct to select between a const interface and a non-const interface 4515 // for MFWorker 4516 template <typename, typename, typename, typename, bool> 4517 struct InterfaceSelector 4518 {}; 4519 4520 // Version for constant functions 4521 template <typename MF, 4522 typename InVector, 4523 typename OutVector, 4524 typename Container> 4525 struct InterfaceSelector<MF, InVector, OutVector, Container, true> 4526 { 4527 using function_type = void (Container::*)( 4528 const MF &, 4529 OutVector &, 4530 const InVector &, 4531 const std::pair<unsigned int, unsigned int> &) const; 4532 }; 4533 4534 // Version for non-constant functions 4535 template <typename MF, 4536 typename InVector, 4537 typename OutVector, 4538 typename Container> 4539 struct InterfaceSelector<MF, InVector, OutVector, Container, false> 4540 { 4541 using function_type = 4542 void (Container::*)(const MF &, 4543 OutVector &, 4544 const InVector &, 4545 const std::pair<unsigned int, unsigned int> &); 4546 }; 4547 } // namespace MatrixFreeFunctions 4548 4549 4550 4551 // A implementation class for the worker object that runs the various 4552 // operations we want to perform during the matrix-free loop 4553 template <typename MF, 4554 typename InVector, 4555 typename OutVector, 4556 typename Container, 4557 bool is_constant> 4558 class MFWorker : public MFWorkerInterface 4559 { 4560 public: 4561 // An alias to make the arguments further down more readable 4562 using function_type = typename MatrixFreeFunctions:: 4563 InterfaceSelector<MF, InVector, OutVector, Container, is_constant>:: 4564 function_type; 4565 4566 // constructor, binds all the arguments to this class 4567 MFWorker(const MF & matrix_free, 4568 const InVector & src, 4569 OutVector & dst, 4570 const bool zero_dst_vector_setting, 4571 const Container & container, 4572 function_type cell_function, 4573 function_type face_function, 4574 function_type boundary_function, 4575 const typename MF::DataAccessOnFaces src_vector_face_access = 4577 const typename MF::DataAccessOnFaces dst_vector_face_access = 4579 const std::function<void(const unsigned int, const unsigned int)> 4580 &operation_before_loop = {}, 4581 const std::function<void(const unsigned int, const unsigned int)> 4582 & operation_after_loop = {}, 4583 const unsigned int dof_handler_index_pre_post = 0) 4584 : matrix_free(matrix_free) 4585 , container(const_cast<Container &>(container)) 4586 , cell_function(cell_function) 4587 , face_function(face_function) 4588 , boundary_function(boundary_function) 4589 , src(src) 4590 , dst(dst) 4591 , src_data_exchanger(matrix_free, 4592 src_vector_face_access, 4593 n_components(src)) 4594 , dst_data_exchanger(matrix_free, 4595 dst_vector_face_access, 4596 n_components(dst)) 4597 , src_and_dst_are_same(PointerComparison::equal(&src, &dst)) 4598 , zero_dst_vector_setting(zero_dst_vector_setting && 4599 !src_and_dst_are_same) 4600 , operation_before_loop(operation_before_loop) 4601 , operation_after_loop(operation_after_loop) 4602 , dof_handler_index_pre_post(dof_handler_index_pre_post) 4603 {} 4604 4605 // Runs the cell work. If no function is given, nothing is done 4606 virtual void 4607 cell(const std::pair<unsigned int, unsigned int> &cell_range) override 4608 { 4609 if (cell_function != nullptr && cell_range.second > cell_range.first) 4610 for (unsigned int i = 0; i < matrix_free.n_active_fe_indices(); ++i) 4611 { 4612 const auto cell_subrange = 4613 matrix_free.create_cell_subrange_hp_by_index(cell_range, i); 4614 4615 if (cell_subrange.second <= cell_subrange.first) 4616 continue; 4617 4618 (container.* 4619 cell_function)(matrix_free, this->dst, this->src, cell_subrange); 4620 } 4621 } 4622 4623 virtual void 4624 cell(const unsigned int range_index) override 4625 { 4626 process_range(cell_function, 4627 matrix_free.get_task_info().cell_partition_data_hp_ptr, 4628 matrix_free.get_task_info().cell_partition_data_hp, 4629 range_index); 4630 } 4631 4632 virtual void 4633 face(const unsigned int range_index) override 4634 { 4635 process_range(face_function, 4636 matrix_free.get_task_info().face_partition_data_hp_ptr, 4637 matrix_free.get_task_info().face_partition_data_hp, 4638 range_index); 4639 } 4640 4641 virtual void 4642 boundary(const unsigned int range_index) override 4643 { 4644 process_range(boundary_function, 4645 matrix_free.get_task_info().boundary_partition_data_hp_ptr, 4646 matrix_free.get_task_info().boundary_partition_data_hp, 4647 range_index); 4648 } 4649 4650 private: 4651 void 4652 process_range(const function_type & fu, 4653 const std::vector<unsigned int> &ptr, 4654 const std::vector<unsigned int> &data, 4655 const unsigned int range_index) 4656 { 4657 if (fu == nullptr) 4658 return; 4659 4660 for (unsigned int i = ptr[range_index]; i < ptr[range_index + 1]; ++i) 4661 (container.*fu)(matrix_free, 4662 this->dst, 4663 this->src, 4664 std::make_pair(data[2 * i], data[2 * i + 1])); 4665 } 4666 4667 public: 4668 // Starts the communication for the update ghost values operation. We 4669 // cannot call this update if ghost and destination are the same because 4670 // that would introduce spurious entries in the destination (there is also 4671 // the problem that reading from a vector that we also write to is usually 4672 // not intended in case there is overlap, but this is up to the 4673 // application code to decide and we cannot catch this case here). 4674 virtual void 4675 vector_update_ghosts_start() override 4676 { 4677 if (!src_and_dst_are_same) 4678 internal::update_ghost_values_start(src, src_data_exchanger); 4679 } 4680 4681 // Finishes the communication for the update ghost values operation 4682 virtual void 4683 vector_update_ghosts_finish() override 4684 { 4685 if (!src_and_dst_are_same) 4686 internal::update_ghost_values_finish(src, src_data_exchanger); 4687 } 4688 4689 // Starts the communication for the vector compress operation 4690 virtual void 4691 vector_compress_start() override 4692 { 4693 internal::compress_start(dst, dst_data_exchanger); 4694 } 4695 4696 // Finishes the communication for the vector compress operation 4697 virtual void 4698 vector_compress_finish() override 4699 { 4700 internal::compress_finish(dst, dst_data_exchanger); 4701 if (!src_and_dst_are_same) 4702 internal::reset_ghost_values(src, src_data_exchanger); 4703 } 4704 4705 // Zeros the given input vector 4706 virtual void 4707 zero_dst_vector_range(const unsigned int range_index) override 4708 { 4709 if (zero_dst_vector_setting) 4710 internal::zero_vector_region(range_index, dst, dst_data_exchanger); 4711 } 4712 4713 virtual void 4714 cell_loop_pre_range(const unsigned int range_index) override 4715 { 4716 if (operation_before_loop) 4717 { 4719 matrix_free.get_dof_info(dof_handler_index_pre_post); 4720 if (range_index == numbers::invalid_unsigned_int) 4721 { 4722 // Case with threaded loop -> currently no overlap implemented 4724 0U, 4725 dof_info.vector_partitioner->locally_owned_size(), 4726 operation_before_loop, 4728 } 4729 else 4730 { 4731 AssertIndexRange(range_index, 4732 dof_info.cell_loop_pre_list_index.size() - 1); 4733 for (unsigned int id = 4734 dof_info.cell_loop_pre_list_index[range_index]; 4735 id != dof_info.cell_loop_pre_list_index[range_index + 1]; 4736 ++id) 4737 operation_before_loop(dof_info.cell_loop_pre_list[id].first, 4738 dof_info.cell_loop_pre_list[id].second); 4739 } 4740 } 4741 } 4742 4743 virtual void 4744 cell_loop_post_range(const unsigned int range_index) override 4745 { 4746 if (operation_after_loop) 4747 { 4749 matrix_free.get_dof_info(dof_handler_index_pre_post); 4750 if (range_index == numbers::invalid_unsigned_int) 4751 { 4752 // Case with threaded loop -> currently no overlap implemented 4754 0U, 4755 dof_info.vector_partitioner->locally_owned_size(), 4756 operation_after_loop, 4758 } 4759 else 4760 { 4761 AssertIndexRange(range_index, 4762 dof_info.cell_loop_post_list_index.size() - 1); 4763 for (unsigned int id = 4764 dof_info.cell_loop_post_list_index[range_index]; 4765 id != dof_info.cell_loop_post_list_index[range_index + 1]; 4766 ++id) 4767 operation_after_loop(dof_info.cell_loop_post_list[id].first, 4768 dof_info.cell_loop_post_list[id].second); 4769 } 4770 } 4771 } 4772 4773 private: 4774 const MF & matrix_free; 4775 Container & container; 4776 function_type cell_function; 4777 function_type face_function; 4778 function_type boundary_function; 4779 4780 const InVector &src; 4781 OutVector & dst; 4782 VectorDataExchange<MF::dimension, 4783 typename MF::value_type, 4784 typename MF::vectorized_value_type> 4785 src_data_exchanger; 4786 VectorDataExchange<MF::dimension, 4787 typename MF::value_type, 4788 typename MF::vectorized_value_type> 4789 dst_data_exchanger; 4790 const bool src_and_dst_are_same; 4791 const bool zero_dst_vector_setting; 4792 const std::function<void(const unsigned int, const unsigned int)> 4793 operation_before_loop; 4794 const std::function<void(const unsigned int, const unsigned int)> 4795 operation_after_loop; 4796 const unsigned int dof_handler_index_pre_post; 4797 }; 4798 4799 4800 4805 template <class MF, typename InVector, typename OutVector> 4806 struct MFClassWrapper 4807 { 4808 using function_type = 4809 std::function<void(const MF &, 4810 OutVector &, 4811 const InVector &, 4812 const std::pair<unsigned int, unsigned int> &)>; 4813 4814 MFClassWrapper(const function_type cell, 4815 const function_type face, 4816 const function_type boundary) 4817 : cell(cell) 4818 , face(face) 4819 , boundary(boundary) 4820 {} 4821 4822 void 4823 cell_integrator(const MF & mf, 4824 OutVector & dst, 4825 const InVector & src, 4826 const std::pair<unsigned int, unsigned int> &range) const 4827 { 4828 if (cell) 4829 cell(mf, dst, src, range); 4830 } 4831 4832 void 4833 face_integrator(const MF & mf, 4834 OutVector & dst, 4835 const InVector & src, 4836 const std::pair<unsigned int, unsigned int> &range) const 4837 { 4838 if (face) 4839 face(mf, dst, src, range); 4840 } 4841 4842 void 4843 boundary_integrator( 4844 const MF & mf, 4845 OutVector & dst, 4846 const InVector & src, 4847 const std::pair<unsigned int, unsigned int> &range) const 4848 { 4849 if (boundary) 4850 boundary(mf, dst, src, range); 4851 } 4852 4853 const function_type cell; 4854 const function_type face; 4855 const function_type boundary; 4856 }; 4857 4858} // end of namespace internal 4859 4860 4861 4862template <int dim, typename Number, typename VectorizedArrayType> 4863template <typename OutVector, typename InVector> 4864inline void 4866 const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, 4867 OutVector &, 4868 const InVector &, 4869 const std::pair<unsigned int, unsigned int> &)> 4870 & cell_operation, 4871 OutVector & dst, 4872 const InVector &src, 4873 const bool zero_dst_vector) const 4874{ 4875 using Wrapper = 4876 internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, 4877 InVector, 4878 OutVector>; 4879 Wrapper wrap(cell_operation, nullptr, nullptr); 4880 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 4881 InVector, 4882 OutVector, 4883 Wrapper, 4884 true> 4885 worker(*this, 4886 src, 4887 dst, 4888 zero_dst_vector, 4889 wrap, 4890 &Wrapper::cell_integrator, 4891 &Wrapper::face_integrator, 4892 &Wrapper::boundary_integrator); 4893 4894 task_info.loop(worker); 4895} 4896 4897 4898 4899template <int dim, typename Number, typename VectorizedArrayType> 4900template <typename OutVector, typename InVector> 4901inline void 4903 const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, 4904 OutVector &, 4905 const InVector &, 4906 const std::pair<unsigned int, unsigned int> &)> 4907 & cell_operation, 4908 OutVector & dst, 4909 const InVector &src, 4910 const std::function<void(const unsigned int, const unsigned int)> 4911 &operation_before_loop, 4912 const std::function<void(const unsigned int, const unsigned int)> 4913 & operation_after_loop, 4914 const unsigned int dof_handler_index_pre_post) const 4915{ 4916 using Wrapper = 4917 internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, 4918 InVector, 4919 OutVector>; 4920 Wrapper wrap(cell_operation, nullptr, nullptr); 4921 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 4922 InVector, 4923 OutVector, 4924 Wrapper, 4925 true> 4926 worker(*this, 4927 src, 4928 dst, 4929 false, 4930 wrap, 4931 &Wrapper::cell_integrator, 4932 &Wrapper::face_integrator, 4933 &Wrapper::boundary_integrator, 4936 operation_before_loop, 4937 operation_after_loop, 4938 dof_handler_index_pre_post); 4939 4940 task_info.loop(worker); 4941} 4942 4943 4944 4945template <int dim, typename Number, typename VectorizedArrayType> 4946template <typename OutVector, typename InVector> 4947inline void 4949 const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, 4950 OutVector &, 4951 const InVector &, 4952 const std::pair<unsigned int, unsigned int> &)> 4953 &cell_operation, 4954 const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, 4955 OutVector &, 4956 const InVector &, 4957 const std::pair<unsigned int, unsigned int> &)> 4958 &face_operation, 4959 const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, 4960 OutVector &, 4961 const InVector &, 4962 const std::pair<unsigned int, unsigned int> &)> 4963 & boundary_operation, 4964 OutVector & dst, 4965 const InVector & src, 4966 const bool zero_dst_vector, 4967 const DataAccessOnFaces dst_vector_face_access, 4968 const DataAccessOnFaces src_vector_face_access) const 4969{ 4970 using Wrapper = 4971 internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, 4972 InVector, 4973 OutVector>; 4974 Wrapper wrap(cell_operation, face_operation, boundary_operation); 4975 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 4976 InVector, 4977 OutVector, 4978 Wrapper, 4979 true> 4980 worker(*this, 4981 src, 4982 dst, 4983 zero_dst_vector, 4984 wrap, 4985 &Wrapper::cell_integrator, 4986 &Wrapper::face_integrator, 4987 &Wrapper::boundary_integrator, 4988 src_vector_face_access, 4989 dst_vector_face_access); 4990 4991 task_info.loop(worker); 4992} 4993 4994 4995 4996template <int dim, typename Number, typename VectorizedArrayType> 4997template <typename CLASS, typename OutVector, typename InVector> 4998inline void 5000 void (CLASS::*function_pointer)( 5002 OutVector &, 5003 const InVector &, 5004 const std::pair<unsigned int, unsigned int> &) const, 5005 const CLASS * owning_class, 5006 OutVector & dst, 5007 const InVector &src, 5008 const bool zero_dst_vector) const 5009{ 5010 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5011 InVector, 5012 OutVector, 5013 CLASS, 5014 true> 5015 worker(*this, 5016 src, 5017 dst, 5018 zero_dst_vector, 5019 *owning_class, 5020 function_pointer, 5021 nullptr, 5022 nullptr); 5023 task_info.loop(worker); 5024} 5025 5026 5027 5028template <int dim, typename Number, typename VectorizedArrayType> 5029template <typename CLASS, typename OutVector, typename InVector> 5030inline void 5032 void (CLASS::*function_pointer)( 5034 OutVector &, 5035 const InVector &, 5036 const std::pair<unsigned int, unsigned int> &) const, 5037 const CLASS * owning_class, 5038 OutVector & dst, 5039 const InVector &src, 5040 const std::function<void(const unsigned int, const unsigned int)> 5041 &operation_before_loop, 5042 const std::function<void(const unsigned int, const unsigned int)> 5043 & operation_after_loop, 5044 const unsigned int dof_handler_index_pre_post) const 5045{ 5046 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5047 InVector, 5048 OutVector, 5049 CLASS, 5050 true> 5051 worker(*this, 5052 src, 5053 dst, 5054 false, 5055 *owning_class, 5056 function_pointer, 5057 nullptr, 5058 nullptr, 5061 operation_before_loop, 5062 operation_after_loop, 5063 dof_handler_index_pre_post); 5064 task_info.loop(worker); 5065} 5066 5067 5068 5069template <int dim, typename Number, typename VectorizedArrayType> 5070template <typename CLASS, typename OutVector, typename InVector> 5071inline void 5073 void (CLASS::*cell_operation)( 5075 OutVector &, 5076 const InVector &, 5077 const std::pair<unsigned int, unsigned int> &) const, 5078 void (CLASS::*face_operation)( 5080 OutVector &, 5081 const InVector &, 5082 const std::pair<unsigned int, unsigned int> &) const, 5083 void (CLASS::*boundary_operation)( 5085 OutVector &, 5086 const InVector &, 5087 const std::pair<unsigned int, unsigned int> &) const, 5088 const CLASS * owning_class, 5089 OutVector & dst, 5090 const InVector & src, 5091 const bool zero_dst_vector, 5092 const DataAccessOnFaces dst_vector_face_access, 5093 const DataAccessOnFaces src_vector_face_access) const 5094{ 5095 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5096 InVector, 5097 OutVector, 5098 CLASS, 5099 true> 5100 worker(*this, 5101 src, 5102 dst, 5103 zero_dst_vector, 5104 *owning_class, 5105 cell_operation, 5106 face_operation, 5107 boundary_operation, 5108 src_vector_face_access, 5109 dst_vector_face_access); 5110 task_info.loop(worker); 5111} 5112 5113 5114 5115template <int dim, typename Number, typename VectorizedArrayType> 5116template <typename CLASS, typename OutVector, typename InVector> 5117inline void 5119 void (CLASS::*function_pointer)( 5121 OutVector &, 5122 const InVector &, 5123 const std::pair<unsigned int, unsigned int> &), 5124 CLASS * owning_class, 5125 OutVector & dst, 5126 const InVector &src, 5127 const bool zero_dst_vector) const 5128{ 5129 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5130 InVector, 5131 OutVector, 5132 CLASS, 5133 false> 5134 worker(*this, 5135 src, 5136 dst, 5137 zero_dst_vector, 5138 *owning_class, 5139 function_pointer, 5140 nullptr, 5141 nullptr); 5142 task_info.loop(worker); 5143} 5144 5145 5146 5147template <int dim, typename Number, typename VectorizedArrayType> 5148template <typename CLASS, typename OutVector, typename InVector> 5149inline void 5151 void (CLASS::*function_pointer)( 5153 OutVector &, 5154 const InVector &, 5155 const std::pair<unsigned int, unsigned int> &), 5156 CLASS * owning_class, 5157 OutVector & dst, 5158 const InVector &src, 5159 const std::function<void(const unsigned int, const unsigned int)> 5160 &operation_before_loop, 5161 const std::function<void(const unsigned int, const unsigned int)> 5162 & operation_after_loop, 5163 const unsigned int dof_handler_index_pre_post) const 5164{ 5165 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5166 InVector, 5167 OutVector, 5168 CLASS, 5169 false> 5170 worker(*this, 5171 src, 5172 dst, 5173 false, 5174 *owning_class, 5175 function_pointer, 5176 nullptr, 5177 nullptr, 5180 operation_before_loop, 5181 operation_after_loop, 5182 dof_handler_index_pre_post); 5183 task_info.loop(worker); 5184} 5185 5186 5187 5188template <int dim, typename Number, typename VectorizedArrayType> 5189template <typename CLASS, typename OutVector, typename InVector> 5190inline void 5192 void (CLASS::*cell_operation)( 5194 OutVector &, 5195 const InVector &, 5196 const std::pair<unsigned int, unsigned int> &), 5197 void (CLASS::*face_operation)( 5199 OutVector &, 5200 const InVector &, 5201 const std::pair<unsigned int, unsigned int> &), 5202 void (CLASS::*boundary_operation)( 5204 OutVector &, 5205 const InVector &, 5206 const std::pair<unsigned int, unsigned int> &), 5207 CLASS * owning_class, 5208 OutVector & dst, 5209 const InVector & src, 5210 const bool zero_dst_vector, 5211 const DataAccessOnFaces dst_vector_face_access, 5212 const DataAccessOnFaces src_vector_face_access) const 5213{ 5214 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5215 InVector, 5216 OutVector, 5217 CLASS, 5218 false> 5219 worker(*this, 5220 src, 5221 dst, 5222 zero_dst_vector, 5223 *owning_class, 5224 cell_operation, 5225 face_operation, 5226 boundary_operation, 5227 src_vector_face_access, 5228 dst_vector_face_access); 5229 task_info.loop(worker); 5230} 5231 5232 5233 5234template <int dim, typename Number, typename VectorizedArrayType> 5235template <typename CLASS, typename OutVector, typename InVector> 5236inline void 5238 void (CLASS::*function_pointer)( 5240 OutVector &, 5241 const InVector &, 5242 const std::pair<unsigned int, unsigned int> &) const, 5243 const CLASS * owning_class, 5244 OutVector & dst, 5245 const InVector & src, 5246 const bool zero_dst_vector, 5247 const DataAccessOnFaces src_vector_face_access) const 5248{ 5249 auto src_vector_face_access_temp = src_vector_face_access; 5250 if (DataAccessOnFaces::gradients == src_vector_face_access_temp) 5251 src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; 5252 else if (DataAccessOnFaces::values == src_vector_face_access_temp) 5253 src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; 5254 5255 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5256 InVector, 5257 OutVector, 5258 CLASS, 5259 true> 5260 worker(*this, 5261 src, 5262 dst, 5263 zero_dst_vector, 5264 *owning_class, 5265 function_pointer, 5266 nullptr, 5267 nullptr, 5268 src_vector_face_access_temp, 5270 task_info.loop(worker); 5271} 5272 5273 5274 5275template <int dim, typename Number, typename VectorizedArrayType> 5276template <typename CLASS, typename OutVector, typename InVector> 5277inline void 5279 void (CLASS::*function_pointer)( 5281 OutVector &, 5282 const InVector &, 5283 const std::pair<unsigned int, unsigned int> &), 5284 CLASS * owning_class, 5285 OutVector & dst, 5286 const InVector & src, 5287 const bool zero_dst_vector, 5288 const DataAccessOnFaces src_vector_face_access) const 5289{ 5290 auto src_vector_face_access_temp = src_vector_face_access; 5291 if (DataAccessOnFaces::gradients == src_vector_face_access_temp) 5292 src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; 5293 else if (DataAccessOnFaces::values == src_vector_face_access_temp) 5294 src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; 5295 5296 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5297 InVector, 5298 OutVector, 5299 CLASS, 5300 false> 5301 worker(*this, 5302 src, 5303 dst, 5304 zero_dst_vector, 5305 *owning_class, 5306 function_pointer, 5307 nullptr, 5308 nullptr, 5309 src_vector_face_access_temp, 5311 task_info.loop(worker); 5312} 5313 5314 5315 5316template <int dim, typename Number, typename VectorizedArrayType> 5317template <typename OutVector, typename InVector> 5318inline void 5320 const std::function<void(const MatrixFree<dim, Number, VectorizedArrayType> &, 5321 OutVector &, 5322 const InVector &, 5323 const std::pair<unsigned int, unsigned int> &)> 5324 & cell_operation, 5325 OutVector & dst, 5326 const InVector & src, 5327 const bool zero_dst_vector, 5328 const DataAccessOnFaces src_vector_face_access) const 5329{ 5330 auto src_vector_face_access_temp = src_vector_face_access; 5331 if (DataAccessOnFaces::gradients == src_vector_face_access_temp) 5332 src_vector_face_access_temp = DataAccessOnFaces::gradients_all_faces; 5333 else if (DataAccessOnFaces::values == src_vector_face_access_temp) 5334 src_vector_face_access_temp = DataAccessOnFaces::values_all_faces; 5335 5336 using Wrapper = 5337 internal::MFClassWrapper<MatrixFree<dim, Number, VectorizedArrayType>, 5338 InVector, 5339 OutVector>; 5340 Wrapper wrap(cell_operation, nullptr, nullptr); 5341 5342 internal::MFWorker<MatrixFree<dim, Number, VectorizedArrayType>, 5343 InVector, 5344 OutVector, 5345 Wrapper, 5346 true> 5347 worker(*this, 5348 src, 5349 dst, 5350 zero_dst_vector, 5351 wrap, 5352 &Wrapper::cell_integrator, 5353 &Wrapper::face_integrator, 5354 &Wrapper::boundary_integrator, 5355 src_vector_face_access_temp, 5357 task_info.loop(worker); 5358} 5359 5360 5361#endif // ifndef DOXYGEN 5362 5363 5364 5366 5367#endif Abstract base class for mapping classes. Definition: mapping.h:304 unsigned int n_active_fe_indices() const std::pair< typename DoFHandler< dim >::cell_iterator, unsigned int > get_face_iterator(const unsigned int face_batch_index, const unsigned int lane_index, const bool interior=true, const unsigned int fe_component=0) const void loop_cell_centric(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &), CLASS *owning_class, OutVector &dst, const InVector &src, const bool zero_dst_vector=false, const DataAccessOnFaces src_vector_face_access=DataAccessOnFaces::unspecified) const internal::MatrixFreeFunctions::MappingInfo< dim, Number, VectorizedArrayType > mapping_info Definition: matrix_free.h:2114 unsigned int get_cell_active_fe_index(const std::pair< unsigned int, unsigned int > range) const const internal::MatrixFreeFunctions::TaskInfo & get_task_info() const DoFHandler< dim >::active_cell_iterator get_hp_cell_iterator(const unsigned int cell_batch_index, const unsigned int lane_index, const unsigned int dof_handler_index=0) const unsigned int n_ghost_cell_batches() const void loop(const std::function< void(const MatrixFree< dim, Number, VectorizedArrayType > &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &)> &cell_operation, const std::function< void(const MatrixFree< dim, Number, VectorizedArrayType > &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &)> &face_operation, const std::function< void(const MatrixFree< dim, Number, VectorizedArrayType > &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &)> &boundary_operation, OutVector &dst, const InVector &src, const bool zero_dst_vector=false, const DataAccessOnFaces dst_vector_face_access=DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access=DataAccessOnFaces::unspecified) const const internal::MatrixFreeFunctions::ShapeInfo< VectorizedArrayType > & get_shape_info(const unsigned int dof_handler_index_component=0, const unsigned int quad_index=0, const unsigned int fe_base_element=0, const unsigned int hp_active_fe_index=0, const unsigned int hp_active_quad_index=0) const void initialize_dof_handlers(const std::vector< const DoFHandler< dim, dim > * > &dof_handlers, const AdditionalData &additional_data) Table< 4, internal::MatrixFreeFunctions::ShapeInfo< VectorizedArrayType > > shape_info Definition: matrix_free.h:2120 void print(std::ostream &out) const void update_mapping(const std::shared_ptr< hp::MappingCollection< dim > > &mapping) const Table< 3, unsigned int > & get_cell_and_face_to_plain_faces() const void reinit(const std::vector< const DoFHandler< dim > * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const QuadratureType &quad, const AdditionalData &additional_data=AdditionalData()) unsigned int n_inner_face_batches() const unsigned int n_active_entries_per_cell_batch(const unsigned int cell_batch_index) const void update_mapping(const Mapping< dim > &mapping) const Quadrature< dim > & get_quadrature(const unsigned int quad_index=0, const unsigned int hp_active_fe_index=0) const const internal::MatrixFreeFunctions::FaceToCellTopology< VectorizedArrayType::size()> & get_face_info(const unsigned int face_batch_index) const unsigned int get_mg_level() const unsigned int n_components_filled(const unsigned int cell_batch_number) const void print_memory_consumption(StreamType &out) const void reinit(const std::vector< const DoFHandlerType * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const std::vector< QuadratureType > &quad, const AdditionalData &additional_data=AdditionalData()) bool mapping_initialized() const void cell_loop(const std::function< void(const MatrixFree< dim, Number, VectorizedArrayType > &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &)> &cell_operation, OutVector &dst, const InVector &src, const std::function< void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function< void(const unsigned int, const unsigned int)> &operation_after_loop, const unsigned int dof_handler_index_pre_post=0) const void clear() void internal_reinit(const std::shared_ptr< hp::MappingCollection< dim > > &mapping, const std::vector< const DoFHandler< dim, dim > * > &dof_handlers, const std::vector< const AffineConstraints< number2 > * > &constraint, const std::vector< IndexSet > &locally_owned_set, const std::vector< hp::QCollection< q_dim > > &quad, const AdditionalData &additional_data) unsigned int get_n_q_points_face(const unsigned int quad_index=0, const unsigned int hp_active_fe_index=0) const const internal::MatrixFreeFunctions::DoFInfo & get_dof_info(const unsigned int dof_handler_index_component=0) const AlignedVector< VectorizedArrayType > * acquire_scratch_data() const bool at_irregular_cell(const unsigned int cell_batch_index) const ~MatrixFree() override=default const DoFHandlerType & get_dof_handler(const unsigned int dof_handler_index=0) const void copy_from(const MatrixFree< dim, Number, VectorizedArrayType > &matrix_free_base) unsigned int get_dofs_per_cell(const unsigned int dof_handler_index=0, const unsigned int hp_active_fe_index=0) const unsigned int n_constraint_pool_entries() const void cell_loop(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &), CLASS *owning_class, OutVector &dst, const InVector &src, const std::function< void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function< void(const unsigned int, const unsigned int)> &operation_after_loop, const unsigned int dof_handler_index_pre_post=0) const const Number * constraint_pool_begin(const unsigned int pool_index) const AlignedVector< Number > * acquire_scratch_data_non_threadsafe() const const IndexSet & get_locally_owned_set(const unsigned int dof_handler_index=0) const unsigned int get_dofs_per_face(const unsigned int dof_handler_index=0, const unsigned int hp_active_fe_index=0) const internal::MatrixFreeFunctions::TaskInfo task_info Definition: matrix_free.h:2144 const DoFHandler< dim > & get_dof_handler(const unsigned int dof_handler_index=0) const void release_scratch_data(const AlignedVector< VectorizedArrayType > *memory) const void loop(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &) const, void(CLASS::*face_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &) const, void(CLASS::*boundary_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &) const, const CLASS *owning_class, OutVector &dst, const InVector &src, const bool zero_dst_vector=false, const DataAccessOnFaces dst_vector_face_access=DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access=DataAccessOnFaces::unspecified) const std::pair< unsigned int, unsigned int > get_face_category(const unsigned int macro_face) const bool mapping_is_initialized Definition: matrix_free.h:2161 void loop_cell_centric(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &) const, const CLASS *owning_class, OutVector &dst, const InVector &src, const bool zero_dst_vector=false, const DataAccessOnFaces src_vector_face_access=DataAccessOnFaces::unspecified) const void initialize_dof_vector(LinearAlgebra::distributed::Vector< Number2 > &vec, const unsigned int dof_handler_index=0) const DoFHandler< dim >::cell_iterator get_cell_iterator(const unsigned int cell_batch_index, const unsigned int lane_index, const unsigned int dof_handler_index=0) const MatrixFree(const MatrixFree< dim, Number, VectorizedArrayType > &other) std::pair< unsigned int, unsigned int > create_cell_subrange_hp(const std::pair< unsigned int, unsigned int > &range, const unsigned int fe_degree, const unsigned int dof_handler_index=0) const std::pair< unsigned int, unsigned int > create_cell_subrange_hp_by_index(const std::pair< unsigned int, unsigned int > &range, const unsigned int fe_index, const unsigned int dof_handler_index=0) const unsigned int mg_level Definition: matrix_free.h:2184 void cell_loop(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &) const, const CLASS *owning_class, OutVector &dst, const InVector &src, const std::function< void(const unsigned int, const unsigned int)> &operation_before_loop, const std::function< void(const unsigned int, const unsigned int)> &operation_after_loop, const unsigned int dof_handler_index_pre_post=0) const std::vector< std::pair< unsigned int, unsigned int > > cell_level_index Definition: matrix_free.h:2128 const std::shared_ptr< const Utilities::MPI::Partitioner > & get_vector_partitioner(const unsigned int dof_handler_index=0) const const internal::MatrixFreeFunctions::MappingInfo< dim, Number, VectorizedArrayType > & get_mapping_info() const void reinit(const std::vector< const DoFHandler< dim > * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const std::vector< QuadratureType > &quad, const AdditionalData &additional_data=AdditionalData()) std::vector< Number > constraint_pool_data Definition: matrix_free.h:2101 VectorizedArrayType vectorized_value_type Definition: matrix_free.h:128 unsigned int n_cell_batches() const const IndexSet & get_ghost_set(const unsigned int dof_handler_index=0) const std::pair< int, int > get_cell_level_and_index(const unsigned int cell_batch_index, const unsigned int lane_index) const bool indices_initialized() const const Quadrature< dim - 1 > & get_face_quadrature(const unsigned int quad_index=0, const unsigned int hp_active_fe_index=0) const types::boundary_id get_boundary_id(const unsigned int macro_face) const unsigned int get_cell_category(const unsigned int cell_batch_index) const void reinit(const MappingType &mapping, const std::vector< const DoFHandlerType * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const QuadratureType &quad, const AdditionalData &additional_data=AdditionalData()) Threads::ThreadLocalStorage< std::list< std::pair< bool, AlignedVector< VectorizedArrayType > > > > scratch_pad Definition: matrix_free.h:2172 Number value_type Definition: matrix_free.h:127 std::size_t memory_consumption() const unsigned int n_boundary_face_batches() const void cell_loop(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &) const, const CLASS *owning_class, OutVector &dst, const InVector &src, const bool zero_dst_vector=false) const std::list< std::pair< bool, AlignedVector< Number > > > scratch_pad_non_threadsafe Definition: matrix_free.h:2179 const Number * constraint_pool_end(const unsigned int pool_index) const void loop_cell_centric(const std::function< void(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &)> &cell_operation, OutVector &dst, const InVector &src, const bool zero_dst_vector=false, const DataAccessOnFaces src_vector_face_access=DataAccessOnFaces::unspecified) const std::vector< SmartPointer< const DoFHandler< dim > > > dof_handlers Definition: matrix_free.h:2087 void reinit(const std::vector< const DoFHandlerType * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const QuadratureType &quad, const AdditionalData &additional_data=AdditionalData()) void initialize_indices(const std::vector< const AffineConstraints< number2 > * > &constraint, const std::vector< IndexSet > &locally_owned_set, const AdditionalData &additional_data) unsigned int n_components() const unsigned int n_physical_cells() const void initialize_dof_vector(VectorType &vec, const unsigned int dof_handler_index=0) const unsigned int get_n_q_points(const unsigned int quad_index=0, const unsigned int hp_active_fe_index=0) const void reinit(const MappingType &mapping, const std::vector< const DoFHandler< dim > * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const QuadratureType &quad, const AdditionalData &additional_data=AdditionalData()) void cell_loop(const std::function< void(const MatrixFree< dim, Number, VectorizedArrayType > &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &)> &cell_operation, OutVector &dst, const InVector &src, const bool zero_dst_vector=false) const unsigned int n_macro_cells() const void reinit(const MappingType &mapping, const std::vector< const DoFHandlerType * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const std::vector< QuadratureType > &quad, const AdditionalData &additional_data=AdditionalData()) void cell_loop(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &), CLASS *owning_class, OutVector &dst, const InVector &src, const bool zero_dst_vector=false) const std::vector< internal::MatrixFreeFunctions::DoFInfo > dof_info Definition: matrix_free.h:2093 unsigned int n_ghost_inner_face_batches() const void release_scratch_data_non_threadsafe(const AlignedVector< Number > *memory) const void renumber_dofs(std::vector< types::global_dof_index > &renumbering, const unsigned int dof_handler_index=0) unsigned int get_face_active_fe_index(const std::pair< unsigned int, unsigned int > range, const bool is_interior_face=true) const unsigned int n_active_entries_per_face_batch(const unsigned int face_batch_index) const bool indices_are_initialized Definition: matrix_free.h:2156 internal::MatrixFreeFunctions::FaceInfo< VectorizedArrayType::size()> face_info Definition: matrix_free.h:2151 void reinit(const MappingType &mapping, const DoFHandler< dim > &dof_handler, const AffineConstraints< number2 > &constraint, const QuadratureType &quad, const AdditionalData &additional_data=AdditionalData()) void loop(void(CLASS::*cell_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &), void(CLASS::*face_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &), void(CLASS::*boundary_operation)(const MatrixFree &, OutVector &, const InVector &, const std::pair< unsigned int, unsigned int > &), CLASS *owning_class, OutVector &dst, const InVector &src, const bool zero_dst_vector=false, const DataAccessOnFaces dst_vector_face_access=DataAccessOnFaces::unspecified, const DataAccessOnFaces src_vector_face_access=DataAccessOnFaces::unspecified) const void reinit(const MappingType &mapping, const std::vector< const DoFHandler< dim > * > &dof_handler, const std::vector< const AffineConstraints< number2 > * > &constraint, const std::vector< QuadratureType > &quad, const AdditionalData &additional_data=AdditionalData()) std::array< types::boundary_id, VectorizedArrayType::size()> get_faces_by_cells_boundary_id(const unsigned int cell_batch_index, const unsigned int face_number) const std::vector< unsigned int > constraint_pool_row_index Definition: matrix_free.h:2107 const std::vector< unsigned int > & get_constrained_dofs(const unsigned int dof_handler_index=0) const void reinit(const DoFHandler< dim > &dof_handler, const AffineConstraints< number2 > &constraint, const QuadratureType &quad, const AdditionalData &additional_data=AdditionalData()) unsigned int cell_level_index_end_local Definition: matrix_free.h:2137 unsigned int n_base_elements(const unsigned int dof_handler_index) const static const unsigned int dimension Definition: matrix_free.h:133 static bool is_supported(const FiniteElement< dim, spacedim > &fe) A class that provides a separate storage location on each thread that accesses the object. #define DEAL_II_DEPRECATED Definition: config.h:162 #define DEAL_II_NAMESPACE_OPEN Definition: config.h:402 #define DEAL_II_DISABLE_EXTRA_DIAGNOSTICS Definition: config.h:416 #define DEAL_II_NAMESPACE_CLOSE Definition: config.h:403 #define DEAL_II_ENABLE_EXTRA_DIAGNOSTICS Definition: config.h:454 UpdateFlags @ update_JxW_values Transformed quadrature weights. @ update_gradients Shape function gradients. @ update_default No update. unsigned int level Definition: grid_out.cc:4590 static ::ExceptionBase & ExcNotImplemented() static ::ExceptionBase & ExcIndexRange(int arg1, int arg2, int arg3) #define Assert(cond, exc) Definition: exceptions.h:1465 #define AssertDimension(dim1, dim2) Definition: exceptions.h:1622 #define AssertIndexRange(index, range) Definition: exceptions.h:1690 static ::ExceptionBase & ExcInternalError() static ::ExceptionBase & ExcNotInitialized() static ::ExceptionBase & ExcMessage(std::string arg1) #define AssertThrow(cond, exc) Definition: exceptions.h:1575 typename ActiveSelector::cell_iterator cell_iterator Definition: dof_handler.h:466 typename ActiveSelector::active_cell_iterator active_cell_iterator Definition: dof_handler.h:438 void reinit(const size_type size, const bool omit_zeroing_entries=false) static const char U VectorType::value_type * begin(VectorType &V) bool job_supports_mpi() Definition: mpi.cc:1097 unsigned int minimum_parallel_grain_size Definition: parallel.cc:34 const types::boundary_id invalid_boundary_id Definition: types.h:239 static const unsigned int invalid_unsigned_int Definition: types.h:196 void apply_to_subranges(const tbb::blocked_range< RangeType > &range, const Function &f) Definition: parallel.h:367 ::VectorizedArray< Number, width > max(const ::VectorizedArray< Number, width > &, const ::VectorizedArray< Number, width > &) unsigned int boundary_id Definition: types.h:129 TasksParallelScheme tasks_parallel_scheme Definition: matrix_free.h:344 UpdateFlags mapping_update_flags_inner_faces Definition: matrix_free.h:410 AdditionalData(const TasksParallelScheme tasks_parallel_scheme=partition_partition, const unsigned int tasks_block_size=0, const UpdateFlags mapping_update_flags=update_gradients|update_JxW_values, const UpdateFlags mapping_update_flags_boundary_faces=update_default, const UpdateFlags mapping_update_flags_inner_faces=update_default, const UpdateFlags mapping_update_flags_faces_by_cells=update_default, const unsigned int mg_level=numbers::invalid_unsigned_int, const bool store_plain_indices=true, const bool initialize_indices=true, const bool initialize_mapping=true, const bool overlap_communication_computation=true, const bool hold_all_faces_to_owned_cells=false, const bool cell_vectorization_categories_strict=false) Definition: matrix_free.h:217 std::vector< unsigned int > cell_vectorization_category Definition: matrix_free.h:524 AdditionalData & operator=(const AdditionalData &other) Definition: matrix_free.h:283 unsigned int & level_mg_handler Definition: matrix_free.h:455 UpdateFlags mapping_update_flags_boundary_faces Definition: matrix_free.h:389 UpdateFlags mapping_update_flags Definition: matrix_free.h:368 UpdateFlags mapping_update_flags_faces_by_cells Definition: matrix_free.h:438 AdditionalData(const AdditionalData &other) Definition: matrix_free.h:253 unsigned int tasks_block_size Definition: matrix_free.h:355 static bool equal(const T *p1, const T *p2) std::vector< unsigned int > cell_loop_pre_list_index Definition: dof_info.h:721 std::vector< unsigned int > cell_loop_post_list_index Definition: dof_info.h:734 std::vector< std::pair< unsigned int, unsigned int > > vector_zero_range_list Definition: dof_info.h:714 std::shared_ptr< const Utilities::MPI::Partitioner > vector_partitioner Definition: dof_info.h:565 std::vector< std::pair< unsigned int, unsigned int > > cell_loop_pre_list Definition: dof_info.h:727 std::vector< unsigned int > vector_zero_range_list_index Definition: dof_info.h:709 std::vector< std::pair< unsigned int, unsigned int > > cell_loop_post_list Definition: dof_info.h:740 ::Table< 3, unsigned int > cell_and_face_to_plain_faces Definition: face_info.h:172 std::vector< FaceToCellTopology< vectorization_width > > faces Definition: face_info.h:165 ::Table< 3, types::boundary_id > cell_and_face_boundary_id Definition: face_info.h:178 std::vector< unsigned int > boundary_partition_data Definition: task_info.h:518 void loop(MFWorkerInterface &worker) const Definition: task_info.cc:348 std::vector< unsigned int > cell_partition_data Definition: task_info.h:474 std::vector< unsigned int > face_partition_data Definition: task_info.h:496
__label__pos
0.977526
Http Listener 介绍 Http Listener 是专门负载接收 HTTP 请求的 Listener,它可以设置 HTTP 监听的地址和端口。它可以通过如下配置进行引入。 static_resources: listeners: - name: "net/http" protocol_type: "HTTP" # 表明是引入 HTTP Listener address: socket_address: address: "0.0.0.0" # 地址 port: 8883 # 端口 Http Listener 的具体实现可以参考 pkg/listener/http 有关 HTTP Listener 的案例,可以参考: • HTTP to Dubbo 请求的转换,案例 • HTTP 请求代理,案例 目前也支持 HTTPS 协议。可以将 protocol_type 修改为 HTTPS。并且添加 domainscerts_dir 来指定域名和 cert 文件目录。 listeners: - name: "net/http" protocol_type: "HTTPS" address: socket_address: domains: - "sample.domain.com" - "sample.domain-1.com" - "sample.domain-2.com" certs_dir: $PROJECT_DIR/cert 具体案例可以查看 案例
__label__pos
0.915405
Evaluations and SQL Aggregations in FastAPI undraw svg icon Welcome to Part 12 of Up and Running with FastAPI. If you missed part 11, you can find it here. This series is focused on building a full-stack application with the FastAPI framework. The app allows users to post requests to have their residence cleaned, and other users can select a cleaning project for a given hourly rate. Up And Running With FastAPI In the last post, we implemented the beginnings of a marketplace-like environment where users can accept, reject, cancel, and rescind offers for cleaning jobs. Now we're going to provide owners the ability to mark jobs as completed and evaluate the cleaner's work. On top of that, we'll provide a way to aggregate user evaluations and serve up a brief overview on the quality of a given cleaner's work. Migrations Of course, we'll need to update our database to make this happen. Start by rolling back the current migrations as we've done previously. docker ps docker exec -it [CONTAINER_ID] bash alembic downgrade base Then go ahead and create a new table in the same migrations file like so: # ...other code def create_cleaner_evaluations_table() -> None: """ Owner of a cleaning job should be able to evaluate a cleaner's execution of the job. - Allow owner to leave ratings, headline, and comment - Also add no show if the cleaner failed to show up - Rating split into sections - professionalism - did they handle things like pros? - completeness - how thorough were they? did everything get cleaned as it should have? - efficiency - how quickly and effectively did they get the job done? - overall - what's the consensus rating for this cleaning job? """ op.create_table( "cleaning_to_cleaner_evaluations", sa.Column( "cleaning_id", # job that was completed sa.Integer, sa.ForeignKey("cleanings.id", ondelete="SET NULL"), nullable=False, index=True, ), sa.Column( "cleaner_id", # user who completed the job sa.Integer, sa.ForeignKey("users.id", ondelete="SET NULL"), nullable=False, index=True, ), sa.Column("no_show", sa.Boolean, nullable=False, server_default="False"), sa.Column("headline", sa.Text, nullable=True), sa.Column("comment", sa.Text, nullable=True), sa.Column("professionalism", sa.Integer, nullable=True), sa.Column("completeness", sa.Integer, nullable=True), sa.Column("efficiency", sa.Integer, nullable=True), sa.Column("overall_rating", sa.Integer, nullable=False), *timestamps(), ) op.create_primary_key( "pk_cleaning_to_cleaner_evaluations", "cleaning_to_cleaner_evaluations", ["cleaning_id", "cleaner_id"] ) op.execute( """ CREATE TRIGGER update_cleaning_to_cleaner_evaluations_modtime BEFORE UPDATE ON cleaning_to_cleaner_evaluations FOR EACH ROW EXECUTE PROCEDURE update_updated_at_column(); """ ) def upgrade() -> None: create_updated_at_trigger() create_users_table() create_profiles_table() create_cleanings_table() create_offers_table() create_cleaner_evaluations_table() def downgrade() -> None: op.drop_table("cleaning_to_cleaner_evaluations") op.drop_table("user_offers_for_cleanings") op.drop_table("cleanings") op.drop_table("profiles") op.drop_table("users") op.execute("DROP FUNCTION update_updated_at_column") Notice how we don't include the owner of the cleaning job in this table? We don't need to. The cleaning_id has a unique owners column attached, so there's no need to add redundant data here. This table will give the owner of a cleaning job the ability to evaluate a cleaner in 3 categories - professionalism, completeness, and efficiency. These are arbitrary, so feel free to change them. We also provide an overall_rating column for a more generalized evaluation. We again guarantee uniqueness between a cleaning job and a cleaner by using the combination of those two to create our primary key. Run the migrations with alembic upgrade head and move on to the models. Evaluation models Create a new evaluation models file: touch backend/app/models/evaluation.py And add the following: models/evaluation.py from typing import Optional, Union from pydantic import conint, confloat, Field from app.models.core import DateTimeModelMixin, CoreModel from app.models.user import UserPublic from app.models.cleaning import CleaningPublic class EvaluationBase(CoreModel): no_show: bool = False headline: Optional[str] comment: Optional[str] professionalism: Optional[conint(ge=0, le=5)] completeness: Optional[conint(ge=0, le=5)] efficiency: Optional[conint(ge=0, le=5)] overall_rating: Optional[conint(ge=0, le=5)] class EvaluationCreate(EvaluationBase): overall_rating: conint(ge=0, le=5) class EvaluationUpdate(EvaluationBase): pass class EvaluationInDB(DateTimeModelMixin, EvaluationBase): cleaner_id: int cleaning_id: int class EvaluationPublic(EvaluationInDB): owner: Optional[Union[int, UserPublic]] cleaner: Union[int, UserPublic] = Field(..., alias="cleaner_id") cleaning: Union[int, CleaningPublic] = Field(..., alias="cleaning_id") class Config: allow_population_by_field_name = True class EvaluationAggregate(CoreModel): avg_professionalism: confloat(ge=0, le=5) avg_completeness: confloat(ge=0, le=5) avg_efficiency: confloat(ge=0, le=5) avg_overall_rating: confloat(ge=0, le=5) max_overall_rating: conint(ge=0, le=5) min_overall_rating: conint(ge=0, le=5) one_stars: conint(ge=0) two_stars: conint(ge=0) three_stars: conint(ge=0) four_stars: conint(ge=0) five_stars: conint(ge=0) total_evaluations: conint(ge=0) total_no_show: conint(ge=0) For the most part we simply mirror the functionality of the models in our offer.py file, though we're using a conint type here for ratings. The docs for that constrained type can be found here and allow us to specify that these ratings must be an integer between 0 and 5, inclusive. The only attribute we require to create an evaluation is overall_rating. We also provide the ability to attach the owner to the EvaluationPublic model if we feel like doing so. At the bottom we see something new - the EvaluationAggregate model. Here we collect summary statistics about a given cleaner similar to how Amazon, Yelp, and other rating sites do. We're using conint and confloat to restrict the values slightly. Now let's do some testing. Testing Evaluation Routes First, create a new testing file: touch backend/tests/test_evaluations.py And create our standard test routes class. tests/test_evaluations.py from typing import List, Callable import pytest from httpx import AsyncClient from fastapi import FastAPI, status from app.models.cleaning import CleaningInDB from app.models.user import UserInDB from app.models.offer import OfferInDB from app.models.evaluation import EvaluationCreate, EvaluationInDB, EvaluationPublic, EvaluationAggregate from app.db.repositories.evaluations import EvaluationsRepository pytestmark = pytest.mark.asyncio class TestEvaluationRoutes: async def test_routes_exist(self, app: FastAPI, client: AsyncClient) -> None: res = await client.post( app.url_path_for("evaluations:create-evaluation-for-cleaner", cleaning_id=1, username="bradpitt") ) assert res.status_code != status.HTTP_404_NOT_FOUND res = await client.get( app.url_path_for("evaluations:get-evaluation-for-cleaner", cleaning_id=1, username="bradpitt") ) assert res.status_code != status.HTTP_404_NOT_FOUND res = await client.get(app.url_path_for("evaluations:list-evaluations-for-cleaner", username="bradpitt")) assert res.status_code != status.HTTP_404_NOT_FOUND res = await client.get(app.url_path_for("evaluations:get-stats-for-cleaner", username="bradpitt")) assert res.status_code != status.HTTP_404_NOT_FOUND Not much to see here. We're only testing the existence of three routes - create, get, and list. For the time being, we won't allow owners to delete or update their evaluations, though that may change later. Run the tests and watch them fail. We'll need to create a routes, dependency, and repository file for our evaluations as well. Might as well do them all together here: touch backend/app/api/routes/evaluations.py touch backend/app/api/dependencies/evaluations.py touch backend/app/db/repositories/evaluations.py Now add some dummy routes to the routes file. api/routes/evaluations.py from typing import List from fastapi import APIRouter, Depends, Body, Path, status from app.models.evaluation import EvaluationCreate, EvaluationInDB, EvaluationPublic, EvaluationAggregate from app.models.user import UserInDB from app.models.cleaning import CleaningInDB from app.db.repositories.evaluations import EvaluationsRepository from app.api.dependencies.database import get_repository from app.api.dependencies.cleanings import get_cleaning_by_id_from_path from app.api.dependencies.users import get_user_by_username_from_path router = APIRouter() @router.post( "/{cleaning_id}/", response_model=EvaluationPublic, name="evaluations:create-evaluation-for-cleaner", status_code=status.HTTP_201_CREATED, ) async def create_evaluation_for_cleaner( evaluation_create: EvaluationCreate = Body(..., embed=True), ) -> EvaluationPublic: return None @router.get( "/", response_model=List[EvaluationPublic], name="evaluations:list-evaluations-for-cleaner", ) async def list_evaluations_for_cleaner() -> List[EvaluationPublic]: return None @router.get( "/stats/", response_model=EvaluationAggregate, name="evaluations:get-stats-for-cleaner", ) async def get_stats_for_cleaner() -> EvaluationAggregate: return None @router.get( "/{cleaning_id}/", response_model=EvaluationPublic, name="evaluations:get-evaluation-for-cleaner", ) async def get_evaluation_for_cleaner() -> EvaluationPublic: return None Let's also go ahead and register those routes in our api router. api/routes/__init__.py from fastapi import APIRouter from app.api.routes.cleanings import router as cleanings_router from app.api.routes.users import router as users_router from app.api.routes.profiles import router as profiles_router from app.api.routes.offers import router as offers_router from app.api.routes.evaluations import router as evaluations_router router = APIRouter() router.include_router(cleanings_router, prefix="/cleanings", tags=["cleanings"]) router.include_router(users_router, prefix="/users", tags=["users"]) router.include_router(profiles_router, prefix="/profiles", tags=["profiles"]) router.include_router(offers_router, prefix="/cleanings/{cleaning_id}/offers", tags=["offers"]) router.include_router(evaluations_router, prefix="/users/{username}/evaluations", tags=["evaluations"]) This time we're namespacing the evaluations router under users/{username}/evaluations. It's essentially the reverse of what we did with offers and will be useful for when we want to aggregate user statistics later on. Before we can get our tests passing, we'll need a placeholder EvaluationsRepository, so add this as well. db/repositories/evaluations.py from typing import List from databases import Database from app.db.repositories.base import BaseRepository from app.db.repositories.offers import OffersRepository from app.models.cleaning import CleaningInDB from app.models.user import UserInDB from app.models.evaluation import EvaluationCreate, EvaluationUpdate, EvaluationInDB, EvaluationAggregate class EvaluationsRepository(BaseRepository): def __init__(self, db: Database) -> None: super().__init__(db) self.offers_repo = OffersRepository(db) We're integrating the OffersRepository in our __init__ method, as we'll need it in a minute. Run the tests now and they should pass. Create Evaluations Let's begin with some standard tests. Here's the functionality we want to implement: 1. Owners of a cleaning job can leave evaluations for cleaners who completed that cleaning job. 2. Evaluations can only be made for jobs that have been accepted. 3. Evaluations can only be made for users whose offer was accepted for that job. 4. Evaluations can only be left once per cleaning. 5. Once an evaluation has been made, the offer should be marked as completed. Let's test those conditions with a new test class. tests/test_evaluations.py # ...other code class TestCreateEvaluations: async def test_owner_can_leave_evaluation_for_cleaner_and_mark_offer_completed( self, app: FastAPI, create_authorized_client: Callable, test_user2: UserInDB, test_user3: UserInDB, test_cleaning_with_accepted_offer: CleaningInDB, ) -> None: evaluation_create = EvaluationCreate( no_show=False, headline="Excellent job", comment=f""" Really appreciated the hard work and effort they put into this job! Though the cleaner took their time, I would definitely hire them again for the quality of their work. """, professionalism=5, completeness=5, efficiency=4, overall_rating=5, ) authorized_client = create_authorized_client(user=test_user2) res = await authorized_client.post( app.url_path_for( "evaluations:create-evaluation-for-cleaner", cleaning_id=test_cleaning_with_accepted_offer.id, username=test_user3.username, ), json={"evaluation_create": evaluation_create.dict()}, ) assert res.status_code == status.HTTP_201_CREATED evaluation = EvaluationInDB(**res.json()) assert evaluation.no_show == evaluation_create.no_show assert evaluation.headline == evaluation_create.headline assert evaluation.overall_rating == evaluation_create.overall_rating # check that the offer has now been marked as "completed" res = await authorized_client.get( app.url_path_for( "offers:get-offer-from-user", cleaning_id=test_cleaning_with_accepted_offer.id, username=test_user3.username, ) ) assert res.status_code == status.HTTP_200_OK assert res.json()["status"] == "completed" async def test_non_owner_cant_leave_review( self, app: FastAPI, create_authorized_client: Callable, test_user4: UserInDB, test_user3: UserInDB, test_cleaning_with_accepted_offer: CleaningInDB, ) -> None: authorized_client = create_authorized_client(user=test_user4) res = await authorized_client.post( app.url_path_for( "evaluations:create-evaluation-for-cleaner", cleaning_id=test_cleaning_with_accepted_offer.id, username=test_user3.username, ), json={"evaluation_create": {"overall_rating": 2}}, ) assert res.status_code == status.HTTP_403_FORBIDDEN async def test_owner_cant_leave_review_for_wrong_user( self, app: FastAPI, create_authorized_client: Callable, test_user2: UserInDB, test_user4: UserInDB, test_cleaning_with_accepted_offer: CleaningInDB, ) -> None: authorized_client = create_authorized_client(user=test_user2) res = await authorized_client.post( app.url_path_for( "evaluations:create-evaluation-for-cleaner", cleaning_id=test_cleaning_with_accepted_offer.id, username=test_user4.username, ), json={"evaluation_create": {"overall_rating": 1}}, ) assert res.status_code == status.HTTP_400_BAD_REQUEST async def test_owner_cant_leave_multiple_reviews( self, app: FastAPI, create_authorized_client: Callable, test_user2: UserInDB, test_user3: UserInDB, test_cleaning_with_accepted_offer: CleaningInDB, ) -> None: authorized_client = create_authorized_client(user=test_user2) res = await authorized_client.post( app.url_path_for( "evaluations:create-evaluation-for-cleaner", cleaning_id=test_cleaning_with_accepted_offer.id, username=test_user3.username, ), json={"evaluation_create": {"overall_rating": 3}}, ) assert res.status_code == status.HTTP_201_CREATED res = await authorized_client.post( app.url_path_for( "evaluations:create-evaluation-for-cleaner", cleaning_id=test_cleaning_with_accepted_offer.id, username=test_user3.username, ), json={"evaluation_create": {"overall_rating": 1}}, ) assert res.status_code == status.HTTP_400_BAD_REQUEST Ok, we have four new test cases that should cover the functionality we are hoping to implement. In the first tests case we're checking to make sure the status of our offer is "completed" as soon as the evaluation has been created. We haven't added that option to any of our offer models, so keep that in mind as we start fleshing out our EvaluationsRepository. In fact, let's start writing the code our POST route will need so that we can determine how our database interface should look. api/routes/evaluations.py # ...other code @router.post( "/{cleaning_id}/", response_model=EvaluationPublic, name="evaluations:create-evaluation-for-cleaner", status_code=status.HTTP_201_CREATED, ) async def create_evaluation_for_cleaner( evaluation_create: EvaluationCreate = Body(..., embed=True), cleaning: CleaningInDB = Depends(get_cleaning_by_id_from_path), cleaner: UserInDB = Depends(get_user_by_username_from_path), evals_repo: EvaluationsRepository = Depends(get_repository(EvaluationsRepository)), ) -> EvaluationPublic: return await evals_repo.create_evaluation_for_cleaner( evaluation_create=evaluation_create, cleaner=cleaner, cleaning=cleaning ) # ...other code This route is mostly dependencies. We return the result of a single call to our EvaluationsRepository with the create_evaluation_for_cleaner method. That method takes in the cleaner who is being evaluated, the cleaning job the cleaner has completed, and the evaluation_create that's being added to the database. We've already defined each of the needed dependencies in our previous posts, so no need to touch our api/dependencies/evaluations.py file just yet. Let's head into our EvaluationsRepository. db/repositories/evaluations.py # ...other code CREATE_OWNER_EVALUATION_FOR_CLEANER_QUERY = """ INSERT INTO cleaning_to_cleaner_evaluations ( cleaning_id, cleaner_id, no_show, headline, comment, professionalism, completeness, efficiency, overall_rating ) VALUES ( :cleaning_id, :cleaner_id, :no_show, :headline, :comment, :professionalism, :completeness, :efficiency, :overall_rating ) RETURNING no_show, cleaning_id, cleaner_id, headline, comment, professionalism, completeness, efficiency, overall_rating, created_at, updated_at; """ class EvaluationsRepository(BaseRepository): def __init__(self, db: Database) -> None: super().__init__(db) self.offers_repo = OffersRepository(db) async def create_evaluation_for_cleaner( self, *, evaluation_create: EvaluationCreate, cleaning: CleaningInDB, cleaner: UserInDB ) -> EvaluationInDB: async with self.db.transaction(): created_evaluation = await self.db.fetch_one( query=CREATE_OWNER_EVALUATION_FOR_CLEANER_QUERY, values={**evaluation_create.dict(), "cleaning_id": cleaning.id, "cleaner_id": cleaner.id}, ) # also mark offer as completed await self.offers_repo.mark_offer_completed(cleaning=cleaning, cleaner=cleaner) return EvaluationInDB(**created_evaluation) Ok, now we've got something going. We execute our queries inside a transaction block so that this becomes an all-or-nothing trip to the db. First, we create the new evaluation and attach the cleaning_id and cleaner_id to it. Then, we mark the cleaner's offer for this job as "completed" using a yet-to-be-created method on the OffersRepository called mark_offer_completed. If all goes well, we return the newly-created evaluation. We'll need to define the mark_offer_completed next, so open up that file. db/repositories/offers.py # ...other code MARK_OFFER_COMPLETED_QUERY = """ UPDATE user_offers_for_cleanings SET status = 'completed' WHERE cleaning_id = :cleaning_id AND user_id = :user_id """ class OffersRepository(BaseRepository): # ...other code async def mark_offer_completed(self, *, cleaning: CleaningInDB, cleaner: UserInDB) -> OfferInDB: return await self.db.fetch_one( query=MARK_OFFER_COMPLETED_QUERY, # owner of cleaning marks job status as completed values={"cleaning_id": cleaning.id, "user_id": cleaner.id}, ) Nothing too crazy here. We simply add a method to set the status of the offer as "completed". We'll also need to update the models/offer.py file to recognize this option for status, so open up that file and modify it like so: models/offer.py # ...other code class OfferStatus(str, Enum): accepted = "accepted" rejected = "rejected" pending = "pending" cancelled = "cancelled" completed = "completed" # ...other code And there we go! Run the tests again and the first condition should pass. The other tests are returning 201 responses instead of the 403 and 400s we expect, so we'll need to create a new dependency to deal with that properly. api/dependencies/evaluations.py from typing import List from fastapi import HTTPException, Depends, Path, status from app.models.user import UserInDB from app.models.cleaning import CleaningInDB from app.models.offer import OfferInDB from app.models.evaluation import EvaluationInDB from app.db.repositories.evaluations import EvaluationsRepository from app.api.dependencies.database import get_repository from app.api.dependencies.auth import get_current_active_user from app.api.dependencies.users import get_user_by_username_from_path from app.api.dependencies.cleanings import get_cleaning_by_id_from_path from app.api.dependencies.offers import get_offer_for_cleaning_from_user_by_path async def check_evaluation_create_permissions( current_user: UserInDB = Depends(get_current_active_user), cleaning: CleaningInDB = Depends(get_cleaning_by_id_from_path), cleaner: UserInDB = Depends(get_user_by_username_from_path), offer: OfferInDB = Depends(get_offer_for_cleaning_from_user_by_path), evals_repo: EvaluationsRepository = Depends(get_repository(EvaluationsRepository)), ) -> None: # Check that only owners of a cleaning can leave evaluations for that cleaning job if cleaning.owner != current_user.id: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Users are unable to leave evaluations for cleaning jobs they do not own.", ) # Check that evaluations can only be made for jobs that have been accepted # Also serves to ensure that only one evaluation per-cleaner-per-job is allowed if offer.status != "accepted": raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Only users with accepted offers can be evaluated.", ) # Check that evaluations can only be made for users whose offer was accepted for that job if offer.user_id != cleaner.id: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="You are not authorized to leave an evaluation for this user.", ) Though we're only checking three conditions here, it feels like there's a lot going on with this dependency. We get the cleaning, cleaner, and offer from path parameters using dependencies we've defined in previous posts, and we grab the current user making the request. Composing dependencies in this manner is a clean way to manage resource access. Having already tested their behavior, we can be relatively confident that they're behaving the way we expect them to. So all we need to do is check that the currently authenticated user is the owner of the cleaning job, that the status of the offer in question is "accepted", and that the cleaner being evaluated is the one who created the offer. Let's update our POST route with this new dependency. api/routes/evaluations.py # ...other code from app.api.dependencies.evaluations import check_evaluation_create_permissions @router.post( "/{cleaning_id}/", response_model=EvaluationPublic, name="evaluations:create-evaluation-for-cleaner", status_code=status.HTTP_201_CREATED, dependencies=[Depends(check_evaluation_create_permissions)], ) async def create_evaluation_for_cleaner( evaluation_create: EvaluationCreate = Body(..., embed=True), cleaning: CleaningInDB = Depends(get_cleaning_by_id_from_path), cleaner: UserInDB = Depends(get_user_by_username_from_path), evals_repo: EvaluationsRepository = Depends(get_repository(EvaluationsRepository)), ) -> EvaluationPublic: return await evals_repo.create_evaluation_for_cleaner( evaluation_create=evaluation_create, cleaner=cleaner, cleaning=cleaning ) # ...other code Run those tests again...and they pass! Fantastic. On to the GET routes. Fetching Evaluations Before we start listing evaluations, we'll need to create a new pytest fixture in our conftest.py file. We'll begin by defining a helper function and then move to our fixture. tests/conftest.py # ...other code import random # ...other code from app.models.evaluation import EvaluationCreate from app.db.repositories.evaluations import EvaluationsRepository # ...other code async def create_cleaning_with_evaluated_offer_helper( db: Database, owner: UserInDB, cleaner: UserInDB, cleaning_create: CleaningCreate, evaluation_create: EvaluationCreate, ) -> CleaningInDB: cleaning_repo = CleaningsRepository(db) offers_repo = OffersRepository(db) evals_repo = EvaluationsRepository(db) created_cleaning = await cleaning_repo.create_cleaning(new_cleaning=cleaning_create, requesting_user=owner) offer = await offers_repo.create_offer_for_cleaning( new_offer=OfferCreate(cleaning_id=created_cleaning.id, user_id=cleaner.id) ) await offers_repo.accept_offer(offer=offer, offer_update=OfferUpdate(status="accepted")) await evals_repo.create_evaluation_for_cleaner( evaluation_create=evaluation_create, cleaning=created_cleaning, cleaner=cleaner, ) return created_cleaning @pytest.fixture async def test_list_of_cleanings_with_evaluated_offer( db: Database, test_user2: UserInDB, test_user3: UserInDB, ) -> List[CleaningInDB]: return [ await create_cleaning_with_evaluated_offer_helper( db=db, owner=test_user2, cleaner=test_user3, cleaning_create=CleaningCreate( name=f"test cleaning - {i}", description=f"test description - {i}", price=float(f"{i}9.99"), cleaning_type="full_clean", ), evaluation_create=EvaluationCreate( professionalism=random.randint(0, 5), completeness=random.randint(0, 5), efficiency=random.randint(0, 5), overall_rating=random.randint(0, 5), headline=f"test headline - {i}", comment=f"test comment - {i}", ), ) for i in range(5) ] Ok. So we're creating 5 new cleaning jobs and making an offer for each one. We then accept the offer and create an evaluation for it with some random rating values. This will be useful when we start aggregating them. With that in place, let's start testing. Add this following new test case to the tests/test_evaluations.py file. tests/test_evaluations.py from statistics import mean # ...other code class TestGetEvaluations: """ Test that authenticated user who is not owner or cleaner can fetch a single evaluation Test that authenticated user can fetch all of a cleaner's evaluations Test that a cleaner's evaluations comes with an aggregate """ async def test_authenticated_user_can_get_evaluation_for_cleaning( self, app: FastAPI, create_authorized_client: Callable, test_user3: UserInDB, test_user4: UserInDB, test_list_of_cleanings_with_evaluated_offer: List[CleaningInDB], ) -> None: authorized_client = create_authorized_client(user=test_user4) res = await authorized_client.get( app.url_path_for( "evaluations:get-evaluation-for-cleaner", cleaning_id=test_list_of_cleanings_with_evaluated_offer[0].id, username=test_user3.username, ) ) assert res.status_code == status.HTTP_200_OK evaluation = EvaluationPublic(**res.json()) assert evaluation.cleaning == test_list_of_cleanings_with_evaluated_offer[0].id assert evaluation.cleaner == test_user3.id assert "test headline" in evaluation.headline assert "test comment" in evaluation.comment assert evaluation.professionalism >= 0 and evaluation.professionalism <= 5 assert evaluation.completeness >= 0 and evaluation.completeness <= 5 assert evaluation.efficiency >= 0 and evaluation.efficiency <= 5 assert evaluation.overall_rating >= 0 and evaluation.overall_rating <= 5 async def test_authenticated_user_can_get_list_of_evaluations_for_cleaner( self, app: FastAPI, create_authorized_client: Callable, test_user3: UserInDB, test_user4: UserInDB, test_list_of_cleanings_with_evaluated_offer: List[CleaningInDB], ) -> None: authorized_client = create_authorized_client(user=test_user4) res = await authorized_client.get( app.url_path_for("evaluations:list-evaluations-for-cleaner", username=test_user3.username) ) assert res.status_code == status.HTTP_200_OK evaluations = [EvaluationPublic(**e) for e in res.json()] assert len(evaluations) > 1 for evaluation in evaluations: assert evaluation.cleaner == test_user3.id assert evaluation.overall_rating >= 0 async def test_authenticated_user_can_get_aggregate_stats_for_cleaner( self, app: FastAPI, create_authorized_client: Callable, test_user3: UserInDB, test_user4: UserInDB, test_list_of_cleanings_with_evaluated_offer: List[CleaningInDB], ) -> None: authorized_client = create_authorized_client(user=test_user4) res = await authorized_client.get( app.url_path_for("evaluations:list-evaluations-for-cleaner", username=test_user3.username) ) assert res.status_code == status.HTTP_200_OK evaluations = [EvaluationPublic(**e) for e in res.json()] res = await authorized_client.get( app.url_path_for("evaluations:get-stats-for-cleaner", username=test_user3.username) ) assert res.status_code == status.HTTP_200_OK stats = EvaluationAggregate(**res.json()) assert len(evaluations) == stats.total_evaluations assert max([e.overall_rating for e in evaluations]) == stats.max_overall_rating assert min([e.overall_rating for e in evaluations]) == stats.min_overall_rating assert mean([e.overall_rating for e in evaluations]) == stats.avg_overall_rating assert ( mean([e.professionalism for e in evaluations if e.professionalism is not None]) == stats.avg_professionalism ) assert mean([e.completeness for e in evaluations if e.completeness is not None]) == stats.avg_completeness assert mean([e.efficiency for e in evaluations if e.efficiency is not None]) == stats.avg_efficiency assert len([e for e in evaluations if e.overall_rating == 1]) == stats.one_stars assert len([e for e in evaluations if e.overall_rating == 2]) == stats.two_stars assert len([e for e in evaluations if e.overall_rating == 3]) == stats.three_stars assert len([e for e in evaluations if e.overall_rating == 4]) == stats.four_stars assert len([e for e in evaluations if e.overall_rating == 5]) == stats.five_stars async def test_unauthenticated_user_forbidden_from_get_requests( self, app: FastAPI, client: AsyncClient, test_user3: UserInDB, test_list_of_cleanings_with_evaluated_offer: List[CleaningInDB], ) -> None: res = await client.get( app.url_path_for( "evaluations:get-evaluation-for-cleaner", cleaning_id=test_list_of_cleanings_with_evaluated_offer[0].id, username=test_user3.username, ) ) assert res.status_code == status.HTTP_401_UNAUTHORIZED res = await client.get( app.url_path_for("evaluations:list-evaluations-for-cleaner", username=test_user3.username) ) assert res.status_code == status.HTTP_401_UNAUTHORIZED Oh my. We ensure that any user can fetch a single evaluation or a list of evaluations for a given cleaner. We also expect that users can fetch aggregate ratings for a given cleaner - things like average rating and the number of 5 star ratings, 4 star ratings, etc. Instead of doing the mean calculations by hand, we're importing the statistics package and letting it handle the calculations for us. Run those tests and watch them fail miserably. Looks like we have some work to do. Let's hop over to our routes and flesh them out. api/routes/evaluations.py # ...other code from app.api.dependencies.evaluations import ( check_evaluation_create_permissions, list_evaluations_for_cleaner_from_path, get_cleaner_evaluation_for_cleaning_from_path, ) # ...other code @router.get( "/", response_model=List[EvaluationPublic], name="evaluations:list-evaluations-for-cleaner", ) async def list_evaluations_for_cleaner( evaluations: List[EvaluationInDB] = Depends(list_evaluations_for_cleaner_from_path) ) -> List[EvaluationPublic]: return evaluations @router.get( "/stats/", response_model=EvaluationAggregate, name="evaluations:get-stats-for-cleaner", ) async def get_stats_for_cleaner( cleaner: UserInDB = Depends(get_user_by_username_from_path), evals_repo: EvaluationsRepository = Depends(get_repository(EvaluationsRepository)), ) -> EvaluationAggregate: return await evals_repo.get_cleaner_aggregates(cleaner=cleaner) @router.get( "/{cleaning_id}/", response_model=EvaluationPublic, name="evaluations:get-evaluation-for-cleaner", ) async def get_evaluation_for_cleaner( evaluation: EvaluationInDB = Depends(get_cleaner_evaluation_for_cleaning_from_path), ) -> EvaluationPublic: return evaluation As we've done before, most of the grunt work is handled by our dependencies. Important note! The order in which we define these routes ABSOLUTELY DOES MATTER. If we were to put the /stats/ route after our evaluations:get-evaluation-for-cleaner route, that stats route wouldn't work. FastAPI would assume that "stats" is the ID of a cleaning and throw a 422 error since "stats" is not an integer id. We're primarily using two dependendencies to do the evaluation fetching, so we'll need to create those. api/routes/evaluations.py # ...other code async def list_evaluations_for_cleaner_from_path( cleaner: UserInDB = Depends(get_user_by_username_from_path), evals_repo: EvaluationsRepository = Depends(get_repository(EvaluationsRepository)), ) -> List[EvaluationInDB]: return await evals_repo.list_evaluations_for_cleaner(cleaner=cleaner) async def get_cleaner_evaluation_for_cleaning_from_path( cleaning: CleaningInDB = Depends(get_cleaning_by_id_from_path), cleaner: UserInDB = Depends(get_user_by_username_from_path), evals_repo: EvaluationsRepository = Depends(get_repository(EvaluationsRepository)), ) -> EvaluationInDB: evaluation = await evals_repo.get_cleaner_evaluation_for_cleaning(cleaning=cleaning, cleaner=cleaner) if not evaluation: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No evaluation found for that cleaning.") return evaluation We have two standard dependencies, each using the EvaluationsRepository to fetch evaluations depending on resources fetched from the path parameters. Let's add the needed methods to our evals repo. db/repositories/evaluations.py # ...other code GET_CLEANER_EVALUATION_FOR_CLEANING_QUERY = """ SELECT no_show, cleaning_id, cleaner_id, headline, comment, professionalism, completeness, efficiency, overall_rating, created_at, updated_at FROM cleaning_to_cleaner_evaluations WHERE cleaning_id = :cleaning_id AND cleaner_id = :cleaner_id; """ LIST_EVALUATIONS_FOR_CLEANER_QUERY = """ SELECT no_show, cleaning_id, cleaner_id, headline, comment, professionalism, completeness, efficiency, overall_rating, created_at, updated_at FROM cleaning_to_cleaner_evaluations WHERE cleaner_id = :cleaner_id; """ GET_CLEANER_AGGREGATE_RATINGS_QUERY = """ SELECT AVG(professionalism) AS avg_professionalism, AVG(completeness) AS avg_completeness, AVG(efficiency) AS avg_efficiency, AVG(overall_rating) AS avg_overall_rating, MIN(overall_rating) AS min_overall_rating, MAX(overall_rating) AS max_overall_rating, COUNT(cleaning_id) AS total_evaluations, SUM(no_show::int) AS total_no_show, COUNT(overall_rating) FILTER(WHERE overall_rating = 1) AS one_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 2) AS two_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 3) AS three_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 4) AS four_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 5) AS five_stars FROM cleaning_to_cleaner_evaluations WHERE cleaner_id = :cleaner_id; """ class EvaluationsRepository(BaseRepository): # ...other code async def get_cleaner_evaluation_for_cleaning(self, *, cleaning: CleaningInDB, cleaner: UserInDB) -> EvaluationInDB: evaluation = await self.db.fetch_one( query=GET_CLEANER_EVALUATION_FOR_CLEANING_QUERY, values={"cleaning_id": cleaning.id, "cleaner_id": cleaner.id}, ) if not evaluation: return None return EvaluationInDB(**evaluation) async def list_evaluations_for_cleaner(self, *, cleaner: UserInDB) -> List[EvaluationInDB]: evaluations = await self.db.fetch_all( query=LIST_EVALUATIONS_FOR_CLEANER_QUERY, values={"cleaner_id": cleaner.id} ) return [EvaluationInDB(**e) for e in evaluations] async def get_cleaner_aggregates(self, *, cleaner: UserInDB) -> EvaluationAggregate: return await self.db.fetch_one(query=GET_CLEANER_AGGREGATE_RATINGS_QUERY, values={"cleaner_id": cleaner.id}) Some interesting stuff going on here, mostly in the SQL for our GET_CLEANER_AGGREGATE_RATINGS_QUERY. We'll break down each chunk of SELECT statements to illustrate what's happening. If we only queried the average values, our SQL would look like this: SELECT AVG(professionalism) AS avg_professionalism, AVG(completeness) AS avg_completeness, AVG(efficiency) AS avg_efficiency, AVG(overall_rating) AS avg_overall_rating FROM cleaning_to_cleaner_evaluations WHERE cleaner_id = :cleaner_id; We find all rows where the cleaner_id matches the user in question. We then use the AVG aggregation to find the mean of each rating category. This is what users probably care about most, and so it's important to provide that for each cleaner. Moving on to querying only the sums, here's what our SQL would look like: SELECT COUNT(cleaning_id) AS total_evaluations, SUM(no_show::int) AS total_no_show, COUNT(overall_rating) FILTER(WHERE overall_rating = 1) AS one_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 2) AS two_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 3) AS three_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 4) AS four_stars, COUNT(overall_rating) FILTER(WHERE overall_rating = 5) AS five_stars FROM cleaning_to_cleaner_evaluations WHERE cleaner_id = :cleaner_id; We have two interesting selections and one standard one. • COUNT(cleaning_id) AS total_evaluations simply determines the number of rows that exist for this cleaner. • SUM(no_show::int) AS total_no_show casts the boolean no_show value to an integer of 1 or 0, and then sums the values. • COUNT(overall_rating) FILTER(WHERE overall_rating = 1) ... uses the FILTER statement to only include rows where the overall_rating was assigned a value of 1 and then counts them up. This is done for all star values and will be used to show a bar chart when displaying aggregate values. We also have a maximum and minimum overall rating just to round things off. All together this query provides us with a nice set of aggregate statistics that we can send to our frontend when needed. Doing this in SQL is much more performant than any other approach, so we'll lean heavily on postgres when we need to. Run the tests again and they should all pass. Wrapping Up and Resources Well there you have it. We've added an evaluation system to our application and used SQL aggregations to provide summary statistics for a given cleaner. At the moment there's no payment system, and we're letting users sort that out under the table. Now seems like the right time to start building our front end, so we'll do that in the next post. • Postgresql aggregate functions docs • SQL Bolt Queries with Aggregates Part 1 • SQL Bolt Queries with Aggregates Part 2 • Mode Analytics SQL Aggregations tutorial • Modern SQL Filter Statement guide Github Repo All code up to this point can be found here:
__label__pos
0.99099
Articles with the tag: Close Changelog Close Articles with the tag: Close BINOM.INV Function The BINOM.INV function is one of the statistical functions. It is used to return the smallest value for which the cumulative binomial distribution is greater than or equal to a criterion value. The BINOM.INV function syntax is: BINOM.INV(trials, probability-s, alpha) where trials is the number of trials, a numeric value greater than 0. probability-s is the success probability of each trial, a numeric value greater than 0 but less than 1. alpha is the criterion, a numeric value greater than 0 but less than 1. The numeric values can be entered manually or included into the cells you make reference to. To apply the BINOM.INV function, 1. select the cell where you wish to display the result, 2. click the Insert Function Insert Function icon icon situated at the top toolbar, or right-click within a selected cell and select the Insert Function option from the menu, or click the Function icon icon situated at the formula bar, 3. select the Statistical function group from the list, 4. click the BINOM.INV function, 5. enter the required arguments separating them by commas, 6. press the Enter button. The result will be displayed in the selected cell. BINOM.INV Function Return to previous page Try now for free Try and make your decision No need to install anything to see all the features in action
__label__pos
0.97339
/* $echo FILE: TS_path1.lex $echo Purpose: Pathological test $echo Error --- Rule |RA| does not completely derive a subrule */ /@ @** |TS_path1| grammar.\fbreak Pathological test grammar.\fbreak Rule |RA| does not completely derive a subrule. This is a left or right recursion situation: it depends on how u view the the epsilon situation. i'm slanted towards the left. Before left recursion can take place, one of its subrules must be derived before it can continue deriving its $\beta$ string. I allow printing of the PDF document but there can be down stream annoyances caused by my PDF implementation: the fsc file is expected. now I have corrected the emitted ``xx.w'' file to test for its existance. Also notice that i corrected the single symbol left recursion: i just bypass trying to draw it as it is pathological.\fbreak |RA| $\rightarrow$ $\alpha_{\epsilon}$ |RA| $\beta_{\epsilon}$ \fbreak @/ fsm (fsm-id "TS_path1.lex",fsm-filename TS_path1 ,fsm-namespace NS_TS_path1 ,fsm-class CTS_path1 ,fsm-version "1.0" ,fsm-date "17 Juin 2003",fsm-debug "true" ,fsm-comments "Pathological grammar -- does not derives a terminal string") @"/usr/local/yacco2/compiler/grammars/yacco2_T_includes.T" rules{ Rstart AD AB(){ -> RA } RA AD AB() { -> RA } }// end of rules
__label__pos
0.660522
C++ Manual Instrumentation for OpenTracing This Quickstart will have you configure your tracer to communicate with the Cloud Observability Microsatellites and create a single span on your service. You install both the OpenTracing API and Cloud Observability tracer and then use the OpenTracing and Cloud Observability APIs to instrument your code. While Cloud Observability offers tracers and APIs specific to its tracing software, you will still use the OpenTracing API to fully instrument your code. Be sure you have read and are familiar with both Cloud Observability tracers and the OpenTracing specification in your application’s language. C++ Instrumentation for OpenTracing 1. Follow the instructions in the lightstep-tracer-c++ README for prerequisites and to build and install the OpenTracing library on your machine. 2. Find your access token in Cloud Observability. You’ll need this to configure your Cloud Observability tracer. • Click the Project Settings button. • In the Access Tokens table, click the Copy icon to copy your access token to the clipboard. 3. In your application code, add a reference to the Cloud Observability C++ Tracer and to the OpenTracing API. 1 2 #include <opentracing/tracer.h> #include <lightstep/tracer.h> 4. Early in your application’s initialization, configure the Cloud Observability tracer and register it as the OpenTracing Global Tracer. As part of the configuration, you need to add your access token and add a tag to hold the value of your service’s name. Use the right code for your environment! When initializing the tracer, you pass in properties to the Cloud Observability Microsatellites that collect the span data. Be sure to use the code for your Cloud Observability Microsatellite environment - On-Premise, Cloud Observability Public Microsatellite pool, or Developer Mode Satellite. Start tabs On-Premise Microsatellites 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 const bool use_streaming_tracer = true; //Set to false if not using streaming HTTPvoid initGlobalTracer() void initGlobalTracer() { lightstep::LightStepTracerOptions options; options.component_name = "YOUR_SERVICE_NAME"; options.access_token = "YOUR_ACCESS_TOKEN"; // Configure the tracer to send to on-premise Microsatellite pool: options.collector_plaintext = true; if (use_streaming_tracer) { options.satellite_endpoints = your_load_balancer_DNS_name_or_IP_address;//enter the port your pool uses options.use_stream_recorder = true; } else { options.collector_host = "your_load_balancer_DNS_name_or_IP_address"; options.collector_port = 8360;//enter the port your pool uses options.use_stream_recorder = false; } auto tracer = lightstep::MakeLightStepTracer(std::move(options)); opentracing::Tracer::InitGlobal(tracer); } Public Microsatellites 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 const bool use_streaming_tracer = true; //Set to false if not using streaming HTTPvoid initGlobalTracer() void initGlobalTracer() { lightstep::LightStepTracerOptions options; options.component_name = "YOUR_SERVICE_NAME"; options.access_token = "YOUR_ACCESS_TOKEN"; // Configure the tracer to send to on-premise Microsatellite pool: options.collector_plaintext = true; if (use_streaming_tracer) { options.satellite_endpoints = ingest.lightstep.com; options.use_stream_recorder = true; } else { options.collector_host = "ingest.lightstep.com"; options.collector_port = 443; options.use_stream_recorder = false; } auto tracer = lightstep::MakeLightStepTracer(std::move(options)); opentracing::Tracer::InitGlobal(tracer); } Developer Mode 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 const bool use_streaming_tracer = true; //Set to false if not using streaming HTTPvoid initGlobalTracer() void initGlobalTracer() { lightstep::LightStepTracerOptions options; options.component_name = "YOUR_SERVICE_NAME"; options.access_token = "developer"; // Configure the tracer to send to on-premise Microsatellite pool: options.collector_plaintext = true; if (use_streaming_tracer) { options.satellite_endpoints = localhost; options.use_stream_recorder = true; } else { options.collector_host = "localhost"; options.collector_port = 8360; options.use_stream_recorder = false; } auto tracer = lightstep::MakeLightStepTracer(std::move(options)); opentracing::Tracer::InitGlobal(tracer); } End code tabs 5. Test that everything is connected by sending a test span. Annotate the span by adding a tag and logs, then flush the tracer. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 int main() { initGlobalTracer(); auto span = opentracing::Tracer::Global()->StartSpan("test_span"); span->SetTag("key", "value"); span->Log({{"logkey", "logval"}, {"number", 1}}); span->Finish(); opentracing::Tracer::Global()->Close(); return 0; } 6. Build the app. Depending on the operating system and the compiler toolchain’s default settings, you may need several compiler flags for your compiler to locate the OpenTracing and Cloud Observability include and library paths. See the lightstep-tracer-c++ README for detailed instructions on installing the library for your operating system. The library installs by default to /usr/local/, so it may be necessary to add -I/usr/local/include to the compile and link command line (or using CXXFLAGS and LDFLAGS). For example, place the two snippets above into the file test.cpp, then run: c++ -std=c++11 -I/usr/local/include -L/usr/local/lib -lopentracing -llightstep_tracer -o test test.cpp 7. Run the ./test binary to send a span to Cloud Observability. 8. Open Cloud Observability. You should see your service in the Service directory list. It may take a few moments for your service to display in the Service Directory. To see data immediately, click the Explorer tab to view data in the histogram. Read the OpenTracing C++ README on GitHub to learn how to continue instrumentation in your service. See also Measure your instrumentation quality Updated Mar 2, 2020
__label__pos
0.834168
CGI/Perl Guide | Learning Center | Forums | Advertise | Login Site Search: in   Main Index MAIN INDEX Search Posts SEARCH POSTS Who's Online WHO'S ONLINE Log in LOG IN Home: Perl Programming Help: Intermediate: Arrays   Jono stranger Aug 17, 2001, 7:58 AM Post #1 of 2 (568 views) Arrays Can't Post Hi, I want to do this sort of thing: open INFILE2, "$prf" or die "cannot open address.txt: $!\n"; #Array will hold pointers to arrays, ie: #@struct = (['name1', 'addr1'], # ['name2', 'addr2'], # etc... ); my @records; while(INFILE2) { my ($name, $addr); #Grab 3 lines and store them, quitting on EOF: ($name, undef, $address) = (<INFILE2>, <INFILE2>, <INFILE2>) or last; #Push new data into array: push @records, [$name, $address]; #Skip lines until we see a divider. while(<INFILE2>) { last if /----------/; } print "<TR><TD>$name</TD><TD>$address</TD></TR>"; } close INFILE2; for each record for an undefined number of records. Each one is separated by "----------" and the file I'm reading is basically just a text file, each record can be any length, but the first three lines contain Name, ??, E-mail address of each person the record exists for. Once I've got the first three lines I want to move onto the next record and just ignore the rest of the lines in the record. Does that make sense? Basically I want to store this data in some array (of arrays?) hence the @struct part in the code...and then use the data later in the program. Like just run through the arrays of the three lines, use the last element (e-mail address) then move onto the next one. This code here only displays the data from the first record, Any ideas why? I would like to print out the data for each record, for the number of records in each file (I'm running through lots of files) there can be between 1 and ~1000 records in each file. Please try to help if you can...:) Cheers, Jono rGeoffrey User / Moderator Aug 20, 2001, 2:38 PM Post #2 of 2 (546 views) Re: Arrays [In reply to] Can't Post Here is my input file (I used the same data in both files as I am lazy)... Code Fred Wilma [email protected] some text here ---------- George Jane [email protected] some text here ---------- Homer Marge [email protected] some text here Here is the code... Code #!/usr/local/bin/perl use strict; my @files = ('readrecord.txt', 'readrecord2.txt'); my @results; foreach my $prf (@files) { my @records; open (INFILE2, $prf) or die "cannot read from $prf: $!\n"; local $/ = "----------\n"; while (my $record = <INFILE2>) { chomp $record; my @parts = split ("\n", $record, 4); push (@records, [$parts[0], $parts[2]]); } close INFILE2; push (@results, \@records); } print <<EOD; Content-type: text/html <html><head> <title>See Test Results</title> </head> <body> <table border="1"> EOD foreach my $list (@results) { print "<tr><td colspan='2'>File had ", scalar @{$list}, " records</td></tr>\n"; foreach (@{$list}) { print ("<tr><td>", join ("</td><td>", @{$_}), "</td></tr>\n"); } } print "\n</table></body></html>\n"; It takes a list of files and reads each one in turn. Inside each file it reads one record and collects the 1st and 3rd line. And the @records from each file are placed in @results. Note that I have changed $/ inside the foreach loop so the change won't affect other parts of the program later. The split will make an array of 4 parts, so everything after the 3rd line will stay together in the 4th part. -- Sun Sep 9, 2001 - 1:46:40 GMT, a very special second in the epoch. How will you celebrate?     Search for (options) Powered by Gossamer Forum v.1.2.0 Web Applications & Managed Hosting Powered by Gossamer Threads Visit our Mailing List Archives
__label__pos
0.73163
X Charlotte from New York City Signed up at Highroller Casino 22 minutes ago. » Try Highroller Casino too Do not show again 23 Types of Consensus Mechanisms Used in Blockchains consensus mechanism in blockchain illustratedPublic blockchains unlike centralized systems, are self-regulating systems. The consensus mechanism or consensus method as some call it, ensures the validity of the transactions happening in a network. This means there is no authority that regulates them. Instead, there are hundreds of thousands of participants whose role is to verify and authenticate the transactions that are happening in a particular blockchain. With these regular changes in a blockchain, the publicly shared ledgers require an efficient, functional, fair, reliable, fast, cost efficient and secure mechanism. Many investors prefer a blockchain with the lowest possible transfer cost, the highest possible security and the quickest possible transfer time. But how does the consensus methods come into the picture? Continue below to learn more about what it is and how it works. What is a blockchain consensus model or method? This is a process in which the users of a blockchain network agree on the state of the data in the network. A blockchain consensus method, model, or mechanism is a set of rules that ensures the legitimacy, integrity and reliability of the data. This in turn leads to trust in the blockchain network. Difference between consensus and validation It is important to understand that consensus and validation are different types and stages of a transaction. For one, a blockchain validator validates a transaction by ensuring that it is lawful and not malicious. On the other hand, a consensus defines the order of events until they agree. Therefore, the working mechanism of consensus algorithms involves agreeing on the order of the verified transactions. That means validation happens before a consensus. How transaction verification works in a blockchain There are several steps to include a transaction to a blockchain. Despite the decentralization of cryptos, there is a need to authenticate transactions. This is done using crypto keys that help to identify a user and provide access to their wallet. Users who have a computer in a network earn incentives to verify a transaction. How many blockchain consensus mechanisms exist? With the different types of blockchain technology out there and the vast opportunities offered by blockchain, it can be hard to determine the number of blockchains out there. But what is clear is that there are literally tens of working mechanisms in the consensus algorithm. That said, let us look at several types of blockchain consensus mechanisms and their sub methods. Some of the most important are the 23 different consensus methods described below: Proof of Work A key element of how to achieve consensus is through a distributed network where validators confirm the records of transactions. Bitcoin and other early cryptocurrencies use proof of work. In this protocol, miners who are basically hardware operators take part in the computing power when validating a transaction in a network. For their role, they get compensation in form of cryptos. This is what led to the utilization and transaction recording of the PoW protocols. See a top list over proof of work here or learn more about Bitcoin blockchain which is the most famous PoW based network. Proof of Stake The Proof of stake (POS) is a consensus mechanism that was created to deal with inefficiencies that are common with proof of work protocols. Previously, these inefficiencies were solved through crypto mining. Today, POS uses nodes that have been chosen depending on the platform token stake to audit and record transactions. The Ethereum blockchain merge is a merge in September will change the network from PoW to PoS. Blockchain and computer systems use various version of the POS protocol to achieve the required agreement. The agreement is on a certain value of data or a unique state of a network in distributed processes and multi-agent systems such as cryptocurrencies. Most of the modern Blockchain projects now commonly use the POS consensus mechanism. Some of these are Cosmos (ATOM), Cardano (ADA), Polkadot (DOT), Solana (SOL), VeChain (VET), and Tezos (XTZ), to name a few. One of the reasons why it’s popular is because it’s more scalable by far. POS is also more flexible and environmentally friendly as compared to the POW iterations. See a top list over proof of stake coins & tokens here. There are a huge amount of different proof of stake types and some of the most important ones are mentioned below. Liquid proof of stake (LPoS) Tezos Blockchain uses liquid proof of stake (LPoS) as a validation mechanism. With this protocol, holders of a token can pass their validation rights to other users. However, holders achieve this while still maintaining their token ownership. Therefore, the token remains in the wallet of the delegator. If there is a security mishap, the penalty goes to the validator. Its main downside is that it’s among the slowest blockchain validation. Delegated Proof of Stake (DPoS) This is another consensus mechanism that is commonly used in projects such as Steemit and EOS network. It was developed by Dan Larimer and works similarly to the LPOS. However, users vote on the delegate who should get the blockchain’s new block. The token holders also vote on the person to validate a transaction on a network. The delegate’s token number determines how much power each vote has. That means that token holders with more tokens are more likely to become validators. An example of DPos is the EOS token. Some blockchains combine both delegated proof of stake and another consensus method, such as Solana network that combine it with proof of history. Pure Proof of Stake (PPoS) The native coin (ALGO) of the Algorand network was the first user of the PPoS. This blockchain’s aim is to provide security, decentralization, and scalability in an environmental-friendly way. The consensus mechanism uses the Byzantine consensus and a more egalitarian approach as compared to the POS. Bonded Proof of Stake (BPoS) The Bonded Proof of stake works in the same way as the LPOS. Just like LPOS, holders of a token can transfer their rights to vote without the custodial rights. This means that just like in LPoS, token holders can vote for or against protocol change. However, BPOS is different from LPOS in that if there is a security lapse, the blockchain deducts both the delegator and the validator’s stake. This is unlike LPOS where only the stake of the validator is deducted. Two of the earliest projects that used the BPoS protocol were Cosmos and IRISnet. Nominated Proof of Stake (NPoS) One of the key differences between NPOS and other consensus mechanisms is that validators are chosen automatically. However, they need to build their reputation to prove their reliability in the bigger community. Validators can do that by providing low gas fees on transactions. Blockchain projects including Cosmos, Kusama blockchain, EOS and Polkadot use the NPoS consensus algorithm. Hybrid Proof of Stake (HPoS) Just like the name suggests, Hybrid Proof of Stake (HPoS)‍ marries the proof of work with the proof of stake. Both mechanisms work hand in hand to ensure the security of the network. These rules require miners to produce some new blocks while the validators vote on whether they are valid or not. Dash blockchain and Decred are some notable projects that have adopted an HPoS consensus mechanism. In most cases, these rely on POW miners to get new blocks that accommodate transactions. These are then passed to the POS validators who vote on whether the blocks and records need to be confirmed or not. Thresholded Proof of Stake (TPoS) In this approach, both stakers and validators earn the staking rewards. However, their stake depends on the percentage of Near Staked with a certain percentage shared up to a particular maximum. An example of this is the Near Mechanisms with the Near Blockchain and its native token with the same name. Leased Proof of Stake (LPoS) Commonly used on the Waves platform, this is a proof of stake mechanism. It enables the holders of a token to lend their tokens. They in turn earn a percentage of the payout. This is a departure from the traditional proof of stake protocol. Previously, every block could add a new block to a blockchain. But with a leased POS, users can either choose a full node or they can lease their stake to the full node with the receiving rewards. This kind of system allows any person to participate in Wave network maintenance. Less common blockchain consensus methods On top of the above various types of consensus algorithms, there are other less common consensus mechanisms. These proof of stake variants include: Proof of History (PoH) This consensus algorithms blockchain uses the Proof of stake but calculates the time differently. For instance, It changes historical events into a hash that can be generated using certain previous events. The computation sequence in Proof of History provides a way of verifying the time that has passed between two events. The Solana founder developed this consensus mechanism and now use it together with DPoS. This makes Solana one of the fastest blockchain algorithm, with transaction speeds of up to 65,000 TSP. Proof of Authority (POA) Proof of Authority is an algorithm that uses blockchain to deliver faster transaction speed. It uses a consensus mechanism where the stake is the identity. One of the most notable blockchains that use this mechanism is Vechain. The founder of Ethereum Dr. Garvin started the blockchain in 2015. However, there are other blockchains that use the consensus mechanism such as Kovan and Giveth. Therefore, POS is a highly centralized consensus method that identifies validators. It is, therefore, suitable for private blockchains and consortiums such as insurance companies and banks. Proof of Capacity (PoC) This consensus mechanism uses the hard disk space of a mining node to determine the hard drive space of a mining node. In this system, miners can precalculate the POW functions and keep them in an HDD. This makes it less time-consuming but more energy efficient. Creating a new block takes an average of 4 seconds. Burstcoin (SIGNA) is one of the tokens that used this new mining method. Update from 2/9, 2022: Burstcoin is not active anymore. Proof of Elapsed Time (PoET) Intel created this consensus method in 2016. It enables blockchains to determine the next creator of the next Block. Additionally, PoeT uses a lottery method that distributes the winning chances to all network users. Hyperledger Sawtooth, which focuses on building distributed ledgers uses this consensus mechanism. Proof of Validation (PoV) This is a unique consensus mechanism that aims to achieve consensus using the validator staked nodes. In this protocol, all the nodes of POV system maintain the transaction sequence in the blocks created on that blockchain. Proof of Importance (PoI) The Proof of Importance is a blockchain consensus method that aims to show the utility of a node in the cryptocurrency system. The final goal is to create a block. The NEM token (XEM) uses PoI. Delegated Proof of Contribution Protocol (DPoC) This is a democratized and decentralized governance and incentive protocol. In this consensus mechanism, holders use their governance rights by delegating their stakes to people contributing to the growth of a network. A random selection picks one delegate who is voted to add to the block. Therefore, the goal of DPOS is to use voting delegates to improve the POS mechanism by ensuring the representation of a transaction within the blockchain. It can therefore be termed as a technology-based democracy that uses voting to prevent malicious usage and centralization. Proof-of-Stake Voting (PoSV) The POSV is a blockchain consensus mechanism that works similarly to the proof of stake. TomoChain uses a type of PoSV algorithm. Proof of Activity (PoA) This type of blockchain technology combines the POS and POW mechanisms. It requires the miners to perform heavy computation in order to add a new block with header information and the reward address. After this, one empty block will be chosen depending on the tokens in their account. The person who mined the block will have an opportunity to add it to the block. This project was launched in 2016 and is most conspicuous in the Decred (DCR) blockchain. Proof of Burn (PoB) This consensus method requires the miners to get to a consensus by burning coins. Users permanently ban coins from regular circulation. The miner sends cryptos to a verifiable public address. This address is known as an eater address. The goal is for the miner to make some type of investment into the blockchain. Since there are high numbers of cryptos burned on the mechanism, the miner gets more mining power. Some of the coins that use this mechanism are Slimcoin, Counterparty, and Factom. For instance, Counterparty requires users to send bitcoins to a certain address and in return get XCP tokens. Ripple Protocol Consensus RippleNet blockchain mechanism is similar to other blockchain protocols such as Bitcoin and Ethereum. However, its major difference is that it has the goal of ensuring efficient and affordable transfer of funds to other parts of the world. It uses the Ripple Protocol Consensus Algorithm to achieve this. Stampery Blockchain Timestamping Architecture (BTA) This is one of the many types of blockchain technology that can timestamp and anchor an infinite quantity of data in a blockchain. The goal of the consensus mechanism is to ensure the affordability and scalability of the data. At the same time, it helps to maintain integrity, efficiency, and ownership of transactions with the help of cryptocurrency proof. One of the proofs of stake variants in this consensus method is the Byzantine Fault Tolerance (BFT). An example of a blockchain that uses this mechanism is the Hperledger Fabric. The blockchain uses less than 20 validators that are preselected to determine the network’s consensus. Federated Byzantine Agreement is another branch of BTA. It uses a variation of this consensus mechanism. Anonymous proof of stake (ZPoS) PIVX, a project that aims to provide security of the global digital cash is the brain behind this consensus mechanism. It does this through the use of data protection. The project enables users to be their own bank with full control of their digital assets. ZPOS uses zerocoin protocol to make the consensus method possible. The number of coins that each person stakes in a network remain private. This means that people can own private cryptocurrency balances while getting rewards privately and securely. Conclusion about consensus methods The above are the most common types of blockchain technology consensus mechanisms. While there may be others out there, validators commonly use these types. Generally, all these algorithms have the same goal of ensuring the integrity of a transaction. However, blockchain developers keep on mixing and matching existing protocols. They also try to find new ways to streamline the on-chain governance. This is an indication that in the days to come, there will be an increase in the number of consensus mechanisms. All in all, while the above consensus methods are a broader view of the proof of stake we use today, there is nothing constant in the blockchain space. Thousands of blockchain projects are already using some kind of PoS. In fact, all consensus methods including permissioned blockchain systems and permissionless blockchain systems are working to improve network decision-making. Additionally, they also seek to improve resource efficiency and scalability. Therefore, we expect consensus mechanisms to keep on playing an important role in the development of the blockchain industry. New Casino Reviews New Crypto Casinos Best Crypto Casinos Recent Crypto Sites Recent Crypto Coins • CorgiAI logo  CorgiAI CRONOS-TOKEN • IPVERSE logo  IPVERSE ETHEREUM-TOKEN • Book.io logo  Book.io CARDANO-TOKEN • Smart logo  Smart NATIVE-COIN Keep up to date with Our Newsletter Sign up to our newsletter to get the latest crypto news, new casinos, bonus offers and other exciting exclusives. * indicates required CryptoLists.com Copyright © 2019-2022, by Crypto Lists Ltd (CryptoLists.com). Company name: Crypto Lists Limited. Address: 5 Upper Montagu Street, LONDON W1H 2AG, England. Jump to top
__label__pos
0.775798
This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5 use PERL_REVISION in os2/Makefile.SHs [perl5.git] / regen_perly.pl CommitLineData 0de566d7 DM 1#!/usr/bin/perl 2# 3# regen_perly.pl, DAPM 12-Feb-04 4# 2eee27d7 5# Copyright (c) 2004, 2005, 2006, 2009, 2010, 2011 Larry Wall 0de566d7 DM 6# 7# Given an input file perly.y, run bison on it and produce 8# the following output files: 9# 10# perly.h standard bison header file with minor doctoring of 11# #line directives plus adding a #ifdef PERL_CORE 12# 13# perly.tab the parser table C definitions extracted from the bison output 0539ab63 14# plus an extra table generated by this script. 0de566d7 DM 15# 16# perly.act the action case statements extracted from the bison output 17# 18# Note that perly.c is *not* regenerated - this is now a static file which 19# is not dependent on perly.y any more. 20# 21# If a filename of the form foo.y is given on the command line, then 22# this is used instead as the basename for all the files mentioned 23# above. 24# 25# Note that temporary files of the form perlytmp.h and perlytmp.c are 26# created and then deleted during this process 27# 28# Note also that this script is intended to be run on a UNIX system; 29# it may work elsewhere but no specific attempt has been made to make it 30# portable. 31 e8fb9efb 32use 5.006; 0de566d7 DM 33sub usage { die "usage: $0 [ -b bison_executable ] [ file.y ]\n" } 34 35use warnings; 36use strict; 37 e64a0c47 38our $Verbose; 3d7c117d 39BEGIN { require './regen/regen_lib.pl'; } a9718e07 40 0de566d7 DM 41my $bison = 'bison'; 42 43if (@ARGV >= 2 and $ARGV[0] eq '-b') { 44 shift; 45 $bison = shift; 46} 47 48my $y_file = shift || 'perly.y'; 49 50usage unless @ARGV==0 && $y_file =~ /\.y$/; 51 52(my $h_file = $y_file) =~ s/\.y$/.h/; 53(my $act_file = $y_file) =~ s/\.y$/.act/; 54(my $tab_file = $y_file) =~ s/\.y$/.tab/; 55(my $tmpc_file = $y_file) =~ s/\.y$/tmp.c/; 56(my $tmph_file = $y_file) =~ s/\.y$/tmp.h/; 57 58# the yytranslate[] table generated by bison is ASCII/EBCDIC sensitive 59 60die "$0: must be run on an ASCII system\n" unless ord 'A' == 65; 61 62# check for correct version number. The constraints are: 63# * must be >= 1.24 to avoid licensing issues. 64# * it must generate the yystos[] table. Version 1.28 doesn't generate 65# this; 1.35+ does 66# * Must produce output which is extractable by the regexes below 67# * Must produce the right values. 8abc1060 68# These last two constraints may well be met by earlier versions, but 0de566d7 DM 69# I simply haven't tested them yet. If it works for you, then modify 70# the test below to allow that version too. DAPM Feb 04. 71 72my $version = `$bison -V`; 7b931d50 LB 73unless ($version) { die <<EOF; } 74Could not find a version of bison in your path. Please install bison. 75EOF 76 9c221ee4 NC 77# Don't change this to add new bison versions without testing that the generated 78# files actually work :-) Win32 in particular may not like them. :-( 86b50d93 79unless ($version =~ /\b(1\.875[a-z]?|2\.[0134567]|3\.[0-4])\b/) { die <<EOF; } 0de566d7 80 f39ff1f3 81You have the wrong version of bison in your path; currently versions 86b50d93 821.875, 2.0-2.7 or 3.0-3.4 are known to work. Try installing 9c221ee4 83 http://ftp.gnu.org/gnu/bison/bison-2.5.1.tar.gz 0de566d7 DM 84or similar. Your bison identifies itself as: 85 86$version 87EOF 88 9c221ee4 NC 89# bison's version number, not the entire string, is most useful later on. 90$version = $1; 91 0de566d7 DM 92# creates $tmpc_file and $tmph_file 93my_system("$bison -d -o $tmpc_file $y_file"); 94 e8fb9efb 95open my $ctmp_fh, '<', $tmpc_file or die "Can't open $tmpc_file: $!\n"; 0de566d7 96my $clines; e8fb9efb 97{ local $/; $clines = <$ctmp_fh>; } 0de566d7 DM 98die "failed to read $tmpc_file: length mismatch\n" 99 unless length $clines == -s $tmpc_file; e8fb9efb 100close $ctmp_fh; 0de566d7 DM 101 102my ($actlines, $tablines) = extract($clines); 103 6c7ae946 104our %tokens; d5c6462e 105$tablines .= make_type_tab($y_file, $tablines); 0539ab63 106 cc49830d NC 107my ($act_fh, $tab_fh, $h_fh) = map { 108 open_new($_, '>', { by => $0, from => $y_file }); 109} $act_file, $tab_file, $h_file; 0de566d7 110 cc49830d 111print $act_fh $actlines; e8fb9efb 112 cc49830d 113print $tab_fh $tablines; 0de566d7 DM 114 115unlink $tmpc_file; 116 117# Wrap PERL_CORE round the symbol definitions. Also, the 96f4e226 SH 118# C<#line 30 "perly.y"> confuses the Win32 resource compiler and the 119# C<#line 188 "perlytmp.h"> gets picked up by make depend, so remove them. 0de566d7 120 e8fb9efb 121open my $tmph_fh, '<', $tmph_file or die "Can't open $tmph_file: $!\n"; e8fb9efb 122 f39ff1f3 DM 123# add integer-encoded #def of the bison version 124 125{ 126 $version =~ /^(\d+)\.(\d+)/ 127 or die "Can't handle bison version format: '$version'"; 128 my ($v1,$v2) = ($1,$2); 129 die "Unexpectedly large bison version '$v1'" if $v1 > 99; 130 die "Unexpectedly large bison subversion '$v2'" if $v2 > 9999; 131 132 printf $h_fh "#define PERL_BISON_VERSION %2d%04d\n\n", $v1, $v2; 133} 134 0de566d7 135my $endcore_done = 0; 2434f628 136# Token macros need to be generated manually from bison 2.4 on 9c221ee4 137my $gather_tokens = $version >= 2.4 ? undef : 0; ce1534ab 138my $tokens; e8fb9efb 139while (<$tmph_fh>) { 04ff073f JL 140 # bison 2.6 adds header guards, which break things because of where we 141 # insert #ifdef PERL_CORE, so strip them because they aren't important 142 next if /YY_PERLYTMP_H/; 143 e8fb9efb 144 print $h_fh "#ifdef PERL_CORE\n" if $. == 1; 0de566d7 145 if (!$endcore_done and /YYSTYPE_IS_DECLARED/) { 6c7ae946 FC 146 print $h_fh <<h; 147#ifdef PERL_IN_TOKE_C 148static bool 149S_is_opval_token(int type) { 150 switch (type) { 151h 152 print $h_fh <<i for sort grep $tokens{$_} eq 'opval', keys %tokens; 153 case $_: 154i 155 print $h_fh <<j; 156 return 1; 157 } 158 return 0; 159} 160#endif /* PERL_IN_TOKE_C */ 161#endif /* PERL_CORE */ 162j 0de566d7 DM 163 $endcore_done = 1; 164 } 96f4e226 165 next if /^#line \d+ ".*"/; ce1534ab VP 166 if (not defined $gather_tokens) { 167 $gather_tokens = 1 if /^\s* enum \s* yytokentype \s* \{/x; 168 } 169 elsif ($gather_tokens) { 170 if (/^\# \s* endif/x) { # The #endif just after the end of the token enum 171 $gather_tokens = 0; 172 $_ .= "\n/* Tokens. */\n$tokens"; 173 } 174 else { 175 my ($tok, $val) = /(\w+) \s* = \s* (\d+)/x; 176 $tokens .= "#define $tok $val\n" if $tok; 177 } 178 } e8fb9efb 179 print $h_fh $_; 0de566d7 180} e8fb9efb 181close $tmph_fh; 0de566d7 DM 182unlink $tmph_file; 183 c24c946d NC 184foreach ($act_fh, $tab_fh, $h_fh) { 185 read_only_bottom_close_and_rename($_, ['regen_perly.pl', $y_file]); 186} 0de566d7 DM 187 188exit 0; 189 190 59966791 DM 191# extract the tables and actions from the generated .c file 192 0de566d7 DM 193sub extract { 194 my $clines = shift; 195 my $tablines; 196 my $actlines; 197 f39ff1f3 198 my $last_table = $version >= 3 ? 'yyr2' : 'yystos'; 0de566d7 DM 199 $clines =~ m@ 200 (?: 201 ^/* YYFINAL[^\n]+\n #optional comment 202 )? 203 \# \s* define \s* YYFINAL # first #define 204 .*? # other defines + most tables f39ff1f3 205 $last_table\[\]\s*= # start of last table 0de566d7 DM 206 .*? 207 }\s*; # end of last table 208 @xms 209 or die "Can't extract tables from $tmpc_file\n"; 210 $tablines = $&; 211 212 59966791 DM 213 # extract all the cases in the big action switch statement 214 0de566d7 215 $clines =~ m@ 59966791 DM 216 switch \s* \( \s* yyn \s* \) \s* { \s* 217 ( .*? default: \s* break; \s* ) 218 } 0de566d7 DM 219 @xms 220 or die "Can't extract actions from $tmpc_file\n"; 221 $actlines = $1; 222 ce1534ab VP 223 # Remove extraneous comments from bison 2.4 224 $actlines =~ s!\s* /\* \s* Line \s* \d+ \s* of \s* yacc\.c \s* \*/!!gx; 225 0d6f9730 DM 226 # C<#line 188 "perlytmp.c"> gets picked up by make depend, so remove them. 227 $actlines =~ s/^#line \d+ "\Q$tmpc_file\E".*$//gm; 228 1654d593 DM 229 # convert yyvsp[nnn] into ps[nnn].val 230 231 $actlines =~ s/yyvsp\[(.*?)\]/ps[$1].val/g 232 or die "Can't convert value stack name\n"; 233 0de566d7 DM 234 return $actlines. "\n", $tablines. "\n"; 235} 236 d5c6462e DM 237# Generate a table, yy_type_tab[], that specifies for each token, what 238# type of value it holds. 0539ab63 239# d5c6462e DM 240# Read the .y file and extract a list of all the token names and 241# non-terminal names; then scan the string $tablines for the table yytname, 242# which gives the token index of each token/non-terminal; then use this to 243# create yy_type_tab. 0539ab63 244# d5c6462e DM 245# ie given (in perly.y), 246# 247# %token <opval> A 248# %token <ival> B 249# %type <pval> C 250# %type <opval> D 251# 252# and (in $tablines), 253# 254# yytname[] = { "A" "B", "C", "D", "E" }; 0539ab63 DM 255# 256# then return d5c6462e DM 257# 258# typedef enum { toketype_ival, toketype_opval, toketype_pval } toketypes; 259# 260# static const toketypes yy_type_tab[] 261# = { toketype_opval, toketype_ival, toketype_pval, 262# toketype_opval, toketype_ival } 263# 264# where "E" has the default type. The default type is determined 265# by the __DEFAULT__ comment next to the appropriate union member in 266# perly.y 0539ab63 267 d5c6462e 268sub make_type_tab { 0539ab63 269 my ($y_file, $tablines) = @_; 6c7ae946 270 my %just_tokens; 0539ab63 271 my %tokens; d5c6462e DM 272 my %types; 273 my $default_token; 0539ab63 DM 274 open my $fh, '<', $y_file or die "Can't open $y_file: $!\n"; 275 while (<$fh>) { b5bbe64a 276 if (/(\$\d+)\s*=[^=]/) { 29522234 DM 277 warn "$y_file:$.: dangerous assignment to $1: $_"; 278 } 279 d5c6462e DM 280 if (/__DEFAULT__/) { 281 m{(\w+) \s* ; \s* /\* \s* __DEFAULT__}x 282 or die "$y_file: can't parse __DEFAULT__ line: $_"; 283 die "$y_file: duplicate __DEFAULT__ line: $_" 284 if defined $default_token; 285 $default_token = $1; 286 next; 287 } 288 289 next unless /^%(token|type)/; 6c7ae946 290 s/^%((token)|type)\s+<(\w+)>\s+// d5c6462e 291 or die "$y_file: unparseable token/type line: $_"; 6c7ae946 FC 292 for (split ' ', $_) { 293 $tokens{$_} = $3; 294 if ($2) { 295 $just_tokens{$_} = $3; 296 } 297 } 298 $types{$3} = 1; 0539ab63 299 } 6c7ae946 300 *tokens = \%just_tokens; # perly.h needs this d5c6462e DM 301 die "$y_file: no __DEFAULT__ token defined\n" unless $default_token; 302 $types{$default_token} = 1; 0539ab63 DM 303 304 $tablines =~ /^\Qstatic const char *const yytname[] =\E\n efcfdf1f 305 \{\n 0539ab63 DM 306 (.*?) 307 ^}; 308 /xsm 309 or die "Can't extract yytname[] from table string\n"; 310 my $fields = $1; d5c6462e DM 311 $fields =~ s{"([^"]+)"} 312 { "toketype_" . 313 (defined $tokens{$1} ? $tokens{$1} : $default_token) 314 }ge; f39ff1f3 315 $fields =~ s/, \s* (?:0|YY_NULL|YY_NULLPTR) \s* $//x d5c6462e DM 316 or die "make_type_tab: couldn't delete trailing ',0'\n"; 317 0539ab63 318 return d5c6462e DM 319 "\ntypedef enum {\n\t" 320 . join(", ", map "toketype_$_", sort keys %types) 321 . "\n} toketypes;\n\n" 322 . "/* type of each token/terminal */\n" d5c6462e DM 323 . "static const toketypes yy_type_tab[] =\n{\n" 324 . $fields 325 . "\n};\n"; 0539ab63 DM 326} 327 328 0de566d7 329sub my_system { 95a1c520 DM 330 if ($Verbose) { 331 print "executing: @_\n"; 332 } 0de566d7 DM 333 system(@_); 334 if ($? == -1) { d5c6462e 335 die "failed to execute command '@_': $!\n"; 0de566d7 DM 336 } 337 elsif ($? & 127) { 338 die sprintf "command '@_' died with signal %d\n", 339 ($? & 127); 340 } 341 elsif ($? >> 8) { 342 die sprintf "command '@_' exited with value %d\n", $? >> 8; 343 } 344}
__label__pos
0.911357
[32d3b3]: tools-for-build / determine-endianness.c  Maximize  Restore  History Download this file 52 lines (46 with data), 1.6 kB 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 /* * Test for the endianness of the target platform (needed for MIPS * support, at the very least, as systems with either endianness exist * in the wild). */ /* * This software is part of the SBCL system. See the README file for * more information. * * While most of SBCL is derived from the CMU CL system, many * utilities for the build process (like this one) were written from * scratch after the fork from CMU CL. * * This software is in the public domain and is provided with * absolutely no warranty. See the COPYING and CREDITS files for * more information. */ #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int foo = 0x20212223; char *bar = (char *) &foo; switch(*bar) { case ' ': printf(" :big-endian"); break; case '#': printf(" :little-endian"); break; default: /* FIXME: How do we do sane error processing in Unix? This program will be called from a script, in a manner somewhat like: tools-for-build/determine-endianness >> $ltf but what if we have a too-smart C compiler that actually gets us down to this branch? I suppose that if we have a C compiler that is that smart, we're doomed to miscompile the runtime anyway, so we won't get here. Still, it might be good to have "set -e" in the various scripts so that we can exit with an error here and have it be caught by the build tools. -- CSR, 2002-11-24 */ exit(1); } exit(0); } Get latest updates about Open Source Projects, Conferences and News. Sign up for the SourceForge newsletter: No, thanks
__label__pos
0.656061
adding ‘first’ and ‘last’ class to Joomla Menu items : Menu overrides Share! one often needs to define the first and last element in navigation menu. It is needed when you want to remove the last/first unwanted border or maybe if you want to highlight the first item differently. The effect can be achieved by adding an extra class “first” and “last” to the respective child elements of the menus. It is a much sought after feature and I feel should be made the default feature of joomla menu system. Joomla has a mod_mainmenu module for creating menus. Joomla allows the users to create overrides to get this special enhancements. We would make an override to joomla’s ‘mod_mainmenu’ module to get out classification finctionality.   The overrides are placed in a folder named “html” inside your template folder. Inside ‘html’ place another folder called ‘mod_mainmenu’ to specify the override. Next, copy the file default.php from modules/mod_mainmenu/tmpl from your joomla filesystem to our folder(mod_mainmenu). I recommend you get your own file it may avoid any version related issues. Your default.php file is now located similar to: templates/MYTEMPLATE/html/mod_mainmenu/default.php open the file and navigate to the ‘ul’ component which looks like if ($node->name() == 'ul') { foreach ($node->children() as $child) { if ($child->attributes('access') > $user->get('aid', 0)) { $node->removeChild($child); } } } We will add a few lines of code to this to get the ‘first’ and ‘last’ class in the menu items. Our new block will look like : if ($node->name() == 'ul') { foreach ($node->children() as $child) { if ($child->attributes('access') > $user->get('aid', 0)) { $node->removeChild($child); } } //NEW CODE STARTS HERE $children_count = count($node->children()); $children_index = 0; foreach ($node->children() as $child) { if ($children_index == 0) { $child->addAttribute('class', 'first'); } if ($children_index == $children_count - 1) { $child->addAttribute('class', 'last'); } $children_index++; } //ENDS HERE } We are done. Just update the file on your webserver and test it. Now the menu child items must get classified. You can now use these classes to transform the look of its children elements.   for joomla 1.6, 1.7 if ($item->deeper) { $class .= 'deeper '; } Replace this with: $currentitemcount ++; if ($item->shallower or $currentitemcount == count($list)) { $class .= 'last '; } if ($lastdeeper or $currentitemcount == 1) { $class .= 'first '; } if ($item->deeper) { $class .= 'deeper '; $lastdeeper = true; } else { $lastdeeper = false; } Share! Leave a comment
__label__pos
0.94853
Quantcast groovy git commit: add tests Previous Topic Next Topic   classic Classic list List threaded Threaded 1 message Options Reply | Threaded Open this post in threaded view |   Report Content as Inappropriate groovy git commit: add tests jwagenleitner-2 Repository: groovy Updated Branches:   refs/heads/master beab89aff -> d40a6400c add tests Project: http://git-wip-us.apache.org/repos/asf/groovy/repo Commit: http://git-wip-us.apache.org/repos/asf/groovy/commit/d40a6400 Tree: http://git-wip-us.apache.org/repos/asf/groovy/tree/d40a6400 Diff: http://git-wip-us.apache.org/repos/asf/groovy/diff/d40a6400 Branch: refs/heads/master Commit: d40a6400c3151ac4223c0312ee5a5c1f70460fc7 Parents: beab89a Author: John Wagenleitner <[hidden email]> Authored: Sun Feb 12 13:13:22 2017 -0800 Committer: John Wagenleitner <[hidden email]> Committed: Sun Feb 12 13:13:22 2017 -0800 ----------------------------------------------------------------------  .../reflection/ClassInfoLeakStressTest.java     | 101 ++++++++++++++  .../util/ManagedConcurrentMapStressTest.java    | 136 +++++++++++++++++++  .../ManagedConcurrentValueMapStressTest.java    | 135 ++++++++++++++++++  3 files changed, 372 insertions(+) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/groovy/blob/d40a6400/subprojects/stress/src/test/java/org/codehaus/groovy/reflection/ClassInfoLeakStressTest.java ---------------------------------------------------------------------- diff --git a/subprojects/stress/src/test/java/org/codehaus/groovy/reflection/ClassInfoLeakStressTest.java b/subprojects/stress/src/test/java/org/codehaus/groovy/reflection/ClassInfoLeakStressTest.java new file mode 100644 index 0000000..fa4f2ff --- /dev/null +++ b/subprojects/stress/src/test/java/org/codehaus/groovy/reflection/ClassInfoLeakStressTest.java @@ -0,0 +1,101 @@ +/* + *  Licensed to the Apache Software Foundation (ASF) under one + *  or more contributor license agreements.  See the NOTICE file + *  distributed with this work for additional information + *  regarding copyright ownership.  The ASF licenses this file + *  to you 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. + */ +package org.codehaus.groovy.reflection; + +import groovy.lang.GroovyClassLoader; +import org.apache.groovy.stress.util.GCUtils; +import org.codehaus.groovy.util.ReferenceBundle; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; +import java.util.ArrayList; +import java.util.List; + +import org.codehaus.groovy.util.ReferenceManager; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ClassInfoLeakStressTest { + +    private static final int NUM_OBJECTS = 3101; +    private static ReferenceBundle bundle = ReferenceBundle.getWeakBundle(); + +    private ReferenceQueue<ClassLoader> classLoaderQueue = new ReferenceQueue<ClassLoader>(); +    private ReferenceQueue<Class<?>> classQueue = new ReferenceQueue<Class<?>>(); +    private ReferenceQueue<ClassInfo> classInfoQueue = new ReferenceQueue<ClassInfo>(); + +    // Used to keep a hard reference to the References so they are not collected +    private List<Reference<?>> refList = new ArrayList<Reference<?>>(NUM_OBJECTS * 3); + +    @Before +    public void setUp() { +        // Make sure we switch over to callback manager +        ReferenceManager manager = bundle.getManager(); +        for (int i = 0; i < 1501; i++) { +            manager.afterReferenceCreation(null); +        } +    } + +    @Test +    public void testLeak() { +        assertFalse(Boolean.getBoolean("groovy.use.classvalue")); +        for (int i = 0; i < NUM_OBJECTS; i++) { +            GroovyClassLoader gcl = new GroovyClassLoader(); +            Class scriptClass = gcl.parseClass("int myvar = " + i); +            ClassInfo ci = ClassInfo.getClassInfo(scriptClass); +            Reference<ClassLoader> classLoaderRef = new WeakReference<ClassLoader>(gcl, classLoaderQueue); +            Reference<Class<?>> classRef = new WeakReference<Class<?>>(scriptClass, classQueue); +            Reference<ClassInfo> classInfoRef = new WeakReference<ClassInfo>(ci, classInfoQueue); +            refList.add(classLoaderRef); +            refList.add(classRef); +            refList.add(classInfoRef); +            gcl = null; +            scriptClass = null; +            ci = null; +            GCUtils.gc(); +        } + +        // Add new class to help evict the last collected entry +        GroovyClassLoader gcl = new GroovyClassLoader(); +        Class scriptClass = gcl.parseClass("int myvar = 7777"); +        ClassInfo ci = ClassInfo.getClassInfo(scriptClass); + +        GCUtils.gc(); + +        // All objects should have been collected +        assertEquals("GroovyClassLoaders not collected by GC", NUM_OBJECTS, queueSize(classLoaderQueue)); +        assertEquals("Script Classes not collected by GC", NUM_OBJECTS, queueSize(classQueue)); + +        int ciSize = queueSize(classInfoQueue); +        assertEquals("ClassInfo objects [" + ciSize + "] collected by GC, expected [" + NUM_OBJECTS + "]", +                NUM_OBJECTS, ciSize); +    } + +    private int queueSize(ReferenceQueue<?> queue) { +        int size = 0; +        while (queue.poll() != null) { +            ++size; +        } +        return size; +    } + +} http://git-wip-us.apache.org/repos/asf/groovy/blob/d40a6400/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentMapStressTest.java ---------------------------------------------------------------------- diff --git a/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentMapStressTest.java b/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentMapStressTest.java new file mode 100644 index 0000000..0fb936f --- /dev/null +++ b/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentMapStressTest.java @@ -0,0 +1,136 @@ +/* + *  Licensed to the Apache Software Foundation (ASF) under one + *  or more contributor license agreements.  See the NOTICE file + *  distributed with this work for additional information + *  regarding copyright ownership.  The ASF licenses this file + *  to you 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. + */ +package org.codehaus.groovy.util; + +import org.apache.groovy.stress.util.GCUtils; +import org.apache.groovy.stress.util.ThreadUtils; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class ManagedConcurrentMapStressTest { + +    static final int ENTRY_COUNT = 10371; + +    static final ReferenceBundle bundle = ReferenceBundle.getWeakBundle(); + +    @Test +    public void testMapRemovesCollectedReferences() throws Exception { +        ManagedConcurrentMap<Object, String> map = new ManagedConcurrentMap<Object, String>(bundle); + +        // Keep a hardref so we can test get later +        List<Object> keyList = populate(map); +        assertEquals(ENTRY_COUNT, map.size()); + +        // Make sure we still have our entries, sample a few +        Object key1337 = keyList.remove(1337); +        assertEquals("value1337", map.get(key1337)); + +        Object key77 = keyList.remove(77); +        assertEquals("value77", map.get(key77)); + +        key1337 = null; +        key77 = null; + +        GCUtils.gc(); +        assertEquals(ENTRY_COUNT - 2, map.size()); +        for (Object o : map.values()) { +            if (o instanceof AbstractConcurrentMapBase.Entry<?>) { +                @SuppressWarnings("unchecked") +                AbstractConcurrentMapBase.Entry<String> e = (AbstractConcurrentMapBase.Entry)o; +                if ("value77".equals(e.getValue()) || "value1337".equals(e.getValue())) { +                    fail("Entries not removed from map"); +                } +            } else { +                fail("No Entry found"); +            } +        } + +        // Clear all refs and gc() +        keyList.clear(); +        GCUtils.gc(); + +        // Add an entries to force ReferenceManager.removeStaleEntries +        map.put(new Object(), "last"); +        assertEquals("Map removed weak entries", 1, map.size()); +    } + +    /** +     * This tests for deadlock which can happen if more than one thread is allowed +     * to process entries from the same RefQ. We run multiple iterations because it +     * wont always be detected one run. +     * +     * @throws Exception +     */ +    @Test +    public void testMultipleThreadsPutWhileRemovingRefs() throws Exception { +        for (int i = 0; i < 10; i++) { +            ManagedConcurrentMap<Object, String> map = new ManagedConcurrentMap<Object, String>(bundle); +            multipleThreadsPutWhileRemovingRefs(map); +        } +    } + +    private void multipleThreadsPutWhileRemovingRefs(final ManagedConcurrentMap<Object, String> map) throws Exception { +        List<Object> keyList1 = populate(map); +        List<Object> keyList2 = populate(map); +        assertEquals(keyList1.size() + keyList2.size(), map.size()); + +        // Place some values on the ReferenceQueue +        keyList1.clear(); +        GCUtils.gc(); + +        final int threadCount = 16; +        final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); +        final Object[] threadKeys = new Object[threadCount]; +        for (int i = 0; i < threadCount; i++) { +            final int idx = i; +            Thread t = new Thread(new Runnable() { +                @Override +                public void run() { +                    Object k = new Object(); +                    threadKeys[idx] = k; +                    String v = "thread-" + idx; +                    ThreadUtils.await(barrier); +                    map.put(k, v); +                    ThreadUtils.await(barrier); +                } +            }); +            t.setDaemon(true); +            t.start(); +        } +        barrier.await(); // start threads +        barrier.await(30L, TimeUnit.SECONDS); // wait for them to complete +        assertEquals(keyList2.size() + threadCount, map.size()); +    } + +    private List<Object> populate(ManagedConcurrentMap<Object, String> map) { +        List<Object> elements = new ArrayList<Object>(ENTRY_COUNT); +        for (int i = 0; i < ENTRY_COUNT; i++) { +            Object key = new Object(); +            elements.add(key); +            map.put(key, "value" + i); +        } +        return elements; +    } +} http://git-wip-us.apache.org/repos/asf/groovy/blob/d40a6400/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentValueMapStressTest.java ---------------------------------------------------------------------- diff --git a/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentValueMapStressTest.java b/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentValueMapStressTest.java new file mode 100644 index 0000000..d379f97 --- /dev/null +++ b/subprojects/stress/src/test/java/org/codehaus/groovy/util/ManagedConcurrentValueMapStressTest.java @@ -0,0 +1,135 @@ +/* + *  Licensed to the Apache Software Foundation (ASF) under one + *  or more contributor license agreements.  See the NOTICE file + *  distributed with this work for additional information + *  regarding copyright ownership.  The ASF licenses this file + *  to you 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. + */ +package org.codehaus.groovy.util; + +import groovy.lang.MetaClass; +import org.apache.groovy.stress.util.GCUtils; +import org.apache.groovy.stress.util.ThreadUtils; +import org.codehaus.groovy.runtime.InvokerHelper; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class ManagedConcurrentValueMapStressTest { + +    static final int ENTRY_COUNT = 10371; + +    static final ReferenceBundle bundle = ReferenceBundle.getWeakBundle(); + +    @Test +    public void testMapRemovesCollectedReferences() throws InterruptedException { +        ManagedConcurrentValueMap<String, Object> map = new ManagedConcurrentValueMap<String, Object>(bundle); + +        // Keep a hardref so we can test get later +        List<Object> valueList = populate(map); + +        // Make sure we still have our entries, sample a few +        Object value77 = map.get("key77"); +        assertEquals(valueList.get(77), value77); + +        Object value1337 = map.get("key1337"); +        assertEquals(valueList.get(1337), value1337); + +        // Clear hardrefs and gc() +        value77 = null; +        value1337 = null; +        valueList.clear(); + +        GCUtils.gc(); + +        // Add an entries to force ReferenceManager.removeStaleEntries +        map.put("keyLast", new Object()); + +        // No size() method, so let's just check a few keys we that should have been collected +        assertEquals(null, map.get("key77")); +        assertEquals(null, map.get("key1337")); +        assertEquals(null, map.get("key3559")); + +        assertEquals(1, size(map)); +    } + +    /** +     * This tests for deadlock which can happen if more than one thread is allowed +     * to process entries from the same RefQ. We run multiple iterations because it +     * wont always be detected one run. +     * +     * @throws Exception +     */ +    @Test +    public void testMultipleThreadsPutWhileRemovingRefs() throws Exception { +        for (int i = 0; i < 10; i++) { +            ManagedConcurrentValueMap<String, Object> map = new ManagedConcurrentValueMap<String, Object>(bundle); +            multipleThreadsPutWhileRemovingRefs(map); +        } +    } + +    private void multipleThreadsPutWhileRemovingRefs(final ManagedConcurrentValueMap<String, Object> map) throws Exception { +        List<Object> valueList1 = populate(map); +        List<Object> valueList2 = populate(map); + +        // Place some values on the ReferenceQueue +        valueList1.clear(); +        GCUtils.gc(); + +        final int threadCount = 16; +        final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); +        final Object[] threadValues = new Object[threadCount]; +        for (int i = 0; i < threadCount; i++) { +            final int idx = i; +            Thread t = new Thread(new Runnable() { +                @Override +                public void run() { +                    Object v = new Object(); +                    threadValues[idx] = v; +                    String k = "thread-" + idx; +                    ThreadUtils.await(barrier); +                    map.put(k, v); +                    ThreadUtils.await(barrier); +                } +            }); +            t.setDaemon(true); +            t.start(); +        } +        barrier.await(); // start threads +        barrier.await(30L, TimeUnit.SECONDS); // wait for them to complete +        assertEquals(ENTRY_COUNT + threadValues.length, size(map)); +    } + +    private List<Object> populate(ManagedConcurrentValueMap<String, Object> map) { +        List<Object> elements = new ArrayList<Object>(ENTRY_COUNT); +        for (int i = 0; i < ENTRY_COUNT; i++) { +            Object val = new Object(); +            elements.add(val); +            map.put("key" + i, val); +        } +        return elements; +    } + +    private static int size(ManagedConcurrentValueMap<String, Object> map) { +        MetaClass metaClass = InvokerHelper.getMetaClass(map); +        ConcurrentHashMap<String, Object> internalMap = (ConcurrentHashMap<String, Object>)metaClass.getProperty(map, "internalMap"); +        return internalMap.size(); +    } +} Loading...
__label__pos
0.582002
What is 46 to the 25th Power? So you want to know what 46 to the 25th power is do you? In this article we'll explain exactly how to perform the mathematical operation called "the exponentiation of 46 to the power of 25". That might sound fancy, but we'll explain this with no jargon! Let's do it. What is an Exponentiation? Let's get our terms nailed down first and then we can see how to work out what 46 to the 25th power is. When we talk about exponentiation all we really mean is that we are multiplying a number which we call the base (in this case 46) by itself a certain number of times. The exponent is the number of times to multiply 46 by itself, which in this case is 25 times. 46 to the Power of 25 There are a number of ways this can be expressed and the most common ways you'll see 46 to the 25th shown are: • 4625 • 46^25 So basically, you'll either see the exponent using superscript (to make it smaller and slightly above the base number) or you'll use the caret symbol (^) to signify the exponent. The caret is useful in situations where you might not want or need to use superscript. So we mentioned that exponentation means multiplying the base number by itself for the exponent number of times. Let's look at that a little more visually: 46 to the 25th Power = 46 x ... x 46 (25 times) So What is the Answer? Now that we've explained the theory behind this, let's crunch the numbers and figure out what 46 to the 25th power is: 46 to the power of 25 = 4625 = 370,634,456,879,779,497,815,637,488,681,697,333,477,376 Why do we use exponentiations like 4625 anyway? Well, it makes it much easier for us to write multiplications and conduct mathematical operations with both large and small numbers when you are working with numbers with a lot of trailing zeroes or a lot of decimal places. Hopefully this article has helped you to understand how and why we use exponentiation and given you the answer you were originally looking for. Now that you know what 46 to the 25th power is you can continue on your merry way. Feel free to share this article with a friend if you think it will help them, or continue on down to find some more examples. Cite, Link, or Reference This Page If you found this content useful in your research, please do us a great favor and use the tool below to make sure you properly reference us wherever you use it. We really appreciate your support! • "What is 46 to the 25th Power?". VisualFractions.com. Accessed on August 18, 2022. http://visualfractions.com/calculator/exponent/what-is-46-to-the-25th-power/. • "What is 46 to the 25th Power?". VisualFractions.com, http://visualfractions.com/calculator/exponent/what-is-46-to-the-25th-power/. Accessed 18 August, 2022. • What is 46 to the 25th Power?. VisualFractions.com. Retrieved from http://visualfractions.com/calculator/exponent/what-is-46-to-the-25th-power/. Exponentiation Calculator Want to find the answer to another problem? Enter your number and power below and click calculate. Calculate Exponentiation Random List of Exponentiation Examples If you made it this far you must REALLY like exponentiation! Here are some random calculations for you:
__label__pos
0.885583
Latent Class Analysis is a cluster-wise regression approach that we use to discover respondent segments with similar (latent) preference structures in choice data. Different from traditional cluster techniques, it first classifies respondents into segments that are as distinct as possible, and then it estimates preference structure parameters at the segment level instead of the respondent level. Latent Class: benefits & limitations • It delivers a good understanding of market structure and of addressable target groups • It delivers insightful input into product portfolio optimization by providing insight into heterogeneity in preferences • It delivers a perfect balance between insightful but potentially unstable respondent-level parameters and solid but over-generalizing sample-level parameters Latent Class: when to use it? • Perfect input for product line optimization • To identify unmet needs for product development • To identify different price groups and what each group values, so they can be targeted
__label__pos
0.999783
Mapping Definitions A mapping definition is a collection of settings that describes how AccuSync synchronizes AccuWork and ITS issues. Examples of mapping definition settings include: Issue type You create a mapping definition for each issue type you want to synchronize. You might create one mapping definition for defects and another for tasks, for example. Field mappings You use field mappings to specify the AccuWork issue fields and ITS issue fields whose data you want to synchronize. For example, you might want to synchronize the content of the AccuWork issue Assigned To field with the content of the Owner field in your ITS. Depending on the allowed values for a given field, and whether those values are the same on both systems, you also might need to create a mapping group. See Mapping Groups for more information. Transformers AccuSync uses transformers to convert values in one system to different values in the other. For example, valid user names in Rally systems are email addresses, [email protected], for example. AccuRev usernames do not take this form, so AccuSync provides a transformer that strips the @domain_name suffix from Rally user names when synchronizing Rally artifacts with AccuWork issues, and vice versa. AccuSync includes several predefined transformers, and you can create custom transformers using a Java project installed with AccuSync. See Transformers for more information. Synchronization type override The synchronization type determines whether AccuSync performs a two-way or one-way synchronization. By default, AccuSync uses the synchronization type specified for the synchronization pattern that the mapping definition is associated with. If you want, you can override the synchronization type for individual field mappings. See Synchronization Types for more information. Filters Filters provide a way for you to control which issues, or types of issues, are synchronized. For example you might create a filter that does not synchronize issues filed against a specific subsystem, or issues submitted by a specific user. You can define filters for both AccuWork and your ITS. See Creating a Mapping Definition Filter for more information.
__label__pos
0.877655
Authorization mechanism for establishing addressability to information in another address space - IBM Permits one program in one address space to obtain access to data in another address space without invoking a supervisor. Each of a plurality of address spaces assigned an Address Space Number (ASN) has an associated set of address translation tables. Addressability to a second address space may be specified by a program if authorized in accordance with the entry of an authority table associated with the second address space, the entry being designated by an authorization index associated with the program. Skip to: Description  ·  Claims  ·  References Cited  · Patent History  ·  Patent History Description BACKGROUND OF THE INVENTION 1. Related Applications On even date herewith, the following related applications were filed: (1) "Authorization Mechanism For Transfer Of Program Control Or Data Between Different Address Spaces Having Different Storage Protect Keys" by A. Heller et al and (2) "Mechanism For Control Of Address Translation By A Program Using A Plurality of Translation Tables" by A. Heller et al. 2. Field Of The Invention This invention relates generally to data processing systems and more particularly to program or data protection hardware and techniques. 3. Description Of The Prior Art Any stored program data processing system that provides for multiprogramming, multiprocessing, virtual memories, or a supervisor program providing for a multiple virtual system must be concerned with the protection of data and/or programs from inadvertent or unauthorized use or modification. A widely published form of this protection is that described in connection with Multics which is an operating system developed primarily by Massachusetts Institute of Technology in cooperation with General Electric Company and others, and first implemented on a Honeywell 635 Computer. This technique has been recently described in U.S. Pat. No. 4,177,510. Another form of protection mechanism is disclosed in U.S. Pat. No. 4,038,645, assigned to the assignee of the present invention, and is descriptive of the technique utilized in the IBM Series/1 computer system. A particular form of prior protection mechanism, more closely associated with the present invention, is that defined for the IBM System/370 series of data processing systems. The organizational and hardware/architectural aspects of the IBM System/370 are described in the "IBM System/370 Principles of Operation", Form No. GA22-7000-4, File No. S/370-01. In the IBM System/370, the basic form of data protection is accomplished by the storage protect keys associated with physical blocks of memory and associated with particular programs. This concept is disclosed and claimed in U.S. Pat. No. RE 27,251 entitled "Memory Protection System", Issued 12/21/71 to G. M. Amdahl et al, and assigned to International Business Machines Corp. A four-bit coded storage protect key associated with physical blocks of memory is compared with a PSW key associated with a program to control access to data. In present IBM System/370 systems, the method by which programs are controlled in their access to data or the ability to call other programs in the data processing system is under strict control of an operating system or supervisor. One such control program is the Multiple Virtual System (MVS) control program. One program can call another program only by alerting the supervisor program by means of a Supervisor Call instruction (SVC), leaving to the supervisor program the determination of the authorization of the calling program to call the called program. A major IBM System/370 user requirement addressed by this invention is to provide an enhanced method of communication between address spaces in a system operating under MVS. In present systems, there are a number of multi-address space program subsystems, e.g. IMS, TSO/VTAM, VSPC, and JES. These subsystems use a multiple address space structure to separate themselves from their users. This separation provides them with a number of advantages. By providing their own address space in which to run their programs and keep their private data, they are able to better ensure a recovery environment for their programs and data. If users of the subsystem were to run in the same address space as the subsystem control, the subsystem's recovery could be affected by the user's recovery. If the subsystem's control information is kept in common storage, storage protect keys become the only mechanism to protect the data. However, there are not enough keys (16) to guarantee that the information is protected from an inadvertent store by another subsystem or authorized program since it is commonly addressable. By using their own private area for keeping their control information, subsystems are able to have up to eight megabytes of addressability for their data. If more than eight megabytes of data is required, the subsystem may use more than one private address space for the data; in effect, extending the 24-bit addressability limit of the 370 architecture. By keeping sensitive data in their own private address space they are able to isolate their data from all unauthorized users in the system. These are some of the reasons that subsystems use a multi-address space structure; however, there are problems with the communication mechanisms available in MVS for calling programs in another address space and moving/referencing data between two address spaces. To permit calling of programs or reference data in another address space, the user must be authorized; therefore, most subsystems must embed the mechanisms within Supervisor Call instructions (SVC) to give an interface to the unauthorized user. Solutions require the user to do his own synchronization if a synchronous call is desired and are extremely slow. Since the 370 architecture supports only one address space at any instant in time, subsystems must put any data that must be shared or moved between the subsystem and its user in common storage. This has a number of undesirable effects. The amount of common storage available for other uses is reduced because it is being used by only a few address spaces. Since the data is globally addressable in all address spaces, the only means of protecting the data against an inadvertent store is through keys. However, there are only sixteen keys, thus no guaranteed way of limiting access to the data can be ensured. If the data contains proprietary information, the only way to protect the security of the data is to fetch protect the data. Opportunities to exploit virtual storage such as virtual data bases are severely limited. If a virtual data base is to be shared among two or more users, the data base must be placed in common storage or the performance benefit of the virtual data will be negated by the slow private-to-private access mechanisms available. However, common storage is a limited resource; therefore virtual data bases must be relatively small. SUMMARY OF THE INVENTION The primary object of the present invention is to provide a problem program operating in a present address space to call a program in a different address space or obtain addressability to another address space by utilizing a supervisor provided index value for accessing an authority table associated with the new address space. To provide enhancement needed for a System/370 to operate with MVS, the present invention introduces the concept of dual address spaces with problem program ability to obtain addressability to a different address space if permitted by an authority table associated with the different address space. The invention is included in a new subsystem control facility that provides: (1) basic authority control with dual address space memory references; (2) program subsystem linkages; and (3)Address Space Number translation to main memory addresses with authorization control. Basic authority control makes available to problem programs a gradation of privilege or authority. It includes extraction-authority control indicated by bit 4 of control register 0, which allows the following instructions to be executed in the problem state: Insert Address Space Control, Insert PSW Key, and Insert Virtual Storage Key. A PSW-key mask is placed in control register 3. This 16-bit mask is used to control the keys that may be placed in the current PSW by the instruction Set PSW Key From Address. When in the problem program state, the key mask is used to control the keys that may be specified by three move instructions in order to access one of their operands with a key different from the PSW key. The instructions are Move With Key, Move To Primary, and Move To Secondary. The mask is also ANDed with an authorization key mask in an entry-table entry during execution of a Program Call instruction to determine if the program is authorized to call this particular entry point. An Insert Virtual Storage Key instruction allows the virtual address of a location to be used to examine the storage key associated with the location. For Move With Key, the access key for the source operand is specified as an operand and authorized by the PSW-key mask. Instructions that can be executed in either the problem state or the supervisor state when certain authority requirements are met are called semiprivileged instructions. Failure to meet the requirements of the extraction-authority control or the PSW-key mask causes a privileged-operation exception to be recognized. The requirements of the extraction-authority control and the PSW-key mask are not enforced when execution is in supervisor state. Other authority requirements for semiprivileged instructions can cause other program exceptions to be recognized, and these other requirements are enforced regardless of whether execution is in the problem state or the supervisor state. The dual address space concept provides, for the problem program, the ability to move information from one address space into another and also to specify in which address space the operands of the program are to be accessed. It includes, in control register 7, a secondary-segment-table origin and the secondary-segment-table length, which together define the location and extent of the secondary-segment table. The secondary-segment table is used to translate the secondary virtual addresses of the secondary address space, while a primary-segment table in control register 1 is used for the primary virtual addresses of the primary address space. When the normal 370 dynamic address translation facility (DAT) is on, the CPU is said to be in either primary-space mode or secondary-space mode, depending on which segment table is being used. Bit 5 in control register 0 authorizes the execution of the instructions Set Address Space Control, Move To Primary, and Move to Secondary which move data between the primary and secondary address spaces. The secondary-space access key is specified as an operand and authorized by the PSW-key mask in control register 3. Address-space control in bit 16 of the PSW, which, when on, causes any logical address to be treated as secondary virtual addresses. The implication is that instructions that are executed in secondary-space mode should be in both address spaces through being in the common area. Instructions Insert Address Space Control and Set Address Space Control, allow the program to inspect and set, respectively, the address-space control bit 16 in the PSW. Another feature of the present invention provides for direct linkage between problem programs executing at different levels of authority, without the use of the Supervisor Call instruction. Control register 5 includes a subsystem-linkage control valid bit, a linkage-table origin, and the linkage-table length. The subsystem-linkage control authorizes the execution of a Program Call and Program Transfer instruction. The linkage-table origin and linkage-table length define the location and extent of the linkage table. The linkage table and the associated entry tables are used during a PC-number-translation process. The contents of an entry-table entry are: authorization key mask, ASN, entry addressing-mode bit, entry instruction address, entry problem-state bit, entry parameter, and entry key mask. The PC-number-translation process occurs during the execution of the Program Call instruction. Program Call (PC) specifies a PC number, which is used to locate an entry-table entry. If the Program Call is executed in problem state, the authorization key mask in the entry table entry is ANDed with the PSW-key mask in control register 3, with a nonzero result indicating that the program issuing the Program Call is authorized to access the entry. The PSW-key mask and primary ASN, and the addressing-mode bit, instruction address, and problem-state bit of the current PSW, are saved in general registers. The entry addressing-mode bit, entry instruction address, and entry problem-state bit are placed in the current PSW. The entry key mask is ORed with the PSW-key mask, and the PSW-key mask is replaced by the result. The secondary ASN and secondary-segment-table designation are set equal to the primary ASN and primary-segment-table designation, respectively. If the ASN in the entry-table entry is zero, it indicates the current-primary ASN is still effective. Program Transfer (PT) specifies general registers containing a key mask, ASN, addressing-mode bit, instruction address, and problem-state bit. These contents are normally the ones that were saved by a Program Call. The addressing-mode bit, instruction address, and problem-state bit are placed in the current PSW, except that this is not allowed to cause a change from problem to supervisor state. The key mask is ANDed with the PSW-key mask, and the PSW-key mask is replaced by the result. The secondary ASN is set equal to the specified ASN. If the specified ASN is equal to the current primary ASN, the secondary-segment-table designation is set equal to the primary-segment-table designation. The Address Space Number (ASN) facility and feature provides the translation tables and authorization controls whereby a program in the problem state can designate an address space as being the primary address space or a secondary address space. This involves possible space-switching operations of the Program Call and Program Transfer Instructions. A Set Secondary ASN instruction is also provided. ASN translation control is provided by a bit in control register 14 which also stores an ASN first-table origin (AFTO) which defines the location of an ASN first table. The ASN first table and an associated ASN second table are used during the ASN-translation process. The contents of an ASN-second-table entry are: ASX-invalid bit, authority-table origin, authorization index, authority table length, segment table designation, and linkage-table designation. An authority-table entry contains a primary authority bit and secondary authority bit. The Primary ASN in control register 4 is set equal to the ASN in an entry-table entry by a Program Call instruction with space switching (PC-ss) and the ASN in a general register by a space switching Program Transfer instruction (PT-ss). A secondary ASN is set in control register 3 equal to (1) the old primary ASN by PC-ss, (2) the new primary ASN by PT-ss, (3) the primary ASN by PC-cp (current primary) and PT-cp, and (4) the ASN in a general register by Set Secondary ASN (SSAR). The corresponding primary-segment-table designation or secondary-segment-table designation is set whenever the primary ASN or secondary ASN, respectively, is set. An authorization index in control register 4 is used, along with an authority table, to authorize a PT-ss or SSAR-ss operation. It is set during a PC-ss or PT-ss operation. The Set Secondary ASN (SSAR) instruction sets the secondary ASN equal to an ASN in a general register. SSAR performs either a current-primary (SSAR-cp) operation or a space-switching (SSAR-ss) operation. For SSAR-cp, the specified ASN equals the primary ASN. The specified ASN replaces the secondary ASN, and the primary-segment-table designation replaces the secondary-segment-table designation. For SSAR-ss, the specified ASN is different from the primary ASN. The specified ASN is used to locate an ASN-second-table entry. The current authorization index and the authority-table origin and length in the ASN-second-table entry are used to locate an authority-table entry, and then the secondary-authority bit is examined to determine if the operation is authorized. If it is, the specified ASN replaces the secondary ASN, and the segment-table designation in the ASN-second-table entry replaces the secondary-segment-table designation. For Program Call, if the ASN in the entry-table entry is nonzero, it indicates the space-switching (PC-ss) operation. The ASN replaces the primary ASN and is used to locate an ASN-second-table entry. The authorization index, segment table designation, the linkage-table designation in the ASN-second-table entry replace the current authorization index, primary-segment-table designation, and current linkage-table designation, respectively. For Program Transfer, the specified ASN is different from the primary ASN, indicating the space-switching (PT-ss) operation. The specified ASN is used to locate an ASN-second-table entry. The current authorization index and the authority-table origin and length in the ASN-second-table entry are used to locate an authority-table entry, and then the primary-authority bit is examined to determine if the operation is authorized. If it is, the specified ASN replaces the primary ASN, and the authorization index, segment-table designation, and linkage-table designation in the ASN-second-table entry replace the current authorization index, primary-segment-table designation, and current linkage-table designation, respectively. The segment-table designation in the ASN-second-table entry also replaces the secondary-segment-table designation. BRIEF DESCRIPTION OF DRAWINGS FIG. 1 is a general block diagram of a stored program general purpose computer for practicing the method of the present invention. FIG. 2 depicts three of the System/370 instruction formats utilized in the present invention. FIG. 3 depicts the information or data stored in the System/370 defined control registers utilized in practicing the present invention. FIG. 4 depicts the program status word (PSW) showing one newly defined binary bit position controlling address space operations. FIG. 5 depicts the information stored in new system control tables utilized in practicing the present invention. FIG. 6 is a combined logic and data flow diagram for effecting address space number (ASN) translation. FIG. 7 is a combined logic and data flow diagram for effecting program call (PC) number translation. FIG. 8 is a combined logic and data flow diagram for establishing a secondary address space number. FIGS. 9, 10 and 11 are a combined logic and data flow diagram for effecting transfer of control from a calling program to a called program in accordance with the present invention. FIGS. 12 and 13 are combined logic and data flow diagrams for returning control from a called program to a calling program in accordance with the present invention. FIG. 14 is a table summarizing the authorization mechanism of the present invention controlling transfer of program control or data between address spaces. FIG. 15 depicts the interaction between programs, system control tables, and data in a main memory under control of information contained in control registers to effect transfer of control between programs or transfer of data between address spaces FIG. 16 depicts programs and system control tables in main memory and their interaction with control registers and general registers to effect transfer of program control to a called program in another address space. FIG. 17 depicts programs and system control tables in main memory interacting with information in control registers and general registers of a central processing unit to effect return of program control from a called program in one address space to a calling program in another address space. DETAILED DESCRIPTION OF INVENTION FIG. 1 shows the major functional units of any stored program general purpose computer, and represents the environment for incorporating the present invention. The major units include a central processing unit 20, main memory 21, and input/output equipment 22. The central processing unit 20 includes a number of subunits. These include an arithmetic/logic unit 23 where arithmetic and logic functions are accomplished in response to program instructions. During the execution of program instructions, local storage/registers 24 provide temporary storage for intermediate results during instruction execution. The program status word (PSW) 25 is comprised of many fields, and includes an instruction address counter utilized for accessing program instructions from main memory 21 in sequence. Program instructions accessed from main memory 21 will be transferred to an instruction register/decode mechanism 26 for determining the operation to be performed within the central processing unit 20. In response to the decoding of an instruction, execution control apparatus 27 will be rendered effective to accomplish the operation called for by the instruction. The subunits just described in connection with the central processing unit 20 are found in almost any general purpose computer. As defined in the above cited IBM System/370 Principles of Operation, program-instruction-addressable registers are identified and include sixteen general registers 28 and sixteen control registers 29. Main memory 21 is comprised of a number of addressable blocks of individual addressable locations. Each block has an associated addressable coded storage protect key as defined in the above cited U.S. Pat. No. Re 27,251. The main memory 21 is adapted to store information which includes data 30, application or problem programs 31, system control or supervisor programs 32, and a number of system control tables 33. In describing the present invention, details will be given concerning new system control tables 33, use of control registers 29, not previously used or defined in the IBM System/370 Principles of Operation and certain general registers 28 required for practicing the present invention. Further, reference will be made to the existing fields of the PSW 25 which include the four-bit PSW protect key, P-bit which designates whether the system is in the problem or supervisor program state, and the instruction address portion. An additional bit, not previously defined for the PSW in the IBM System/370 Principles of Operation will also be defined. It is noted at this time that a number of alternatives for the implementation of execution control 27 are available. In the case of IBM data processing systems which implement the System/370 architecture, U.S. Pat. No. 3,400,371 is representative of an execution control mechanism consisting of a read only store microprogramming technique utilized in the recently announced 4300 series of computers. Recently issued U.S. Pat. No. 4,200,927 discloses the execution control apparatus for the IBM 3033 data processing system, which includes a combination of hardware sequencers and a microprogram control store. Some other representative data processing systems which implement the IBM System/370 Principles of Operation include systems manufactured by Fujitsu and Amdahl Corporation which are considered hardwired execution control systems. In the past, these two companies have accomplished the changes and additions to System/370 without the need for changing the hardwired sequencing. It is done by implementing the new System/370 features by means of simulation programs accessed from main memory 21. Systems provided by Magnuson, National Advanced System, IPL, CDC, and Hitachi provide their changes to System/370 functions by means of microprogramming techniques. FIG. 2 shows the System/370 instruction formats utilized in practicing the present invention. The RRE format includes a 16-bit OP code and provides addressability to a first general register (R1) and to a second general register (R2). The S format instruction includes a 16-bit OP code, addressability to one of the general registers (B2) specifying a base address to which the 12-bit displacement field (D2) is added to obtain an operand, and the operation specified by the OP code utilizes an implied operand. The SS format includes a 8-bit OP code, two 4-bit fields specifying one general register (R1) and another general register (R3). The operation specified by the OP code will involve the two general registers and two operands addressed in main memory utilizing two displacement fields (D1 and D2) added to base address values contained in associated general registers (B1 and B2). FIG. 3 and FIG. 4 depict the 16 control registers (CR0-15) and the program status word (PSW), respectively, defined in the IBM System/370 Principles of Operation. The control bits or control fields of the CR's not necessary for understanding the present invention have not been shown in FIG. 3. Of the control bits and fields shown in FIG. 3, the information in CR1 has been previously defined for IBM System/370 systems CR1 provides the address of the origin in main memory, and the length of, a segment table used by a program for implementing the dynamic address translation (DAT) facility for translating virtual or logical addresses to real main memory addresses. CR1 represents a first addressing control register for storing the main memory address of a particular address translation table. In accordance with the present invention, a second address control register for storing the main memory address of another address translation table is implemented in CR7. There is thus created a primary segment table and a secondary segment table for purposes of virtual to real address translation. Each of the segment tables identified by CR1 and CR7 is associated with an address space number (ASN). The ASN is a 16-bit symbolic identifier of an address space currently defined and connected to the system in accordance with control techniques provided by a supervisor program. An address space is a consecutive sequence of numbers and a specific transformation mechanism which allows each number to be associated with a byte location in main memory. A Primary 16-bit ASN (PASN) associated with the primary segment table origin (PSTO) in CR1 is contained in CR4, bits 16-31. The secondary address space number (SASN) is contained in bit positions 16-31 of CR3 and is associated with the secondary segment table origin (SSTO) in CR7. A supervisor program must still establish, for any particular address space, an appropriate segment table for address translation. When a secondary segment table has been established for an address space, the supervisor will set the CR0 bit position 5 to a binary 1 indicating that other program instruction operations to be described can utilize an established secondary ASN. Also under supervisor control, is the entry of information into CR14 relative to providing dual address spaces. Bit 12 of CR14 will be set by the supervisor to indicate that certain other program instructions can attempt to establish access to an address space other than that specified by the primary ASN and primary segment table. Whenever a program instruction operation results in the attempt to load a new ASN into either CR3 or CR4, an ASN translation mechanism must be invoked. The result of the ASN translation will be to identify the segment table origin (STO) for the ASN which is being loaded into CR3 or CR4. The translation process will be more thoroughly described but includes an first entry a system control table identified as the ASN-first-table, and the origin (AFTO) of this table in main memory is specified in bit positions 20-31 of CR14. Bit position 16 of the PSW shown in FIG. 4 has been newly defined. When set to binary 0, all logical or virtual addresses utilized in the data processing system will be translated utilizing the primary ASN segment table. When bit 16 is binary 1, address translation takes place utilizing the secondary ASN segment table. Completing discussion of the PSW in connection with the present invention, the only other fields to be discussed concern the previously defined PSW-key field in bit positions 8-11 which define the storage protect key for the program currently being executed in the system, and the instruction address portion which is manipulated to execute program instructions in a specified sequence. In accordance with the present invention, one further authority control provided is that represented by bit position 4 of CR0. Prior to the present invention, there were two classes of programs identified by the P bit 15 of the PSW, specifying either a problem program state or a supervisor program state. Any manipulation of the PSW or control data in the CR's had to be done by a supervisor program and only when the PSW indicated that the system was in the supervisor program state. The present invention provides certain manipulation capabilities to programs in the problem program state. This state is known as a "semiprivileged state" and is indicated when bit position 4 of CR0 is a binary 1. As part of address space management, each program being executed in the system is provided with a supervisor program created authorization index (AX) which is stored in bit positions 0-15 of CR4. Any program executing in the system which attempts to establish addressability to an address space other than its own address space, by attempting to store an ASN in either CR3 or CR4, will be authorized to establish the addressability if the AX used for entry into an authorization table indicates that use of the ASN is authorized. This process will be further described. As part of the program linkage or calling process, programs executing in the system which attempt to call another program will utilize a program identification code (PC) of the called program to address an entry in a linkage table. The main memory address origin of the linkage table (LTO), and its length, is stored in CR5. A final feature of the present invention relates to allowing problem programs, when the system is in the problem program state, to utilize coded storage protect key values other than the coded storage protect key assigned in bit positions 8-11 of the PSW. Storage of a key mask (KM) is provided in CR3 bit position 0-15. The PSW key mask provides for levels of control for the access key at entry points made available to a particular program running in the problem state. Bits 0-15 in CR3 correspond to key values 0-15, respectively, which can be expressed by the 4-bit coded storage protect key values. If the mask bit associated with a specified key is 1, then the operation desiring use of a key other than that specified in the PSW is allowed. Also, during the process of calling another program, the key mask in CR3 will be compared with a key mask associated with the called program to determine whether or not the calling program has authority to call the called program without invoking supervisor control. FIG. 5 depicts the entry format in each of a number of new system control tables utilized in practicing the present invention. When a calling program has identified a called program, the identification of the called program (PC number) is combined with the linkage table origin value in CR5 to obtain entry into a linkage table (LT). The LT entry 34 includes the main memory address of the origin of an entry table (ET) specified in bit positions 8-25. The ET length is in bit positions 26-31. A further portion of the PC number is combined with the entry table origin (ETO) to provide an index to the ET to obtain an entry 35 comprised of an 8-byte entry. The ET entry 35 includes an authority key mask (AKM) in bit positions 0-15, an entry address space number (EASN) in bit position 16-31 which specifies the address space number assigned to the called program. The first instruction of the called program will be accessed from the entry instruction address (EIA) in bit positions 40-62 which will be inserted into the corresponding field of the PSW. Bit position 63 is the P bit also inserted in the PSW to specify either problem or supervisor state. Various parameters to be utilized by the called program will be stored in general registers and are contained in bit positions 64-95. The key mask to be associated with the called program is found in the entry key mask (EKM) in bit positions 96-111. As part of any attempt to load a new address space number (ASN) into address control registers CR3 or CR4, an ASN translation process is effected. A first table origin (AFTO) is specified in CR14 and a first part of the ASN is utilized as an entry into that table to obtain an ASN first table entry (ASTE) 36 which, in bit positions 8-27 specifies the main memory address of an ASN second table origin (ASTO) which enters into the translation process. The origin of the ASN second table is combined with a further portion of the ASN number to provide an index to an 8-byte ASN second table entry 37. The AST entry 37 includes, in bit positions 8-29, the main memory address of the origin of an authority table (ATO). For the new ASN to be established in the CR's, bit positions 32-47 contain a new authority index (AX). Positions 48-59 indicate the length of the authority table identified in the ATO. Associated with the new ASN being established, is a segment table description (STD) which provides for identifying the length of a segment table in bit positions 64-71 (STL) and the main memory address of the origin of the segment table associated with the ASN in bit positions 72-89 (STO). The linkage table description (LTD) to be inserted in CR5 as part of a change of program control includes, in bit positions 104-120, the main memory address of a new linkage table origin (LTO) and the length (LTL) in bit positions 121-127 of the linkage table. As part of the ASN translation process for establishing addressability to a new ASN, the authority index (AX) in CR4 of the program currently being executed is used to access an authority table (AT) entry 38, the main memory address of which is specified in the ATO of the ASN second table entry 37. The AX accesses a 2-bit field from the authority table. The binary 0 or 1 state of a P bit or a S bit specify whether or not the ASN being established can be made either a primary (P) or secondary (S) address space. FIG. 6 is a data flow and logic diagram explaining the process of ASN translation which must be accomplished in certain cases when program instructions cause a new ASN to be inserted in the control registers. Three new instructions, as part of the System/370 instruction set may cause the ASN translation process to be invoked. The new instructions are program call (PC), program transfer (PT), and set secondary ASN (SSAR). All three of these instructions, which may be accessed from a program operating in a primary address space, may specify an ASN to be loaded which is equal to the primary ASN presently effective. If this is the situation, the three instructions are identified as being "current primary" (cp) instructions. If the ASN being loaded as a result of the instruction execution is different from the current primary ASN, a "space switching" (ss) execution is effected causing the ASN translation process to be invoked. During execution of the PC instruction, the called program, identified by its PC number, may reside in another address space. This will be determined by a PC translation process to be described subsequently. Prior to the execution of PT or SSAR, information to be utilized during the execution of these instructions will have been loaded into designated ones of the general registers which will be identified and addressed by the R1 and/or R2 fields of these instructions. In FIG. 6, the PT instruction is shown at 39 and the information contained in general registers identified by R1 and R2 is shown at 40 and 41. The SSAR instruction is shown at 42 and the information contained in general register R1 is shown at 43. The new ASN which may or may not require translation is also shown at 44. During the explanation of the data and logic flow shown in FIG. 6, previous references to system control table entries are shown with the same numerals utilized in FIG. 5. ASN translation is the process of translating the 16-bit ASN to locate address-space control parameters. ASN translation is performed as part of Program Call with space switching (PC-ss), Program Transfer with space switching (PT-ss), and Set Secondary ASN with space switching (SSAR-ss). For PC-ss and PT-ss, the ASN which is translated replaces the primary ASN in CR4. For SSAR-ss, the ASN which is translated replaces the secondary ASN in CR3. These two translation processes are called primary ASN translation and secondary ASN translation, respectively. The ASN translation process is the same for both primary and secondary ASN translation; only the results of the process are used differently. The ASN translation process uses two system control tables stored in main memory 21, the ASN first table (AFT) 45 and the ASN second table (AST) 46. They are used to locate the address-space-control parameters, and a third table, the authority table (AT) 47, which is used in PT-ss and SSAR-ss to perform an authorization test. For the purposes of translation, the 16-bit ASN shown at 44 is considered to consist of two parts: the ASN-first-table index (AFX) comprises the high-order 10 bits of the ASN, and the ASN-second-table index (ASX) comprises the six low-order bits. The AFX portion of the ASN shown at 44 is used at 48 to select an AFT entry 36 that designates the AST 46 to be used for the second lookup. The 31-bit real address of the AFT 45 is obtained by appending 12 low-order zeros to the AFT origin contained in bit positions 13-31 of CR14. The address of the AFT entry is obtained by appending two low-order zeros and 19-high order zeros to the AFX and adding this 31-bit value to the real address of the AFT, ignoring any carry into bit position 0. All four bytes of the ASN-first-table entry are fetched concurrently. The fetch access is not subject to protection. Bit 0 of the four-byte AFT entry specifies whether the corresponding AST is available. The ASX portion of the ASN shown at 44, in conjunction with the ASN-second-table origin (ASTO) derived from the AFT entry 36, is used at 49 to select an entry 37 from the AST 46. Bits 1-27 of the AFT entry 36, with four low-order zeros appended, form the 31-bit real address of the AST 46. The address of the AST entry 37 is obtained by appending four low-order zeros and 21 high-order zeros to the ASX and adding this 31-bit value to the real address of the AST, ignoring any carry into bit position 0. The 16 bytes of the AST entry 37 are fetched left to right, a doubleword at a time. The fetch access is not subject to protection. Bit 0 of the 16-byte AST entry 37 specifies whether the address space is accessible. If this bit is one, an ASX-translation exception is recognized, and the operation is nullified. ASN authorization is the process of testing whether the program associated with the current authorization index (AX) in CR4 is permitted to obtain addressability to a particular address space. The ASN authorization is performed as part of PT-ss and SSAR-ss. ASN authorization is performed after the ASN translation process for these two instructions. When performed as part of PT-ss, the ASN authorization checks tests whether the ASN can be loaded into CR4 as the primary ASN, and is called primary-ASN authorization. When performed as part of SSAR-ss, the ASN authorization checks whether the ASN can be loaded into CR3 as the secondary ASN and is called secondary-ASN authorization. The ASN authorization is performed by means of the authority table 47 which is designated by the authority-table-origin (ATO) and authority-table-length (AL) fields in the AST entry 37. The authority table 47 consists of a plurality of entries 38 of two bits each. The left bit (P) of an authority table entry 38 controls whether the program with the AX corresponding to the entry is permitted to load the address space as a primary address space using PT. If the P bit is one, the access is permitted. If the P bit is zero, the access is not permitted; a primary authority exception is recognized and the operation is nullified. The right bit (S) of an authority table entry 38 controls whether the program with the corresponding AX is permitted to load the address space as a secondary address space using SSAR-ss. If the S bit is one, the access is permitted. If the S bit is zero, the access is not permitted; a secondary authority exception is recognized, and the operation is nullified. The ASN authorization process is performed by using the AX currently in CR4 shown at 50, in conjunction with the authority table origin and length from the AST entry 37 to select at 51 an authority table entry 38. The entry is fetched, and either the primary or secondary authority bit is examined, depending on whether the primary or secondary authorization process is being performed. An AX value greater than the table length (AL) signals an error 52. Bit positions 8-29 of the AST entry 37 contain the real address of the authority table 47 that controls access authority to the address space, and bit positions 48-59 contain the length of the table (AL). As part of the authority-table-entry-lookup process, bits 0-11 of the AX are compared against the AL. If the compared portion is greater, then an authority exception (primary for PT-ss and secondary for SSAR-ss) is recognized, and the operation is nullified. The address of a byte in the AT 47 is obtained by appending 10 high-order zeros to the 14 high-order bits of the AX obtained from bit positions 0-13 of CR4 and adding this value to the authority table origin obtained from the AST entry 37, with two low-order zeros appended. A carry, if any, into bit position 0 is ignored. If the real address thus generated designates a location which is not provided, an addressing exception is recognized, and the operation is suppressed. Protection does not apply to this access. The byte contains four authority table entries 38 of two bits each. The low-order two bits of the authorization index, bits 14 and 15 of CR4, are used to select one of the four entries. The left or right bit of the entry is then tested, depending on whether the authorization test is for a primary ASN (PT-ss) or a secondary ASN (SSAR-ss). If the selected bit is one, the ASN translation is authorized, and the appropriate address-space-control parameters from the AST entry 37 are loaded into the appropriate control registers. If the selected bit is zero, the ASN translation is not authorized, and a primary authority exception or secondary authority exception is recognized for PT-ss or SSAR-ss, respectively. Some additional logic decisions are made in FIG. 6, not previously referred to. During a PT instruction execution, the ASN shown at 40 is compared with the primary ASN currently in CR4, and the decision shown at 53 is made indicating whether or not the ASN to be loaded equals the current primary ASN. If yes, (Y) there is no requirement for ASN translation. If the primary ASN does not equal the ASN being loaded, the new ASN shown at 40 will be stored into CR4 to become the new primary ASN. During a SSAR instruction execution, the decision shown at 54 is made. Here again, the ASN to be loaded into CR3 to become the secondary ASN is compared with the current primary ASN and if equal, an SSAR-cp is indicated showing that the current primary ASN and secondary ASN are the same, and again indicating that no ASN translation is required. An inequality indicates SSAR-ss and will cause the ASN translation to take place. When an SSAR-cp is performed, the primary segment table description in CR1 is transferred at 55 to CR7 to become the secondary segment table description. During a PT-ss or PC-ss, the linkage table descriptor (LTD) of the AST entry 37 is transferred at 56 to CR5. The segment table descriptor (STD) is transferred to CR1 at 57. For any PT instruction, the primary segment table descriptor in CR1 is transferred at 58 to CR7 to become the secondary segment table descriptor. A new AX is transferred at 59 to CR4. If an SSAR-ss is being executed, the STD is transferred at 60 to CR7 to become the new secondary segment table descriptor. To be more completely described subsequently, FIG. 6 shows that during any PT instruction execution, the ASN shown at 40 is transferred at 61 to CR3 to become the secondary ASN. A logical AND combination shown at 62 is performed on the key mask contained in R1 and the key mask presently stored in CR3. This recreates the key mask associated with the program being returned to by PT. Further, the contents of general register R2 are transferred back to the PSW restoring the P-bit, the address space control bit, and the instruction address. During a PT instruction execution, an error or an exception condition is recognized if execution of the PT instruction attempts to change the P-bit from one to zero, this being an indication that an attempt had been made to change the program state from problem to supervisor. FIG. 7 represents the overall data flow and logic diagram involved in translating a symbolic program number to proper table entries for providing the initial instruction address for a called program. Represented at 63 is the Program Call (PC) instruction, the format of which includes the designation of a general register by a B field and a displacement field D. The general register addressed by the B field contains a base address to which the displacement field D is added in the normal creation of an effective address. Instead of using the sum as an address, the low-order 20 bits represent a PC number shown at 64. In FIG. 7, the designation CR "before" and CR "after" is used. The designation CR "before" relates to information contained in the control register for the current address space and current program which is the calling program. The contents of a control register "after" represent information associated with the called program. A number of transfers between registers and other control registers or general registers occur for all PC instruction executions. One of the first logic decisions made during the execution of the PC instruction is shown at 65 and involves the determination of whether or not the ASN of the called program equals zero. If the ASN of the called program equals zero, this indicates at 66 that the called program is within the current primary address space and therefore no ASN translation is required. If the ASN associated with the called program is other than a zero, a program call with space switch (PC-ss) is indicated at 67 and the new ASN is transferred into CR4 to become the new primary ASN. During every PC instruction execution, certain information in the PSW represented at 68 is transferred to general register 14 to be saved for use when returning to the calling program. The information saved includes the P-bit, the address space control bit 16, and the instruction address. PC number translation is the process of translating the 20-bit PC number to locate an entry-table entry 35 as part of the execution of the Program Call instruction. To perform this translation, the 20-bit PC number shown at 64 is divided into two fields. Bits 12-23 are the linkage index (LX), and bits 24-31 are the entry index (EX). The translation is performed by means of two tables: the Linkage Table (LT) 69 and an Entry Table (ET) 70. Both of these system control tables reside in main storage 21. The origin of the LT 69 resides in CR5. The origin of the entry table 70 (ETO) is designated by means of the LT entry 34. Bits 8-24 of CR5 with seven zeros appended on the right, form a 24-bit real address that designates the beginning of the LT 69. Bits 25-31 of CR5 designate the length of the LT 69 in units of 128 bytes, thus making the length of the LT variable in multiples of 32 four-byte entries. The length of the LT, in units of 128 bytes, is one more than the value in bit positions 25-31. The LT length is compared against the leftmost seven bits of the linkage-index portion of the PC number to determine whether the linkage index designates an entry within the linkage table. The LX portion of the PC number is used at 71 to select an LT entry 34. The entry fetched from the LT designates the availability, origin, and length of the corresponding ET 70. Bits 8-25 of LT entry 34, with six zeros appended on the right, form a 24-bit real address that designates the beginning of the ET 70. Bits 26-31 of entry 34 designate the length of the ET 70 in units of 64 bytes, thus making the ET variable in multiples of four 16-byte entries. The length of the ET in units of 64 bytes, is one more than the value in bit positions 26-31. The ET length is compared against the leftmost six bits of the entry index EX to determine whether the EX designates an entry within the entry table. The entry 35 fetched from the ET 70 is 16 bytes in length. Bits 0-15 are used to verify whether the program issuing the Program Call instruction, when in the problem state, is authorized to call this entry point. The authorization key mask (AKM) and the current PSW-key mask in CR3 are ANDed at 72, and the result is checked for all zeros. If the result is all zeros, a privileged-operation exception is recognized, and the operation is suppressed. The mask is ignored in the supervisor or privileged program state. Bits 16-31 specify at 65 whether a PC-ss or PC-cp is to occur. When bits 16-31 are zeros, a PC-cp is specified. When bits 16-31 are not all zeros, a PC-ss is specified, and the bits contain the ASN that replaces the primary ASN. Bits 40-62, with a zero appended on the right, form the instruction address of the called program which replaces at 73 the instruction address in the PSW as part of the Program Call operation. Bit 63 replaces, at 74, the problem state bit position 15 of the current PSW, as part of the Program Call operation. Bits 64-95 are placed in general register 4 at 75. Bits 96-111 specifying the entry key mask are ORed at 76 into the PSW key mask in CR3 as part of the Program Call operation. Other transfers that take place during PC instruction execution include the transfer at 77 from the key mask storage in CR3 of the calling program to general register 3 to be saved for subsequent return. Also transferred to GR3 at 78 is the primary ASN in CR4. During any PC instruction execution, the primary segment table descriptor (PSTD) in CR1 is transferred at 79 to CR7 to become the secondary segment table descriptor (SSTD) and the primary ASN in CR4 is transferred at 80 to CR3 to become the secondary ASN. Whether or not the primary segment table descriptor and primary ASN are changed depends on whether or not a PC-ss is signalled at 65 which will initiate an ASN translation in accordance with the data flow and logic shown in FIG. 6. FIG. 8 is a logic and data flow diagram depicting the execution of the new instruction set secondary ASN (SSAR). This is one of the new instructions which causes a new ASN to be loaded into one of the address control registers, namely the secondary ASN stored in CR3, and shown at 81. All the remaining designations for tables, entries, data transfer paths, and logic decisions are as previously designated in the discussion of FIG. 6 with regard to the ASN translation operation. In summary, the problem program which is executing in the primary address space utilizing the primary segment table descriptor in CR1 executes the SSAR instruction to obtain addressability to data contained in another address space. As indicated previously, each address space has an associated set of address translation tables, and therefore the associated segment table descriptor for the new address space must be stored into CR7 for performing address translation to obtain data in the other address space. CR7 will receive at 55 the primary segment table description if the ASN specified happens to be equal to the primary ASN. Otherwise, if the secondary ASN to be loaded into CR3 is different from the primary ASN, the address translation operation must be performed to obtain the associated segment table descriptor from the ASN second table entry 37, and transferred to CR7 by the path 60. Further, authority checking must be accomplished by effecting access to the authority table 47 to determine whether or not the program executing in the system has authority to establish addressability to the address space as a secondary address space. FIGS. 9, 10 and 11 depict the operation performed in executing the Program Call (PC) instruction. These figures show the logic and data flow diagram for the PC instruction in particular and are a simplified showing of the diagrams discussed in connection with FIGS. 6 and 7. The numerals for designating various logic functions and data paths used in FIG. 6 and 7 have been utilized in FIGS. 9, 10 and 11. As indicated previously, the B2 and D2 fields of the PC instruction shown at 63 are combined by normal address arithmetic to create a PC number shown at 64. The PC translation process includes access to entry 34 in the linkage table 69 which provides further access to the entry 35 in the entry table 70. As shown in FIG. 10, the first decisions made, if the program making the program call is in the problem state is to perform the AND function 72 between the authority key mask in entry 35 and the key mask in CR3 associated with the calling program. An all zero result indicating identity between the two key masks is considered an error condition and a privileged operation interrupt is generated. In the absence of the privileged operation interrupt, the key mask of the calling program in CR3 is replaced in CR3 by the OR combination shown at 76 with the entry key mask from the entry 35. This provides the called program with the ability to use storage protect keys assigned to the called program by the entry key mask (EKM) and the keys authorized for use by the calling program represented by the key mask in CR3. The original version of the key mask in CR3 associated with the calling program is transferred at 77 and saved in general register 3. The ASN associated with the calling program contained in CR4 is transferred to GR3 for saving when the called program returns to the calling program. Other information saved in GR14 as a result of executing the PC instruction is the P-bit and instruction address of the PSW, represented at 68, associated with calling program. The initial instruction address of the called program and the P bit associated with the called program are transferred from the entry 35 to the PSW. The Program Call may be to a program contained within the address space of the calling program, and if this is so, the ASN value in the entry 35 will equal zero. If so, the secondary ASN and secondary segment table description will be made the same as the primary ASN and associated primary segment table description. If the ASN number in entry 35 is not equal to zero, then the called program is associated with another address space, indicated at 67, and requires ASN translation shown in FIG. 11. The ASN translation process in FIG. 11, as previously discussed in connection with FIG. 6 and FIG. 8 will load a new ASN and associated segment table descriptor into the address control registers CR4 and CR1 respectively for use in providing address translations during execution of the called program. The called program will also have an associated linkage table, the origin and length of which is transferred at 56 to CR5. The called program will also have an authorization index (AX) which is loaded at 59 into CR4 to provide control for the ability of the called program to establish addressability to other address spaces. FIG. 12 depicts execution of the program transfer (PT) instruction previously discussed in connection with FIG. 6. The same designations used in FIG. 6 are utilized in FIG. 12. The PT instruction identifies two general registers by the R1 and R2 fields. Prior to execution of the PT instruction, the general register represented at 40 and 41 will be loaded with the information saved during execution of the PC instruction. This information includes the key mask, address space number, instruction address, and P bit. One of the first checks made during execution of the PT instruction is to determine whether or not the ASN being returned to and stored in address control registers is equal to the current primary ASN in CR4. The equality or nonequality is determined at 53, and if equal, all of the information required for doing address translation including the primary segment table descriptor in CR1 will be effective for the program being returned to. Therefore, the primary segment table descriptor in CR1 will be transferred at 58 to CR7 to also be the secondary segment table descriptor. The ASN of the program being returned to will invariably be stored into the secondary ASN portion of CR3 shown at 61. The next function shown in FIG. 12 is to alter the key mask in CR3, which was being used by the called program, to represent the key mask associated with the program being returned to. This is accomplished at 62 by performing the AND function between the key mask in CR3 and the key mask shown at 40 to replace the key mask in CR3. Returning to a program in an address space having a number different from the present primary ASN, indicated at 53, invokes the ASN translation process previously described in connection with FIG. 6, and this is shown in FIG. 13. The ASN translation process uses the new ASN represented at 44 being loaded into the address control registers to provide the sequence of table entries providing access to the ASN first table table 45 and the ASN second table 46. The ASN translation process shown in FIG. 13 thus returns all of the necessary address translation control information required including the primary segment table descriptor to CR1 and CR7, the authorization index to CR4, and the linkage table descriptor to CR5. The authority table 47 must be accessed during the PT instruction execution to insure that the program which is attempting to return to the present program has authority to return to this program in this particular address space. FIG. 14 is a table summarizing all of the authorization techniques implemented in the present invention. Also shown are a number of new System/370 instructions which utilize the authorization mechanism in various ways. The prior description has discussed the use of the subsystem linkage control in bit 0 of CR5, ASN translation control in bit 12 of CR14, and use of the authorization index in bits 0-15 of CR4. These mechanisms have been discussed in connection with the new instructions: Program Call (PC) Program Transfer (PT) Set Secondary ASN (SSAR) Execution of these new instructions has shown the ability of a program executing in the system to establish addressability to data in two different address spaces with associated address translation tables. Having established addressability to data in two different address spaces, concern must be given to providing a problem program executing in the system with knowledge of the coded storage protect key associated with addressed data in main memory which may physically be stored in two different blocks of main memory having two different storage protect keys. Prior to the present invention, any instruction executing in the system at a particular time was only able to utilize the PSW storage protect key previously assigned by the supervisor. Manipulation of storage protect keys has, prior to this time, been under strict control of the supervisor. The instructions shown in FIG. 14 which utilize the PSW key mask authorization mechanism and extraction authority control mechanism are: Insert PSW Key (IPK) Insert Virtual Storage Key (IVSK) Move to Primary (MVCP) Move to Secondary (MVCS) Move With Key (MVCK) Set PSW Key From Address (SPKA) The IPK and SPKA instructions have been previously defined in System/370. When authorized by bit 4 of CR0, the IPK instruction can, in problem state, cause the PSW key in the current PSW to be inserted in bit positions 24-27 of general register 2. The SPKA instruction causes the 4-bit PSW key to be replaced by bits 24-27 of an operand addressed from memory. The execution of SPKA is subject to control by the PSW key mask in CR3. When the bit in the PSW key mask corresponding to the PSW key value to be set is 1, the corresponding instruction is executed normally. Otherwise, a privileged-operation exception is recognized. The IVSK instruction is a new instruction in the RRE format, the execution of which causes the coded storage protect key associated with the physical block addressed by the contents of the general register designated by the R2 field to be inserted in the general register designated by the R1 field. In the problem state, the extraction authority control bit 4 in CR0 must be 1. The block address is a virtual address and is subject to the address space selection bit 16 of the current PSW. The binary state of bit 16 determines whether the virtual address is translated utilizing the primary segment table descriptor or the secondary segment table descriptor. Providing a problem program executing in the system with the ability to determine the coded storage protect key associated with a particular physical block of main memory and insert that key in a general register, and providing the ability to change the PSW key will provide the problem program with the ability to move data between physical blocks of main memory having different coded storage protect keys. The MVCP and MVCS instructions are in the SS format. The first operand is replaced by the second operand. One operand is in the primary space, and the other is in the secondary space. The accesses to the operand in the primary space are performed using the PSW key, and the accesses to the operand in the secondary space are performed using the key specified in the third operand. The addresses of the operands are virtual, one operand address being translated by the means of the primary segment table description in CR1 and the other by means of the secondary segment table description in CR7. Since the secondary space is accessed, movement is performed only when the secondary space control bit 5 of CR0 is 1. For MVCP, movement is to the primary space from the secondary space with the first operand address being translated using the primary segment table, and the second operand address is translated using the secondary segment table. For MVCS, movement is to the secondary space from the primary space with the first operand address being translated using the secondary segment table and the second operand address is translated using the primary segment table. Bit positions 24-27 of the general register specified by the R3 field are used as the secondary space access key. In the problem state, movement is performed only if the secondary space access key is valid. The secondary space access key is valid only if the corresponding PSW key mask bit in CR3 is 1. Otherwise, a privileged operation exception is recognized. The contents of the general register specified by the R1 field are a 32-bit unsigned value specifying the number of bytes to be transferred. The MVCK instruction is an SS format instruction. The first operand is replaced by the second operand. The fetch accesses to the second operand location are performed using the storage protect key specified in the third operand, and the store accesses to the first operand locations are performed using the PSW key. Bit positions 24-27 of the general register specified by the R3 field are used as the source access key. In the problem state, movement is performed only if the source access key is valid. The source access key is valid only if the corresponding PSW key mask bit in CR3 is 1. Otherwise, a privileged operation exception is recognized. The contents of the general register specified by the R1 field are a 32-bit unsigned value indicating the number of bytes to be transferred. As mentioned before, the present definition of the System/370 is such that only a supervisor program, when the system is in a supervisor program state, is capable of manipulating the control register information or PSW information. Three additional instructions shown in FIG. 14, provided with the semi-privileged state indicated by bit 4 of CR0 are: Extract Primary ASN (EPAR) Extract Secondary ASN (ESAR) Insert Address Space Control (IAC) The EPAR and ESAR instructions are in the RRE format. When in the problem state, and subject to bit 4 of CR0 being a binary 1, the 16-bit primary ASN in bits 16-31 of CR4 or the 16-bit secondary ASN in bits 16-31 of CR3 are placed in bit position 16-31 of the general register designated by the R1 field. An instruction shown in FIG. 14 not previously identified is Set Address Space Control (SAC) which is the complementary instruction to IAC. Utilizing these two instructions, a problem program executing in the system can cause the binary state of PSW bit 16 to be controlled. When bit 16 is zero, all virtual addresses are translated utilizing the primary segment table identified in CR1. When bit 16 is a binary 1, only data addresses are translated utilizing the secondary segment table identified in CR7. Since instruction addresses are considered virtual and subject to address translation, a problem program switching between use of the primary or secondary segment tables, without being able to separate data and instruction address translation, must insure that the instruction addresses being translated by the secondary segment table translates to the same physical main memory location as would have occurred if utilizing the primary segment table. FIG. 15 is a schematic representation of main memory 21 showing a number of problem programs, data, and system control tables previously identified. The interaction between the various tables, control registers, and general registers is shown with a number of examples. A supervisor program would have established a number of address space numbers and two have been shown in FIG. 15 represented by ASN 1 and ASN 9. ASN 1 is considered the primary ASN and therefore CR1 provides the main memory address of the origin of the address translation segment table (ST) and associated page table (PT) which respond to virtual addresses shown at 82 in accordance with previously defined dynamic address translation procedures in System/370. It is assumed that the presently executing program in the system is program P1 which at 83 issues a PC instruction identifying program P2. CR5 indicates the origin of the linkage table (LT) associated with P1. The PC translation process defined in FIG. 7 is invoked. As shown, the program being called is program P2. The LT entry obtained utilizing the LX portion of the PC number will provide the origin 84 of the entry table (ET) of program P2. The ET entry will provide the instruction address 85 of the first instruction to be executed in program P2. Further, as depicted in FIG. 15, the ASN in the ET entry obtained will be equal to 0 indicating that the called program P2 is in the same address space as the calling program P1. Therefore, no ASN translation process will be required. At 86, it is assumed that P2 desires to return control to program P1. The instruction address and other information saved during execution of PC at 83 will be returned to control by execution of the PT instruction issued at 86. Again, no ASN translation will be required. As program P1 continues to execute, 87 reflects the execution of the instruction SSAR identifying ASN 9. Execution of SSAR requires utilization of the first part of the ASN number to provide access into the ASN first table (AFT) which provides the main memory address 88 of the origin of the ASN in the second table (AST) associated with ASN 9. The AST entry includes the origin 89 of the authority table (AT) which is accessed utilizing the authorization index in CR4 associated with ASN 1. If the establishment of a secondary address space is authorized, the AST entry of the secondary segment table descriptor is transferred at 90 to CR7 to provide the main memory address 91 of the origin of the segment table associated with ASN 9. Instruction execution can continue in program P1 and include the new instructions which can obtain the storage protect key associated with data in ASN 9, which keys can be inserted in a general register. At this point, instructions in program P1 can cause data transfers shown at 92 to be effected between the primary address space ASN 1 and the secondary address space ASN 9. FIG. 16 depicts the interaction of system control tables, control registers, and general registers during the execution by problem program P1 of a program call (PC) instruction shown at 93. Depicted is a call to program P3. The PC translation process will utilize the first part of the PC number to address the linkage table (LT) associated with P1. The main memory address 94 of the LT entry points to the entry table (ET) associated with P3. The instruction address shown at 95, associated with program P1, will be transferred to GR14, and the ASN 1 designation in CR4 will be transferred to GR3 and CR3 to become the secondary ASN. The ET entry associated with program P3 will be read out and its contents transferred to various registers. The initial instruction address for program P3 will be transferred at 96 to the instruction address register portion of the PSW. In view of the fact that the PC translation has caused entry into a program in an address space different from ASN 1, the ET entry ASN, when compared with the primary ASN originally in CR4, will indicate the need for ASN translation. The ASN number will be transferred at 97 to become the primary ASN in CR4. The first part of the ASN number will be used to provide an address 98 into the ASN first table, which in turn provides an address 99 to the origin of the ASN second table (AST) where the accessed entry will be read out at 100 to store the associated segment table origin value in CR1 and the authorization index (AX) value into CR4. As a result, the PC instruction 93 has caused a transfer of program control to a program in an address space different from ASN 1. As a result, a new primary ASN and associated primary segment table descriptor has been provided for the indicated control registers. FIG. 17 shows the interaction when program P3 in ASN 9 returns control to program P1 in ASN 1. Prior to executing the PT instruction, GR2 will have been loaded with the instruction address previously saved in GR14 in response to the PC instruction. The ASN 1 value previously saved in GR3 in response to the PC instruction will have been stored in GR1. In response to execution of the PT instruction, the ASN in GR1 is utilized at 101 and 102 to initiate the previously described ASN translation process which includes access to the authority table (AT) utilizing the authorization index in CR4 associated with program P3. Assuming authorization, the ASN translation process completes whereby CR4 receives a new AX, CR1 receives the primary segment table descriptor associated with ASN 1, and CR7 receives the same segment table descriptor thereby making the primary ASN and secondary ASN the same. The previously saved instruction address for program P1 is inserted into the instruction address portion of the PSW and execution of instructions in program P1 is resumed in ASN 1. There has thus been shown increased capability and flexibility for an IBM System/370 data processing system which maintains program and data integrity by using storage protect mask bits, establishing a new program mode called semi-privileged for allowing manipulation of PSW and control register information, providing authorization checking for determining the ability of a problem program to establish addressability to data in an other address space, providing addressability to more than one address space with associated address translation tables, and providing the ability to execute instructions utilizing coded storage protect keys other than that provided in the PSW by a supervisor. All of these capabilities are provided to relieve the programming overhead of a supervisor program. While the invention has been particularly shown and described with references to preferred embodiments thereof, it will be understood by those skilled in the art that the foregoing and other changes in form and details may be made therein without departing from the spirit and scope of the invention. Claims 1. In a multiprogramming data processing system including (1) a main memory comprised of an addressing mechanism providing access to addressable information including data, problem programs, supervisor programs, and system control tables including addressable address translation tables for translating virtual addresses to real main memory addresses and (2) a processor including: (a) an instruction counter connected to the addressing mechanism for extracting program instructions from the main memory; (b) an address translation control register in the processor for storing a main memory address, transferrable by the processor to the main memory addressing mechanism, to provide access to a particular address translation table used for translating addresses of an associated program from virtual to real main memory addresses; (c) an address space number (ASN) control register for storing a plural-binary-bit present-ASN number providing a symbolic identifier of said particular address translation table addressed by said address translation control register; and (d) a processor control including program instruction decoding and execution control signal means, register, data path, and gate means connected and responsive to said execution control signal means, a machine implemented process in which said processor is controlled by said processor control in response to a program instruction to perform the method steps of: transferring from main memory a new-ASN for storage in said ASN control register, and the address of an associated address translation table for storage in said address translation control register; accessing from main memory a new-ASN-specified entry in a first system control table and transferring said entry to a register of said processor control, said particular entry comprising space switch authority control information including an authority control entry for each ASN that may be designated as a new-ASN indicating if the new-ASN can be used as a primary or secondary address space; testing said space switch authority control information with an authorization index stored in said processor control, related to the present-ASN, for providing an interrupt signal in the processor if the program instruction associated with the present ASN is not authorized to establish use of the address translation table associated with the new-ASN. 2. A process in accordance with claim 1 including the further step, in the absence of said interrupt signal of: accessing from main memory a new-ASN-specified entry in a second system control table for transferring said entry from the main memory to the processor and storing said entry in a register of said processor control, said entry comprising ASN translation control information for said new-ASN, including the address of the address translation table for storage in said address translation control register, an authorization index for storage in said authorization index storage means, and the main memory address of the associated one of the system control table entries comprising said space switch authority control information for said new-ASN. 3. A process in accordance with claim 2 wherein the program instruction execution effecting said space switch processing and transfer of said new ASN for storage in said ASN control register is further effective to initiate program instruction addressing from another program, and including the further step of: said ASN translation control information further includes the main memory address of a third system control table comprised of a plurality of entries each including the main memory address of a system control table identifying a linkage table for further programs, said entry providing a starting instruction address for said another program, storing in a register of said processor control said main memory address of said linkage table associated with said another program. Referenced Cited U.S. Patent Documents RE27251 December 1971 Amdahl 3264615 August 1966 Case 3665421 May 1972 Rehhausser 3787813 January 1974 Cole 3893084 July 1975 Kotok 4038645 July 26, 1977 Birney 4084225 April 11, 1978 Anderson 4104718 August 1, 1978 Poublan 4130870 December 19, 1978 Schneider 4177510 December 4, 1979 Appell Patent History Patent number: 4430705 Type: Grant Filed: May 23, 1980 Date of Patent: Feb 7, 1984 Assignee: International Business Machines Corp. (Armonk, NY) Inventors: James A. Cannavino (Hyde Park, NY), Andrew R. Heller (Morgan Hill, CA), Morris Taradalsky (Poughkeepsie, NY), William S. Worley, Jr. (Endicott, NY) Primary Examiner: Harvey E. Springborn Attorney: Robert W. Berray Application Number: 6/152,891 Classifications Current U.S. Class: 364/200 International Classification: G06F 900; G06F 946;
__label__pos
0.540714
Error : Weaker Access Privileges Posted by Ahh so you are getting Weaker Access privileges error , Its really a tricky interview question , I found it really interseting. So what do you think , what will be the output of following program , Lets guess class Super{ protected void print(){ System.out.println("Print in super"); } } class Sub extends Super{ private void print(){ System.out.println("Print in sub"); } public static void main(String ar[]){ Super sub= new Sub(); sub.print(); } } Before getting this error “Weaker Access Privileges” , my answer was “Print in sub” , but what I got   Sub.java:9: error: print() in Sub cannot override print() in Super          void print(){               ^   attempting to assign weaker access privileges; was protected 1 error So what is Weaker Access Privileges , It occurs when you try to override a higher privileged access method with lower privilege access. Explanation :  So in above code we are trying to override protected method with the private specifier, as we know private specifier has only class level access so its lower privileged then protected and thats why its giving error. Now take another example interface Java{ void print(int t); } public class Java2Career implements Java { public static void main(String [] args){ new Java2Career().print(5); } void print(int s) { System.out.println("s " + s); } } You would have noticed that not any access specifier is specified to both methods means It should print 5 as output but no it will also give the error , the same error, WHY? Because all the methods and variable defined in interface are by default public so when we are overriding the method with no access specifier in subclass “Java2Career” , We are trying to give lower access privilege. I hope you have enjoyed it , Thanks for reading , any Suggestions are always welcome , If  I am wrong anywhere, I will update my post with the suggestion in comments. You may also like following Interview Questions: 1. Some tips to solve your java technical test paper 2. Transient and volatile modifier (Most asked in Interviews) 3. Interview Questions of Java for Freshers 4.  A program to check String is palindrom or not? 5.  What is Intern String? 2 comments Leave a Reply
__label__pos
0.999738
aboutsummaryrefslogtreecommitdiffstats path: root/plugins/eg-amp.lv2/amp.c blob: 7f7cacc81382da91daa601c231c1f63fe9052df3 (plain) 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 /* Copyright 2006-2011 David Robillard <[email protected]> Copyright 2006 Steve Harris <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** @file amp.c Implementation of the LV2 Amp example plugin. This is a basic working LV2 plugin, about as small as one can get. It is useful as a skeleton to copy to build more advanced plugins. See lv2.h for more detailed descriptions of the rules for the various functions. */ #include <math.h> #include <stdlib.h> #include <string.h> #include "lv2/lv2plug.in/ns/lv2core/lv2.h" #define AMP_URI "http://lv2plug.in/plugins/eg-amp" /** Port indices. */ typedef enum { AMP_GAIN = 0, AMP_INPUT = 1, AMP_OUTPUT = 2 } PortIndex; /** Plugin instance. */ typedef struct { // Port buffers float* gain; float* input; float* output; } Amp; /** Create a new plugin instance. */ static LV2_Handle instantiate(const LV2_Descriptor* descriptor, double rate, const char* bundle_path, const LV2_Feature* const* features) { Amp* amp = (Amp*)malloc(sizeof(Amp)); return (LV2_Handle)amp; } /** Connect a port to a buffer (audio thread, must be RT safe). */ static void connect_port(LV2_Handle instance, uint32_t port, void* data) { Amp* amp = (Amp*)instance; switch ((PortIndex)port) { case AMP_GAIN: amp->gain = (float*)data; break; case AMP_INPUT: amp->input = (float*)data; break; case AMP_OUTPUT: amp->output = (float*)data; break; } } /** Initialise and prepare the plugin instance for running. */ static void activate(LV2_Handle instance) { /* Nothing to do here in this trivial mostly stateless plugin. */ } #define DB_CO(g) ((g) > -90.0f ? powf(10.0f, (g) * 0.05f) : 0.0f) /** Process a block of audio (audio thread, must be RT safe). */ static void run(LV2_Handle instance, uint32_t n_samples) { Amp* amp = (Amp*)instance; const float gain = *(amp->gain); const float* const input = amp->input; float* const output = amp->output; const float coef = DB_CO(gain); for (uint32_t pos = 0; pos < n_samples; pos++) { output[pos] = input[pos] * coef; } } /** Finish running (counterpart to activate()). */ static void deactivate(LV2_Handle instance) { /* Nothing to do here in this trivial mostly stateless plugin. */ } /** Destroy a plugin instance (counterpart to instantiate()). */ static void cleanup(LV2_Handle instance) { free(instance); } /** Return extension data provided by the plugin. */ static const void* extension_data(const char* uri) { return NULL; /* This plugin has no extension data. */ } /** The LV2_Descriptor for this plugin. */ static const LV2_Descriptor descriptor = { AMP_URI, instantiate, connect_port, activate, run, deactivate, cleanup, extension_data }; /** Entry point, the host will call this function to access descriptors. */ LV2_SYMBOL_EXPORT const LV2_Descriptor* lv2_descriptor(uint32_t index) { switch (index) { case 0: return &descriptor; default: return NULL; } }
__label__pos
0.980438
Apply own function to element of array I have an array that is extracted using a PDO query from the database and I want to perform a function that cuts down the number of words in one of the elements. the function works fine but i don’t know how to apply the function to every row in the array The $rows is an array of all the records //this performs a query using PDO to get all the records but adding a LIMIT to the query $rows = $this->dao->fetchAll($offset, $entries_per_page and this is how i call the function normally ususally done if the foreach/while loop on the row element i want to truncate $this->words->trunc($row['content']); This is my function that truncates the string (in the ‘Words’ class) public function trunc($phrase, $max_words) { $phrase_array = explode(' ',$phrase); if(count($phrase_array) > $max_words && $max_words > 0) $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...'; return $phrase; } I have tried this $rows = $this->words->trunc($this->dao->fetchAll($offset, $entries_per_page), 60); but i get this error message Warning: explode() expects parameter 2 to be string, array given in C:\www\adrock\php\classes\class.words.php on line 48 Any idea how i can just truncate the ‘content’ field in the array using my function Sounds like a good case for recursion. public function trunc($phrase, $max_words) { if( is_array( $phrase ) ) { $out = array(); foreach( $phrase as $k => $v ) { $out[ $k ] = $this->trunc( $v, $max_words ); } return $out; } $phrase_array = explode(' ',$phrase); if(count($phrase_array) > $max_words && $max_words > 0) $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...'; return $phrase; } That will call your truncate on each field which may not be what you’re after. If not, I think you’ll just have to loop through your results and call your function on the one element. you cannot pass $this->dao->fetchAll($offset, $entries_per_page) directly to the trunc function, because fetchAll returns an array. what you need to do is to pass it to a variable an use that variable to pass the content data to the trunc function $result = $this->dao->fetchAll($offset, $entries_per_page); $rows = $this->words->trunc($result[‘content’], 60);
__label__pos
0.984236
1. Python Python’s PyDictionary Module Python’s PyDictionary module/package can be used for getting meaning, translation, synonyms and antonyms of words in English language. Do not that PyDictionary is a Module while Dictionary is just a Object Type. Let’s see How does PyDictionary Module works? Under the hood functions inside PyDictionary make API requests to different websites passing English Word as parameter. • For getting meaning of a word PyDictionary send API request to wordnet.princeton.edu which is a database of words and their meanings, this is developed by Princeton University • For doing translation of English Words to other languages, PyDictionary send API request to Google’s Translator and show whatever is retuned by it • For getting synonyms/antonyms of a Word, PyDictionary send API request to synonyms.com which is a database of words and their respective synonyms or antonyms Let’s use PyDictionary Module for getting information about some English words Setup/Install PyDictionary Module Install PyDictionary Module using python3 -m pip install PyDictionary on terminal/command line. Entering this will take a few sec and download/install PyDictionary Module. On terminal on MAC this process of installing will like. Installing PyDictionary Module Get Meaning of a Word using Python For getting definition/meaning of word PyDictionary Module can be used. • From PyDictionary import PyDictionary() Class using from PyDictionary import PyDictionary • Call meaning(parameter) function of PyDictionary() Class passing English word as parameter Let’s put together all of these steps to Get Meaning of Word # Getting meaning of a word using Python from PyDictionary import PyDictionary dictionary = PyDictionary() word = "Programming" # Word whose meaning you want to find using Python print(dictionary.meaning(word)) # Below is output of this code { 'Noun':['setting an order and time for planned events', 'creating a sequence of instructions to enable the computer to do something'], 'Verb':['arrange a program of or for', 'write a computer program', 'write a computer program', 'arrange a program of or for'] } Translating a Word using Python PyDictionary Module can be used for translating Words into different languages, under the hood PyDictionary translate(word, language Code) function send request to Google Translate API passing language Code parameter stating which language word need to be converted. Below is Python Code for doing translation of Words using Python Programming Language. # Getting meaning of a word using Python from PyDictionary import PyDictionary dictionary = PyDictionary() # Word which you want to convert to other language word = "Programming" # Language Code for Hindi is hi word_in_hindi = dictionary.translate(word, "hi") # Language Code for Serbian is sr word_in_serbian = dictionary.translate(word, "sr") # Language Code for French fi word_in_french = dictionary.translate(word, "fi") print(word, " in hindi is => " + word_in_hindi) print(word, " in serbian is => " + word_in_serbian) print(word, " in French is => " + word_in_french) Above Python Code will print out => Programming in hindi is => प्रोग्रामिंग Programming in serbian is => Програмирање Programming in French is => Ohjelmointi For know what would be language code for a specific language, please see this article Language Name <=> Code table put together by Google Getting Synonyms of a Word using Python Python’s PyDictionary Module can be used for getting a list of synonyms of a word, just pass word to synonym() function and it will return a list containing all of synonyms of word. Just note that its synonym() not synonyms(), having synonym() will return list of all synonyms of word rather using function synonyms() will return a AttributeError: ‘PyDictionary’ object has no attribute ‘synonyms’. Below is Python Code for finding out what are synonyms of a Word => # Getting meaning of a word using Python from PyDictionary import PyDictionary dictionary = PyDictionary() # Word whose synonym you want to find using Python word = "Computer" # Pass word to synonym function as a parameter list_of_synonyms = dictionary.synonym(word) print(list_of_synonyms) Above Python Code will print out, a list of synonyms of word “Computer” => ['digital computer', 'busbar', 'website', 'number cruncher', 'home computer', 'totaliser', 'totalizator', 'microprocessor chip', 'computer circuit', 'micro chip', 'information processing system', 'monitor', 'totalizer', 'computer memory', 'chip', 'totalisator', 'Turing machine', 'peripheral', 'web site', 'memory board', 'server', 'processor', 'central processor', 'floppy disk', 'analog computer', 'computer hardware', 'data processor', 'diskette', 'C.P.U.', 'mainframe', 'data converter', 'internet site', 'storage', 'microchip', 'electronic computer', 'disk cache', 'machine', 'central processing unit', 'monitoring device', 'guest', 'CRT', 'platform', 'floppy', 'node', 'cathode-ray tube', 'host', 'computer storage', 'predictor', 'store', 'peripheral device', 'silicon chip', 'computing machine', 'pari-mutuel machine', 'client', 'hardware', 'memory', 'keyboard', 'site', 'CPU', 'computing device', 'computer accessory', 'bus', 'analogue computer', 'computer peripheral'] Getting Antonyms of a Word using Python Similar to finding out Synonyms of a Word, Python can also be used for finding antonyms of a Word using PyDictionary Module. Just pass word as parameter to antonym() function and this will return a list of antonyms for word. Just note that its antonym() not antonyms(), having antonym() will return list of all antonyms of word rather using function antonyms() will return a AttributeError: ‘PyDictionary’ object has no attribute ‘antonyms’. Below is Python Code for finding out what are antonyms of a Word => # Getting meaning of a word using Python from PyDictionary import PyDictionary dictionary = PyDictionary() # Word whose antonym you want to find using Python word = "night" # Pass word to antonym function as a parameter list_of_synonyms = dictionary.antonym(word) print(list_of_antonyms) Above Python Code will print out, a list of antonyms of word “night” => ['day', 'comprehensible', 'blond', 'enlightenment', 'enlightened'] Final Thoughts PyDictionary is a quite useful Python module for doing a lot of stuff with English Language Words. Specifically I’ve used this in building an APP for showing text in different languages for users accessing the app from different language speaking countries. I think that writing an article about that would be a great, probably I should find some time to write it down here on ComputerScienceHub. Anyway, If your interested in know about internals/source code of PyDictionary then check out its Github Repo -> PyDictionary Github Repo. Happy Coding 🥳 🥳 Comments to: Python’s PyDictionary Module Your email address will not be published. Ads
__label__pos
0.842267
Перейти к основному содержанию Why has Apple betrayed us? Why has Apple betrayed us by requiring a second type of security on our mobile devices? Anytime you have only one source for security credentials things are more secure. But Apple in there past few updates for their mobile devices is trying to have you put in a secondary account such as a phone number or email to allow you to unlock your lock device using a code that is sent to you. This only does one thing, it allows a back door for a third-party to contact Apple and get access to that device with a bypass code. As of now it is an option but you have to look at the rest of the options where they ask you to sign up for this "Increased Security" option to realize you can opt out of this security change. I have nothing to hide on any of my devices, but if I cannot remember my password I deserve to have the device rendered useless. Отвечено! Посмотреть ответ У меня та же проблема Это хороший вопрос? Оценка 4 Комментарии: @mayer , this is what I was talking about из A little more info from Apple. https://support.apple.com/en-us/HT204397 I really need to do some research on this before commenting, it does not sound good to me right now. из Добавить комментарий 3 Ответов Выбранное решение I agree with @admin_0 if they can get into your phones text or your email. You're already screwed. I suppose...with a text..you've got a 50/50 chance of being able to read it as the text notification pops up on the lock screen. Oddly, I don't have my texts hidden. It's convenience for me. Don't have time to open my phone every single time I get a message. Which almost backfired when I was dating a co worker. Smartly I left her number a phone number. No name assigned. One of my other co workers decided to read it. Good thing I planned ahead. I dunno, man. I been trying to get past that lock for years. I'm not gonna find the picture this late. Basically if it's one of three things that shows up after you restore the phone. Then I'm good. It's not lost or stolen, and I'm not doing anything bad. I know Apple repurposes old devices, turned in for $300 and a "new" device. There's still billions of em out there gone waste. I think it would be best for the community, if we could repurpose these devices. I believe if even one of the 52?? Guam and Puerto Rico? Got the right to repair bill. You should be able to go to that state, and they now legally have to either sell or give us schematics for how to get one of those secret machines no one can touch Был ли этот ответ полезен? Оценка 4 Добавить комментарий "This only does one thing, it allows a back door for a third-party to contact Apple and get access to that device with a bypass code." If they can crack into your back-up account then they can crack into your main account and you are no more secure then with one account. Your email security doesn't become less simply because you have two accounts instead of one. The idea behind this is, should you get locked out for whatever reason from that main account your device is not useless you can still access it through your secondary account. This doesn't make you any less secure than you already are. If they can get into the second they can get into the first and you aren't safe anyway. However you are always more than welcome to join the rest of us on Android and break away from the chains and boundaries of Apple. Был ли этот ответ полезен? Оценка 3 Комментарии: I cannot go to the Darkside. I'm too invested with Apple having gone through there on site service training course and 23 years of working on their equipment. But Apple could learn a lot from androids из Добавить комментарий This is absolute necessary because without 2FA, anyone has access to your email can lock you back out of your own device. This has been a great problem in China. Some email providers are not secure and consequently Apple IDs are compromised. Thousands of people are scammed by hackers demanding at least ¥500 for 'unlock'. Apple demand PoP and retail box matched with the device and up to 1 month manual approval for activation lock override, which is hugely inconvenient or just not possible. With 2FA, passcode locked device and a pinned SIM, it is no longer possible. However since this is still optional, people still get hacked. I don't know where you get the more entry point, less secure idea from. Maybe a little bit of security 101 can help you? Был ли этот ответ полезен? Оценка 2 Комментарии: @tomchai Hey, Tom. You have been around here for a while. Almost as long as I have. How about completing your profile? из Добавить комментарий Добавьте свой ответ Ken будет вечно благодарен. Просмотр статистики: За последние 24часов: 0 За последние 7 дней: 0 За последние 30 дней: 0 За всё время: 94
__label__pos
0.500866
Welcome to the Treehouse Community Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! Looking to learn something new? Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today. Start your free trial HTML Introduction to HTML and CSS Make It Beautiful With CSS Adding a Style to several Elements using Class In the CSS file, create a rule for the .social-links class. You don't need to write any style instructions yet. In the CSS file, create a rule for the .social-links class. You don't need to write any style instructions yet. index.html <!doctype html> <html> <head> <title>List Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <a href="#" class="social-links">Follow me on Twitter!</a> <a href="#" class="social-links">Send me an Email!</a> </body> </html> styles.css .social-links{ text-align: center; color: red; { 1 Answer Jonathan Grieve MOD Jonathan Grieve Treehouse Moderator 91,243 Points You've got the selector right, as you've probably guessed it was given for you in the instruction but you needed to leave it empty for this part of the challenge. Remember, the instructions for selectors of made up of pairs of properties and values. .social-links{ }
__label__pos
0.917177
Save the date! Google I/O returns May 18-20 Register now tf.resource_loader.load_resource View source on GitHub Load the resource at given path, where path is relative to tensorflow/. path a string resource path relative to tensorflow/. The contents of that resource. IOError If the path is not found, or the resource can't be opened.
__label__pos
0.827651
1 / 15 How do you find the product of 23 x 15 using the area model? How do you find the product of 23 x 15 using the area model?. 20. 3. 10. 5. In this lesson you will learn how to multiply multi-digit numbers by using the area model. Product – The result when two numbers are multiplied. For Example: 4 x 5 = 20. product. adah Télécharger la présentation How do you find the product of 23 x 15 using the area model? An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher. E N D Presentation Transcript 1. How do you find the product of 23 x 15 using the area model? 20 3 10 5 2. In this lesson you will learn how to multiply multi-digit numbersby using the area model. 3. Product – The result when two numbers are multiplied. For Example: 4 x 5 = 20 product 4. Multiplication is repeated addition. 32 + 32 + 32 + 32 + 32 32 x 5 Multiplication is faster! 5. Multiplication sentences can be represented by using an array. 6 4 4 x 6 = 24 6. Multiplying by powers of 10. 36 x 10 = 360 36 x 100 = 3,600 36 x 1,000 = 36,000 7. Multiplying each digit as if it represents a number of “ones.” It is important to remember the place value of each digit. 36 x 5 = 30 x 5 + 6 x 5 8. Multiply 23 x 15 using the area model. 20 + 3 10 + 5 200 100 30 + 15 445 x 20 3 10 200 30 15 5 100 9. Multiply 225 x 12 using the area model. 2000 400 200 40 50 + 10 2700 200 + 20+ 5 10 + 2 x 200 20 5 200 2000 50 10 400 40 10 2 10. In this lesson you have learned how to multiply multi-digit numbersby using the area model. 11. Multiply 352 x 32 using the area model. 12. In your math journal, draw an area model to find the product of 542 x 78. 13. Roll a dice 4 times to fill in the blanks and create a multiplication problem like the one below. x • Use the area model to find the product. 14. 1). Find the multiplication sentence that matches the model below. 40 7 • 24 x 37 • 47 x 23 • 47 + 23 • 60 x 10 20 3 15. 2) Multiply 351 x 62 using an area model. More Related
__label__pos
0.997121
Rails Application Initialization in 20 Easy Steps Rails::Initializer is the main class that handles setting up the Rails environment within Ruby. Initialization is kicked off by config/environment.rb, which contains the block: Rails::Initializer.run do |config| # (configuration) end   Rails::Initializer.run yields a new Rails::Configuration object to the block. Then run creates a new Rails::Initializer object and calls its process method, which takes the following steps in order to initialize Rails: 1. check_ruby_version: Ensures that Ruby 1.8.2 or above (but not 1.8.3) is being used. 2. set_load_path: Adds the framework paths (RailTies, ActionPack,* ActiveSupport, ActiveRecord, Action Mailer, and Action Web Service) and the application’s load paths to the Ruby load path. The framework is loaded from vendor/rails or a location specified in RAILS_FRAMEWORK_ROOT. 3. require_frameworks: Loads each framework listed in the frameworks configura- tion option. If the framework path was not specified in RAILS_FRAMEWORK_ROOT and it does not exist in vendor/rails, Initializer will assume the frameworks are installed as RubyGems. 4. set_autoload_paths: Sets the autoload paths based on the values of the load_ paths and load_once_paths configuration variables. These determine which paths will be searched to resolve unknown constants. The load_paths option is the same one that provided the application’s load paths in step 2. 5. load_environment: Loads and evaluates the environment-specific (development, production, or test) configuration file. 6. initialize_encoding: Sets $KCODE to u for UTF-8 support throughout Rails. 7. initialize_database: If ActiveRecord is being used, sets up its database configu- ration and connects to the database server. 8. initialize_logger: Sets up the logger and sets the top-level constant RAILS_ DEFAULT_LOGGER to the instance. If logger is specified in the configuration, it is used. If not, a new logger is created and directed to the log_path specified. If that fails, a warning is displayed and logging is redirected to standard error. 9. initialize_framework_logging: Sets the logger for ActiveRecord, ActionControl- ler, and Action Mailer (if they are being used) to the logger that was just set up. 10. initialize_framework_views: Sets the view path for ActionController and Action Mailer to the value of the view_path configuration item. 11. initialize_dependency_mechanism: Sets Dependencies.mechanism (which deter- mines whether to use require or load to load files) based on the setting of the cache_classes configuration item. 12. initialize_whiny_nils: If the whiny_nils configuration item is true, adds the Whiny Nil extensions (that complain when trying to call id or other methods on nil) to NilClass. 13. initialize_temporary_directories: Sets ActionController’s temporary session and cache directories if they exist in the filesystem. 14. initialize_framework_settings: Transforms the framework-specific configura- tion settings into method calls on the frameworks’ Base classes. For example, consider the configuration option: config.active_record.schema_format = :sql The config.active_record object is an instance of Rails::OrderedOptions, which is basically an ordered hash (ordered to keep the configuration directives in order). During initialization, the initialize_framework_settings method trans- forms it into the following: ActiveRecord::Base.schema_format = :sql This offers the advantage that the Configuration object doesn’t have to be updated every time a framework adds or changes a configuration option. 15. add_support_load_paths: Adds load paths for support functions. This function is currently empty. 16. load_plugins: Loads the plugins from paths in the plugin_paths configuration item (default vendor/plugins). If a plugins configuration item is specified, load those plugins respecting that load order. Plugins are loaded close to the end of the process so that they can override any already loaded component. 17. load_observers: Instantiates ActiveRecord observers. This is done after plugins so that plugins have an opportunity to modify the observer classes. 18. initialize_routing: Loads and processes the routes. Also sets the controller paths from the controller_paths configuration item. 19. after_initialize: Calls any user-defined after_initialize callback. These call- backs are defined in the configuration block by config.after_initialize { … }. 20. load_application_initializers: Loads all Ruby files in RAILS_ROOT/config/ initializers and any of its subdirectories. Old framework initialization that may previously have been contained in config/environment.rb can now properly be broken out into separate initializers. Now the framework is ready to receive requests. Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out /  Change ) Google photo You are commenting using your Google account. Log Out /  Change ) Twitter picture You are commenting using your Twitter account. Log Out /  Change ) Facebook photo You are commenting using your Facebook account. Log Out /  Change ) Connecting to %s
__label__pos
0.790332
Version:  2.0.40 2.2.26 2.4.37 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 3.19 4.0 4.1 4.2 4.3 4.4 4.5 4.6 Linux/sound/pci/rme96.c 1 /* 2 * ALSA driver for RME Digi96, Digi96/8 and Digi96/8 PRO/PAD/PST audio 3 * interfaces 4 * 5 * Copyright (c) 2000, 2001 Anders Torger <[email protected]> 6 * 7 * Thanks to Henk Hesselink <[email protected]> for the analog volume control 8 * code. 9 * 10 * This program is free software; you can redistribute it and/or modify 11 * it under the terms of the GNU General Public License as published by 12 * the Free Software Foundation; either version 2 of the License, or 13 * (at your option) any later version. 14 * 15 * This program is distributed in the hope that it will be useful, 16 * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 * GNU General Public License for more details. 19 * 20 * You should have received a copy of the GNU General Public License 21 * along with this program; if not, write to the Free Software 22 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 23 * 24 */ 25 26 #include <linux/delay.h> 27 #include <linux/init.h> 28 #include <linux/interrupt.h> 29 #include <linux/pci.h> 30 #include <linux/module.h> 31 #include <linux/vmalloc.h> 32 #include <linux/io.h> 33 34 #include <sound/core.h> 35 #include <sound/info.h> 36 #include <sound/control.h> 37 #include <sound/pcm.h> 38 #include <sound/pcm_params.h> 39 #include <sound/asoundef.h> 40 #include <sound/initval.h> 41 42 /* note, two last pcis should be equal, it is not a bug */ 43 44 MODULE_AUTHOR("Anders Torger <[email protected]>"); 45 MODULE_DESCRIPTION("RME Digi96, Digi96/8, Digi96/8 PRO, Digi96/8 PST, " 46 "Digi96/8 PAD"); 47 MODULE_LICENSE("GPL"); 48 MODULE_SUPPORTED_DEVICE("{{RME,Digi96}," 49 "{RME,Digi96/8}," 50 "{RME,Digi96/8 PRO}," 51 "{RME,Digi96/8 PST}," 52 "{RME,Digi96/8 PAD}}"); 53 54 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ 55 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ 56 static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */ 57 58 module_param_array(index, int, NULL, 0444); 59 MODULE_PARM_DESC(index, "Index value for RME Digi96 soundcard."); 60 module_param_array(id, charp, NULL, 0444); 61 MODULE_PARM_DESC(id, "ID string for RME Digi96 soundcard."); 62 module_param_array(enable, bool, NULL, 0444); 63 MODULE_PARM_DESC(enable, "Enable RME Digi96 soundcard."); 64 65 /* 66 * Defines for RME Digi96 series, from internal RME reference documents 67 * dated 12.01.00 68 */ 69 70 #define RME96_SPDIF_NCHANNELS 2 71 72 /* Playback and capture buffer size */ 73 #define RME96_BUFFER_SIZE 0x10000 74 75 /* IO area size */ 76 #define RME96_IO_SIZE 0x60000 77 78 /* IO area offsets */ 79 #define RME96_IO_PLAY_BUFFER 0x0 80 #define RME96_IO_REC_BUFFER 0x10000 81 #define RME96_IO_CONTROL_REGISTER 0x20000 82 #define RME96_IO_ADDITIONAL_REG 0x20004 83 #define RME96_IO_CONFIRM_PLAY_IRQ 0x20008 84 #define RME96_IO_CONFIRM_REC_IRQ 0x2000C 85 #define RME96_IO_SET_PLAY_POS 0x40000 86 #define RME96_IO_RESET_PLAY_POS 0x4FFFC 87 #define RME96_IO_SET_REC_POS 0x50000 88 #define RME96_IO_RESET_REC_POS 0x5FFFC 89 #define RME96_IO_GET_PLAY_POS 0x20000 90 #define RME96_IO_GET_REC_POS 0x30000 91 92 /* Write control register bits */ 93 #define RME96_WCR_START (1 << 0) 94 #define RME96_WCR_START_2 (1 << 1) 95 #define RME96_WCR_GAIN_0 (1 << 2) 96 #define RME96_WCR_GAIN_1 (1 << 3) 97 #define RME96_WCR_MODE24 (1 << 4) 98 #define RME96_WCR_MODE24_2 (1 << 5) 99 #define RME96_WCR_BM (1 << 6) 100 #define RME96_WCR_BM_2 (1 << 7) 101 #define RME96_WCR_ADAT (1 << 8) 102 #define RME96_WCR_FREQ_0 (1 << 9) 103 #define RME96_WCR_FREQ_1 (1 << 10) 104 #define RME96_WCR_DS (1 << 11) 105 #define RME96_WCR_PRO (1 << 12) 106 #define RME96_WCR_EMP (1 << 13) 107 #define RME96_WCR_SEL (1 << 14) 108 #define RME96_WCR_MASTER (1 << 15) 109 #define RME96_WCR_PD (1 << 16) 110 #define RME96_WCR_INP_0 (1 << 17) 111 #define RME96_WCR_INP_1 (1 << 18) 112 #define RME96_WCR_THRU_0 (1 << 19) 113 #define RME96_WCR_THRU_1 (1 << 20) 114 #define RME96_WCR_THRU_2 (1 << 21) 115 #define RME96_WCR_THRU_3 (1 << 22) 116 #define RME96_WCR_THRU_4 (1 << 23) 117 #define RME96_WCR_THRU_5 (1 << 24) 118 #define RME96_WCR_THRU_6 (1 << 25) 119 #define RME96_WCR_THRU_7 (1 << 26) 120 #define RME96_WCR_DOLBY (1 << 27) 121 #define RME96_WCR_MONITOR_0 (1 << 28) 122 #define RME96_WCR_MONITOR_1 (1 << 29) 123 #define RME96_WCR_ISEL (1 << 30) 124 #define RME96_WCR_IDIS (1 << 31) 125 126 #define RME96_WCR_BITPOS_GAIN_0 2 127 #define RME96_WCR_BITPOS_GAIN_1 3 128 #define RME96_WCR_BITPOS_FREQ_0 9 129 #define RME96_WCR_BITPOS_FREQ_1 10 130 #define RME96_WCR_BITPOS_INP_0 17 131 #define RME96_WCR_BITPOS_INP_1 18 132 #define RME96_WCR_BITPOS_MONITOR_0 28 133 #define RME96_WCR_BITPOS_MONITOR_1 29 134 135 /* Read control register bits */ 136 #define RME96_RCR_AUDIO_ADDR_MASK 0xFFFF 137 #define RME96_RCR_IRQ_2 (1 << 16) 138 #define RME96_RCR_T_OUT (1 << 17) 139 #define RME96_RCR_DEV_ID_0 (1 << 21) 140 #define RME96_RCR_DEV_ID_1 (1 << 22) 141 #define RME96_RCR_LOCK (1 << 23) 142 #define RME96_RCR_VERF (1 << 26) 143 #define RME96_RCR_F0 (1 << 27) 144 #define RME96_RCR_F1 (1 << 28) 145 #define RME96_RCR_F2 (1 << 29) 146 #define RME96_RCR_AUTOSYNC (1 << 30) 147 #define RME96_RCR_IRQ (1 << 31) 148 149 #define RME96_RCR_BITPOS_F0 27 150 #define RME96_RCR_BITPOS_F1 28 151 #define RME96_RCR_BITPOS_F2 29 152 153 /* Additional register bits */ 154 #define RME96_AR_WSEL (1 << 0) 155 #define RME96_AR_ANALOG (1 << 1) 156 #define RME96_AR_FREQPAD_0 (1 << 2) 157 #define RME96_AR_FREQPAD_1 (1 << 3) 158 #define RME96_AR_FREQPAD_2 (1 << 4) 159 #define RME96_AR_PD2 (1 << 5) 160 #define RME96_AR_DAC_EN (1 << 6) 161 #define RME96_AR_CLATCH (1 << 7) 162 #define RME96_AR_CCLK (1 << 8) 163 #define RME96_AR_CDATA (1 << 9) 164 165 #define RME96_AR_BITPOS_F0 2 166 #define RME96_AR_BITPOS_F1 3 167 #define RME96_AR_BITPOS_F2 4 168 169 /* Monitor tracks */ 170 #define RME96_MONITOR_TRACKS_1_2 0 171 #define RME96_MONITOR_TRACKS_3_4 1 172 #define RME96_MONITOR_TRACKS_5_6 2 173 #define RME96_MONITOR_TRACKS_7_8 3 174 175 /* Attenuation */ 176 #define RME96_ATTENUATION_0 0 177 #define RME96_ATTENUATION_6 1 178 #define RME96_ATTENUATION_12 2 179 #define RME96_ATTENUATION_18 3 180 181 /* Input types */ 182 #define RME96_INPUT_OPTICAL 0 183 #define RME96_INPUT_COAXIAL 1 184 #define RME96_INPUT_INTERNAL 2 185 #define RME96_INPUT_XLR 3 186 #define RME96_INPUT_ANALOG 4 187 188 /* Clock modes */ 189 #define RME96_CLOCKMODE_SLAVE 0 190 #define RME96_CLOCKMODE_MASTER 1 191 #define RME96_CLOCKMODE_WORDCLOCK 2 192 193 /* Block sizes in bytes */ 194 #define RME96_SMALL_BLOCK_SIZE 2048 195 #define RME96_LARGE_BLOCK_SIZE 8192 196 197 /* Volume control */ 198 #define RME96_AD1852_VOL_BITS 14 199 #define RME96_AD1855_VOL_BITS 10 200 201 /* Defines for snd_rme96_trigger */ 202 #define RME96_TB_START_PLAYBACK 1 203 #define RME96_TB_START_CAPTURE 2 204 #define RME96_TB_STOP_PLAYBACK 4 205 #define RME96_TB_STOP_CAPTURE 8 206 #define RME96_TB_RESET_PLAYPOS 16 207 #define RME96_TB_RESET_CAPTUREPOS 32 208 #define RME96_TB_CLEAR_PLAYBACK_IRQ 64 209 #define RME96_TB_CLEAR_CAPTURE_IRQ 128 210 #define RME96_RESUME_PLAYBACK (RME96_TB_START_PLAYBACK) 211 #define RME96_RESUME_CAPTURE (RME96_TB_START_CAPTURE) 212 #define RME96_RESUME_BOTH (RME96_RESUME_PLAYBACK \ 213 | RME96_RESUME_CAPTURE) 214 #define RME96_START_PLAYBACK (RME96_TB_START_PLAYBACK \ 215 | RME96_TB_RESET_PLAYPOS) 216 #define RME96_START_CAPTURE (RME96_TB_START_CAPTURE \ 217 | RME96_TB_RESET_CAPTUREPOS) 218 #define RME96_START_BOTH (RME96_START_PLAYBACK \ 219 | RME96_START_CAPTURE) 220 #define RME96_STOP_PLAYBACK (RME96_TB_STOP_PLAYBACK \ 221 | RME96_TB_CLEAR_PLAYBACK_IRQ) 222 #define RME96_STOP_CAPTURE (RME96_TB_STOP_CAPTURE \ 223 | RME96_TB_CLEAR_CAPTURE_IRQ) 224 #define RME96_STOP_BOTH (RME96_STOP_PLAYBACK \ 225 | RME96_STOP_CAPTURE) 226 227 struct rme96 { 228 spinlock_t lock; 229 int irq; 230 unsigned long port; 231 void __iomem *iobase; 232 233 u32 wcreg; /* cached write control register value */ 234 u32 wcreg_spdif; /* S/PDIF setup */ 235 u32 wcreg_spdif_stream; /* S/PDIF setup (temporary) */ 236 u32 rcreg; /* cached read control register value */ 237 u32 areg; /* cached additional register value */ 238 u16 vol[2]; /* cached volume of analog output */ 239 240 u8 rev; /* card revision number */ 241 242 #ifdef CONFIG_PM_SLEEP 243 u32 playback_pointer; 244 u32 capture_pointer; 245 void *playback_suspend_buffer; 246 void *capture_suspend_buffer; 247 #endif 248 249 struct snd_pcm_substream *playback_substream; 250 struct snd_pcm_substream *capture_substream; 251 252 int playback_frlog; /* log2 of framesize */ 253 int capture_frlog; 254 255 size_t playback_periodsize; /* in bytes, zero if not used */ 256 size_t capture_periodsize; /* in bytes, zero if not used */ 257 258 struct snd_card *card; 259 struct snd_pcm *spdif_pcm; 260 struct snd_pcm *adat_pcm; 261 struct pci_dev *pci; 262 struct snd_kcontrol *spdif_ctl; 263 }; 264 265 static const struct pci_device_id snd_rme96_ids[] = { 266 { PCI_VDEVICE(XILINX, PCI_DEVICE_ID_RME_DIGI96), 0, }, 267 { PCI_VDEVICE(XILINX, PCI_DEVICE_ID_RME_DIGI96_8), 0, }, 268 { PCI_VDEVICE(XILINX, PCI_DEVICE_ID_RME_DIGI96_8_PRO), 0, }, 269 { PCI_VDEVICE(XILINX, PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST), 0, }, 270 { 0, } 271 }; 272 273 MODULE_DEVICE_TABLE(pci, snd_rme96_ids); 274 275 #define RME96_ISPLAYING(rme96) ((rme96)->wcreg & RME96_WCR_START) 276 #define RME96_ISRECORDING(rme96) ((rme96)->wcreg & RME96_WCR_START_2) 277 #define RME96_HAS_ANALOG_IN(rme96) ((rme96)->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST) 278 #define RME96_HAS_ANALOG_OUT(rme96) ((rme96)->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PRO || \ 279 (rme96)->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST) 280 #define RME96_DAC_IS_1852(rme96) (RME96_HAS_ANALOG_OUT(rme96) && (rme96)->rev >= 4) 281 #define RME96_DAC_IS_1855(rme96) (((rme96)->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST && (rme96)->rev < 4) || \ 282 ((rme96)->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PRO && (rme96)->rev == 2)) 283 #define RME96_185X_MAX_OUT(rme96) ((1 << (RME96_DAC_IS_1852(rme96) ? RME96_AD1852_VOL_BITS : RME96_AD1855_VOL_BITS)) - 1) 284 285 static int 286 snd_rme96_playback_prepare(struct snd_pcm_substream *substream); 287 288 static int 289 snd_rme96_capture_prepare(struct snd_pcm_substream *substream); 290 291 static int 292 snd_rme96_playback_trigger(struct snd_pcm_substream *substream, 293 int cmd); 294 295 static int 296 snd_rme96_capture_trigger(struct snd_pcm_substream *substream, 297 int cmd); 298 299 static snd_pcm_uframes_t 300 snd_rme96_playback_pointer(struct snd_pcm_substream *substream); 301 302 static snd_pcm_uframes_t 303 snd_rme96_capture_pointer(struct snd_pcm_substream *substream); 304 305 static void snd_rme96_proc_init(struct rme96 *rme96); 306 307 static int 308 snd_rme96_create_switches(struct snd_card *card, 309 struct rme96 *rme96); 310 311 static int 312 snd_rme96_getinputtype(struct rme96 *rme96); 313 314 static inline unsigned int 315 snd_rme96_playback_ptr(struct rme96 *rme96) 316 { 317 return (readl(rme96->iobase + RME96_IO_GET_PLAY_POS) 318 & RME96_RCR_AUDIO_ADDR_MASK) >> rme96->playback_frlog; 319 } 320 321 static inline unsigned int 322 snd_rme96_capture_ptr(struct rme96 *rme96) 323 { 324 return (readl(rme96->iobase + RME96_IO_GET_REC_POS) 325 & RME96_RCR_AUDIO_ADDR_MASK) >> rme96->capture_frlog; 326 } 327 328 static int 329 snd_rme96_playback_silence(struct snd_pcm_substream *substream, 330 int channel, /* not used (interleaved data) */ 331 snd_pcm_uframes_t pos, 332 snd_pcm_uframes_t count) 333 { 334 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 335 count <<= rme96->playback_frlog; 336 pos <<= rme96->playback_frlog; 337 memset_io(rme96->iobase + RME96_IO_PLAY_BUFFER + pos, 338 0, count); 339 return 0; 340 } 341 342 static int 343 snd_rme96_playback_copy(struct snd_pcm_substream *substream, 344 int channel, /* not used (interleaved data) */ 345 snd_pcm_uframes_t pos, 346 void __user *src, 347 snd_pcm_uframes_t count) 348 { 349 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 350 count <<= rme96->playback_frlog; 351 pos <<= rme96->playback_frlog; 352 return copy_from_user_toio(rme96->iobase + RME96_IO_PLAY_BUFFER + pos, src, 353 count); 354 } 355 356 static int 357 snd_rme96_capture_copy(struct snd_pcm_substream *substream, 358 int channel, /* not used (interleaved data) */ 359 snd_pcm_uframes_t pos, 360 void __user *dst, 361 snd_pcm_uframes_t count) 362 { 363 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 364 count <<= rme96->capture_frlog; 365 pos <<= rme96->capture_frlog; 366 return copy_to_user_fromio(dst, rme96->iobase + RME96_IO_REC_BUFFER + pos, 367 count); 368 } 369 370 /* 371 * Digital output capabilities (S/PDIF) 372 */ 373 static struct snd_pcm_hardware snd_rme96_playback_spdif_info = 374 { 375 .info = (SNDRV_PCM_INFO_MMAP_IOMEM | 376 SNDRV_PCM_INFO_MMAP_VALID | 377 SNDRV_PCM_INFO_SYNC_START | 378 SNDRV_PCM_INFO_RESUME | 379 SNDRV_PCM_INFO_INTERLEAVED | 380 SNDRV_PCM_INFO_PAUSE), 381 .formats = (SNDRV_PCM_FMTBIT_S16_LE | 382 SNDRV_PCM_FMTBIT_S32_LE), 383 .rates = (SNDRV_PCM_RATE_32000 | 384 SNDRV_PCM_RATE_44100 | 385 SNDRV_PCM_RATE_48000 | 386 SNDRV_PCM_RATE_64000 | 387 SNDRV_PCM_RATE_88200 | 388 SNDRV_PCM_RATE_96000), 389 .rate_min = 32000, 390 .rate_max = 96000, 391 .channels_min = 2, 392 .channels_max = 2, 393 .buffer_bytes_max = RME96_BUFFER_SIZE, 394 .period_bytes_min = RME96_SMALL_BLOCK_SIZE, 395 .period_bytes_max = RME96_LARGE_BLOCK_SIZE, 396 .periods_min = RME96_BUFFER_SIZE / RME96_LARGE_BLOCK_SIZE, 397 .periods_max = RME96_BUFFER_SIZE / RME96_SMALL_BLOCK_SIZE, 398 .fifo_size = 0, 399 }; 400 401 /* 402 * Digital input capabilities (S/PDIF) 403 */ 404 static struct snd_pcm_hardware snd_rme96_capture_spdif_info = 405 { 406 .info = (SNDRV_PCM_INFO_MMAP_IOMEM | 407 SNDRV_PCM_INFO_MMAP_VALID | 408 SNDRV_PCM_INFO_SYNC_START | 409 SNDRV_PCM_INFO_RESUME | 410 SNDRV_PCM_INFO_INTERLEAVED | 411 SNDRV_PCM_INFO_PAUSE), 412 .formats = (SNDRV_PCM_FMTBIT_S16_LE | 413 SNDRV_PCM_FMTBIT_S32_LE), 414 .rates = (SNDRV_PCM_RATE_32000 | 415 SNDRV_PCM_RATE_44100 | 416 SNDRV_PCM_RATE_48000 | 417 SNDRV_PCM_RATE_64000 | 418 SNDRV_PCM_RATE_88200 | 419 SNDRV_PCM_RATE_96000), 420 .rate_min = 32000, 421 .rate_max = 96000, 422 .channels_min = 2, 423 .channels_max = 2, 424 .buffer_bytes_max = RME96_BUFFER_SIZE, 425 .period_bytes_min = RME96_SMALL_BLOCK_SIZE, 426 .period_bytes_max = RME96_LARGE_BLOCK_SIZE, 427 .periods_min = RME96_BUFFER_SIZE / RME96_LARGE_BLOCK_SIZE, 428 .periods_max = RME96_BUFFER_SIZE / RME96_SMALL_BLOCK_SIZE, 429 .fifo_size = 0, 430 }; 431 432 /* 433 * Digital output capabilities (ADAT) 434 */ 435 static struct snd_pcm_hardware snd_rme96_playback_adat_info = 436 { 437 .info = (SNDRV_PCM_INFO_MMAP_IOMEM | 438 SNDRV_PCM_INFO_MMAP_VALID | 439 SNDRV_PCM_INFO_SYNC_START | 440 SNDRV_PCM_INFO_RESUME | 441 SNDRV_PCM_INFO_INTERLEAVED | 442 SNDRV_PCM_INFO_PAUSE), 443 .formats = (SNDRV_PCM_FMTBIT_S16_LE | 444 SNDRV_PCM_FMTBIT_S32_LE), 445 .rates = (SNDRV_PCM_RATE_44100 | 446 SNDRV_PCM_RATE_48000), 447 .rate_min = 44100, 448 .rate_max = 48000, 449 .channels_min = 8, 450 .channels_max = 8, 451 .buffer_bytes_max = RME96_BUFFER_SIZE, 452 .period_bytes_min = RME96_SMALL_BLOCK_SIZE, 453 .period_bytes_max = RME96_LARGE_BLOCK_SIZE, 454 .periods_min = RME96_BUFFER_SIZE / RME96_LARGE_BLOCK_SIZE, 455 .periods_max = RME96_BUFFER_SIZE / RME96_SMALL_BLOCK_SIZE, 456 .fifo_size = 0, 457 }; 458 459 /* 460 * Digital input capabilities (ADAT) 461 */ 462 static struct snd_pcm_hardware snd_rme96_capture_adat_info = 463 { 464 .info = (SNDRV_PCM_INFO_MMAP_IOMEM | 465 SNDRV_PCM_INFO_MMAP_VALID | 466 SNDRV_PCM_INFO_SYNC_START | 467 SNDRV_PCM_INFO_RESUME | 468 SNDRV_PCM_INFO_INTERLEAVED | 469 SNDRV_PCM_INFO_PAUSE), 470 .formats = (SNDRV_PCM_FMTBIT_S16_LE | 471 SNDRV_PCM_FMTBIT_S32_LE), 472 .rates = (SNDRV_PCM_RATE_44100 | 473 SNDRV_PCM_RATE_48000), 474 .rate_min = 44100, 475 .rate_max = 48000, 476 .channels_min = 8, 477 .channels_max = 8, 478 .buffer_bytes_max = RME96_BUFFER_SIZE, 479 .period_bytes_min = RME96_SMALL_BLOCK_SIZE, 480 .period_bytes_max = RME96_LARGE_BLOCK_SIZE, 481 .periods_min = RME96_BUFFER_SIZE / RME96_LARGE_BLOCK_SIZE, 482 .periods_max = RME96_BUFFER_SIZE / RME96_SMALL_BLOCK_SIZE, 483 .fifo_size = 0, 484 }; 485 486 /* 487 * The CDATA, CCLK and CLATCH bits can be used to write to the SPI interface 488 * of the AD1852 or AD1852 D/A converter on the board. CDATA must be set up 489 * on the falling edge of CCLK and be stable on the rising edge. The rising 490 * edge of CLATCH after the last data bit clocks in the whole data word. 491 * A fast processor could probably drive the SPI interface faster than the 492 * DAC can handle (3MHz for the 1855, unknown for the 1852). The udelay(1) 493 * limits the data rate to 500KHz and only causes a delay of 33 microsecs. 494 * 495 * NOTE: increased delay from 1 to 10, since there where problems setting 496 * the volume. 497 */ 498 static void 499 snd_rme96_write_SPI(struct rme96 *rme96, u16 val) 500 { 501 int i; 502 503 for (i = 0; i < 16; i++) { 504 if (val & 0x8000) { 505 rme96->areg |= RME96_AR_CDATA; 506 } else { 507 rme96->areg &= ~RME96_AR_CDATA; 508 } 509 rme96->areg &= ~(RME96_AR_CCLK | RME96_AR_CLATCH); 510 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 511 udelay(10); 512 rme96->areg |= RME96_AR_CCLK; 513 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 514 udelay(10); 515 val <<= 1; 516 } 517 rme96->areg &= ~(RME96_AR_CCLK | RME96_AR_CDATA); 518 rme96->areg |= RME96_AR_CLATCH; 519 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 520 udelay(10); 521 rme96->areg &= ~RME96_AR_CLATCH; 522 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 523 } 524 525 static void 526 snd_rme96_apply_dac_volume(struct rme96 *rme96) 527 { 528 if (RME96_DAC_IS_1852(rme96)) { 529 snd_rme96_write_SPI(rme96, (rme96->vol[0] << 2) | 0x0); 530 snd_rme96_write_SPI(rme96, (rme96->vol[1] << 2) | 0x2); 531 } else if (RME96_DAC_IS_1855(rme96)) { 532 snd_rme96_write_SPI(rme96, (rme96->vol[0] & 0x3FF) | 0x000); 533 snd_rme96_write_SPI(rme96, (rme96->vol[1] & 0x3FF) | 0x400); 534 } 535 } 536 537 static void 538 snd_rme96_reset_dac(struct rme96 *rme96) 539 { 540 writel(rme96->wcreg | RME96_WCR_PD, 541 rme96->iobase + RME96_IO_CONTROL_REGISTER); 542 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 543 } 544 545 static int 546 snd_rme96_getmontracks(struct rme96 *rme96) 547 { 548 return ((rme96->wcreg >> RME96_WCR_BITPOS_MONITOR_0) & 1) + 549 (((rme96->wcreg >> RME96_WCR_BITPOS_MONITOR_1) & 1) << 1); 550 } 551 552 static int 553 snd_rme96_setmontracks(struct rme96 *rme96, 554 int montracks) 555 { 556 if (montracks & 1) { 557 rme96->wcreg |= RME96_WCR_MONITOR_0; 558 } else { 559 rme96->wcreg &= ~RME96_WCR_MONITOR_0; 560 } 561 if (montracks & 2) { 562 rme96->wcreg |= RME96_WCR_MONITOR_1; 563 } else { 564 rme96->wcreg &= ~RME96_WCR_MONITOR_1; 565 } 566 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 567 return 0; 568 } 569 570 static int 571 snd_rme96_getattenuation(struct rme96 *rme96) 572 { 573 return ((rme96->wcreg >> RME96_WCR_BITPOS_GAIN_0) & 1) + 574 (((rme96->wcreg >> RME96_WCR_BITPOS_GAIN_1) & 1) << 1); 575 } 576 577 static int 578 snd_rme96_setattenuation(struct rme96 *rme96, 579 int attenuation) 580 { 581 switch (attenuation) { 582 case 0: 583 rme96->wcreg = (rme96->wcreg & ~RME96_WCR_GAIN_0) & 584 ~RME96_WCR_GAIN_1; 585 break; 586 case 1: 587 rme96->wcreg = (rme96->wcreg | RME96_WCR_GAIN_0) & 588 ~RME96_WCR_GAIN_1; 589 break; 590 case 2: 591 rme96->wcreg = (rme96->wcreg & ~RME96_WCR_GAIN_0) | 592 RME96_WCR_GAIN_1; 593 break; 594 case 3: 595 rme96->wcreg = (rme96->wcreg | RME96_WCR_GAIN_0) | 596 RME96_WCR_GAIN_1; 597 break; 598 default: 599 return -EINVAL; 600 } 601 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 602 return 0; 603 } 604 605 static int 606 snd_rme96_capture_getrate(struct rme96 *rme96, 607 int *is_adat) 608 { 609 int n, rate; 610 611 *is_adat = 0; 612 if (rme96->areg & RME96_AR_ANALOG) { 613 /* Analog input, overrides S/PDIF setting */ 614 n = ((rme96->areg >> RME96_AR_BITPOS_F0) & 1) + 615 (((rme96->areg >> RME96_AR_BITPOS_F1) & 1) << 1); 616 switch (n) { 617 case 1: 618 rate = 32000; 619 break; 620 case 2: 621 rate = 44100; 622 break; 623 case 3: 624 rate = 48000; 625 break; 626 default: 627 return -1; 628 } 629 return (rme96->areg & RME96_AR_BITPOS_F2) ? rate << 1 : rate; 630 } 631 632 rme96->rcreg = readl(rme96->iobase + RME96_IO_CONTROL_REGISTER); 633 if (rme96->rcreg & RME96_RCR_LOCK) { 634 /* ADAT rate */ 635 *is_adat = 1; 636 if (rme96->rcreg & RME96_RCR_T_OUT) { 637 return 48000; 638 } 639 return 44100; 640 } 641 642 if (rme96->rcreg & RME96_RCR_VERF) { 643 return -1; 644 } 645 646 /* S/PDIF rate */ 647 n = ((rme96->rcreg >> RME96_RCR_BITPOS_F0) & 1) + 648 (((rme96->rcreg >> RME96_RCR_BITPOS_F1) & 1) << 1) + 649 (((rme96->rcreg >> RME96_RCR_BITPOS_F2) & 1) << 2); 650 651 switch (n) { 652 case 0: 653 if (rme96->rcreg & RME96_RCR_T_OUT) { 654 return 64000; 655 } 656 return -1; 657 case 3: return 96000; 658 case 4: return 88200; 659 case 5: return 48000; 660 case 6: return 44100; 661 case 7: return 32000; 662 default: 663 break; 664 } 665 return -1; 666 } 667 668 static int 669 snd_rme96_playback_getrate(struct rme96 *rme96) 670 { 671 int rate, dummy; 672 673 if (!(rme96->wcreg & RME96_WCR_MASTER) && 674 snd_rme96_getinputtype(rme96) != RME96_INPUT_ANALOG && 675 (rate = snd_rme96_capture_getrate(rme96, &dummy)) > 0) 676 { 677 /* slave clock */ 678 return rate; 679 } 680 rate = ((rme96->wcreg >> RME96_WCR_BITPOS_FREQ_0) & 1) + 681 (((rme96->wcreg >> RME96_WCR_BITPOS_FREQ_1) & 1) << 1); 682 switch (rate) { 683 case 1: 684 rate = 32000; 685 break; 686 case 2: 687 rate = 44100; 688 break; 689 case 3: 690 rate = 48000; 691 break; 692 default: 693 return -1; 694 } 695 return (rme96->wcreg & RME96_WCR_DS) ? rate << 1 : rate; 696 } 697 698 static int 699 snd_rme96_playback_setrate(struct rme96 *rme96, 700 int rate) 701 { 702 int ds; 703 704 ds = rme96->wcreg & RME96_WCR_DS; 705 switch (rate) { 706 case 32000: 707 rme96->wcreg &= ~RME96_WCR_DS; 708 rme96->wcreg = (rme96->wcreg | RME96_WCR_FREQ_0) & 709 ~RME96_WCR_FREQ_1; 710 break; 711 case 44100: 712 rme96->wcreg &= ~RME96_WCR_DS; 713 rme96->wcreg = (rme96->wcreg | RME96_WCR_FREQ_1) & 714 ~RME96_WCR_FREQ_0; 715 break; 716 case 48000: 717 rme96->wcreg &= ~RME96_WCR_DS; 718 rme96->wcreg = (rme96->wcreg | RME96_WCR_FREQ_0) | 719 RME96_WCR_FREQ_1; 720 break; 721 case 64000: 722 rme96->wcreg |= RME96_WCR_DS; 723 rme96->wcreg = (rme96->wcreg | RME96_WCR_FREQ_0) & 724 ~RME96_WCR_FREQ_1; 725 break; 726 case 88200: 727 rme96->wcreg |= RME96_WCR_DS; 728 rme96->wcreg = (rme96->wcreg | RME96_WCR_FREQ_1) & 729 ~RME96_WCR_FREQ_0; 730 break; 731 case 96000: 732 rme96->wcreg |= RME96_WCR_DS; 733 rme96->wcreg = (rme96->wcreg | RME96_WCR_FREQ_0) | 734 RME96_WCR_FREQ_1; 735 break; 736 default: 737 return -EINVAL; 738 } 739 if ((!ds && rme96->wcreg & RME96_WCR_DS) || 740 (ds && !(rme96->wcreg & RME96_WCR_DS))) 741 { 742 /* change to/from double-speed: reset the DAC (if available) */ 743 snd_rme96_reset_dac(rme96); 744 return 1; /* need to restore volume */ 745 } else { 746 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 747 return 0; 748 } 749 } 750 751 static int 752 snd_rme96_capture_analog_setrate(struct rme96 *rme96, 753 int rate) 754 { 755 switch (rate) { 756 case 32000: 757 rme96->areg = ((rme96->areg | RME96_AR_FREQPAD_0) & 758 ~RME96_AR_FREQPAD_1) & ~RME96_AR_FREQPAD_2; 759 break; 760 case 44100: 761 rme96->areg = ((rme96->areg & ~RME96_AR_FREQPAD_0) | 762 RME96_AR_FREQPAD_1) & ~RME96_AR_FREQPAD_2; 763 break; 764 case 48000: 765 rme96->areg = ((rme96->areg | RME96_AR_FREQPAD_0) | 766 RME96_AR_FREQPAD_1) & ~RME96_AR_FREQPAD_2; 767 break; 768 case 64000: 769 if (rme96->rev < 4) { 770 return -EINVAL; 771 } 772 rme96->areg = ((rme96->areg | RME96_AR_FREQPAD_0) & 773 ~RME96_AR_FREQPAD_1) | RME96_AR_FREQPAD_2; 774 break; 775 case 88200: 776 if (rme96->rev < 4) { 777 return -EINVAL; 778 } 779 rme96->areg = ((rme96->areg & ~RME96_AR_FREQPAD_0) | 780 RME96_AR_FREQPAD_1) | RME96_AR_FREQPAD_2; 781 break; 782 case 96000: 783 rme96->areg = ((rme96->areg | RME96_AR_FREQPAD_0) | 784 RME96_AR_FREQPAD_1) | RME96_AR_FREQPAD_2; 785 break; 786 default: 787 return -EINVAL; 788 } 789 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 790 return 0; 791 } 792 793 static int 794 snd_rme96_setclockmode(struct rme96 *rme96, 795 int mode) 796 { 797 switch (mode) { 798 case RME96_CLOCKMODE_SLAVE: 799 /* AutoSync */ 800 rme96->wcreg &= ~RME96_WCR_MASTER; 801 rme96->areg &= ~RME96_AR_WSEL; 802 break; 803 case RME96_CLOCKMODE_MASTER: 804 /* Internal */ 805 rme96->wcreg |= RME96_WCR_MASTER; 806 rme96->areg &= ~RME96_AR_WSEL; 807 break; 808 case RME96_CLOCKMODE_WORDCLOCK: 809 /* Word clock is a master mode */ 810 rme96->wcreg |= RME96_WCR_MASTER; 811 rme96->areg |= RME96_AR_WSEL; 812 break; 813 default: 814 return -EINVAL; 815 } 816 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 817 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 818 return 0; 819 } 820 821 static int 822 snd_rme96_getclockmode(struct rme96 *rme96) 823 { 824 if (rme96->areg & RME96_AR_WSEL) { 825 return RME96_CLOCKMODE_WORDCLOCK; 826 } 827 return (rme96->wcreg & RME96_WCR_MASTER) ? RME96_CLOCKMODE_MASTER : 828 RME96_CLOCKMODE_SLAVE; 829 } 830 831 static int 832 snd_rme96_setinputtype(struct rme96 *rme96, 833 int type) 834 { 835 int n; 836 837 switch (type) { 838 case RME96_INPUT_OPTICAL: 839 rme96->wcreg = (rme96->wcreg & ~RME96_WCR_INP_0) & 840 ~RME96_WCR_INP_1; 841 break; 842 case RME96_INPUT_COAXIAL: 843 rme96->wcreg = (rme96->wcreg | RME96_WCR_INP_0) & 844 ~RME96_WCR_INP_1; 845 break; 846 case RME96_INPUT_INTERNAL: 847 rme96->wcreg = (rme96->wcreg & ~RME96_WCR_INP_0) | 848 RME96_WCR_INP_1; 849 break; 850 case RME96_INPUT_XLR: 851 if ((rme96->pci->device != PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST && 852 rme96->pci->device != PCI_DEVICE_ID_RME_DIGI96_8_PRO) || 853 (rme96->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST && 854 rme96->rev > 4)) 855 { 856 /* Only Digi96/8 PRO and Digi96/8 PAD supports XLR */ 857 return -EINVAL; 858 } 859 rme96->wcreg = (rme96->wcreg | RME96_WCR_INP_0) | 860 RME96_WCR_INP_1; 861 break; 862 case RME96_INPUT_ANALOG: 863 if (!RME96_HAS_ANALOG_IN(rme96)) { 864 return -EINVAL; 865 } 866 rme96->areg |= RME96_AR_ANALOG; 867 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 868 if (rme96->rev < 4) { 869 /* 870 * Revision less than 004 does not support 64 and 871 * 88.2 kHz 872 */ 873 if (snd_rme96_capture_getrate(rme96, &n) == 88200) { 874 snd_rme96_capture_analog_setrate(rme96, 44100); 875 } 876 if (snd_rme96_capture_getrate(rme96, &n) == 64000) { 877 snd_rme96_capture_analog_setrate(rme96, 32000); 878 } 879 } 880 return 0; 881 default: 882 return -EINVAL; 883 } 884 if (type != RME96_INPUT_ANALOG && RME96_HAS_ANALOG_IN(rme96)) { 885 rme96->areg &= ~RME96_AR_ANALOG; 886 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 887 } 888 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 889 return 0; 890 } 891 892 static int 893 snd_rme96_getinputtype(struct rme96 *rme96) 894 { 895 if (rme96->areg & RME96_AR_ANALOG) { 896 return RME96_INPUT_ANALOG; 897 } 898 return ((rme96->wcreg >> RME96_WCR_BITPOS_INP_0) & 1) + 899 (((rme96->wcreg >> RME96_WCR_BITPOS_INP_1) & 1) << 1); 900 } 901 902 static void 903 snd_rme96_setframelog(struct rme96 *rme96, 904 int n_channels, 905 int is_playback) 906 { 907 int frlog; 908 909 if (n_channels == 2) { 910 frlog = 1; 911 } else { 912 /* assume 8 channels */ 913 frlog = 3; 914 } 915 if (is_playback) { 916 frlog += (rme96->wcreg & RME96_WCR_MODE24) ? 2 : 1; 917 rme96->playback_frlog = frlog; 918 } else { 919 frlog += (rme96->wcreg & RME96_WCR_MODE24_2) ? 2 : 1; 920 rme96->capture_frlog = frlog; 921 } 922 } 923 924 static int 925 snd_rme96_playback_setformat(struct rme96 *rme96, snd_pcm_format_t format) 926 { 927 switch (format) { 928 case SNDRV_PCM_FORMAT_S16_LE: 929 rme96->wcreg &= ~RME96_WCR_MODE24; 930 break; 931 case SNDRV_PCM_FORMAT_S32_LE: 932 rme96->wcreg |= RME96_WCR_MODE24; 933 break; 934 default: 935 return -EINVAL; 936 } 937 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 938 return 0; 939 } 940 941 static int 942 snd_rme96_capture_setformat(struct rme96 *rme96, snd_pcm_format_t format) 943 { 944 switch (format) { 945 case SNDRV_PCM_FORMAT_S16_LE: 946 rme96->wcreg &= ~RME96_WCR_MODE24_2; 947 break; 948 case SNDRV_PCM_FORMAT_S32_LE: 949 rme96->wcreg |= RME96_WCR_MODE24_2; 950 break; 951 default: 952 return -EINVAL; 953 } 954 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 955 return 0; 956 } 957 958 static void 959 snd_rme96_set_period_properties(struct rme96 *rme96, 960 size_t period_bytes) 961 { 962 switch (period_bytes) { 963 case RME96_LARGE_BLOCK_SIZE: 964 rme96->wcreg &= ~RME96_WCR_ISEL; 965 break; 966 case RME96_SMALL_BLOCK_SIZE: 967 rme96->wcreg |= RME96_WCR_ISEL; 968 break; 969 default: 970 snd_BUG(); 971 break; 972 } 973 rme96->wcreg &= ~RME96_WCR_IDIS; 974 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 975 } 976 977 static int 978 snd_rme96_playback_hw_params(struct snd_pcm_substream *substream, 979 struct snd_pcm_hw_params *params) 980 { 981 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 982 struct snd_pcm_runtime *runtime = substream->runtime; 983 int err, rate, dummy; 984 bool apply_dac_volume = false; 985 986 runtime->dma_area = (void __force *)(rme96->iobase + 987 RME96_IO_PLAY_BUFFER); 988 runtime->dma_addr = rme96->port + RME96_IO_PLAY_BUFFER; 989 runtime->dma_bytes = RME96_BUFFER_SIZE; 990 991 spin_lock_irq(&rme96->lock); 992 if (!(rme96->wcreg & RME96_WCR_MASTER) && 993 snd_rme96_getinputtype(rme96) != RME96_INPUT_ANALOG && 994 (rate = snd_rme96_capture_getrate(rme96, &dummy)) > 0) 995 { 996 /* slave clock */ 997 if ((int)params_rate(params) != rate) { 998 err = -EIO; 999 goto error; 1000 } 1001 } else { 1002 err = snd_rme96_playback_setrate(rme96, params_rate(params)); 1003 if (err < 0) 1004 goto error; 1005 apply_dac_volume = err > 0; /* need to restore volume later? */ 1006 } 1007 1008 err = snd_rme96_playback_setformat(rme96, params_format(params)); 1009 if (err < 0) 1010 goto error; 1011 snd_rme96_setframelog(rme96, params_channels(params), 1); 1012 if (rme96->capture_periodsize != 0) { 1013 if (params_period_size(params) << rme96->playback_frlog != 1014 rme96->capture_periodsize) 1015 { 1016 err = -EBUSY; 1017 goto error; 1018 } 1019 } 1020 rme96->playback_periodsize = 1021 params_period_size(params) << rme96->playback_frlog; 1022 snd_rme96_set_period_properties(rme96, rme96->playback_periodsize); 1023 /* S/PDIF setup */ 1024 if ((rme96->wcreg & RME96_WCR_ADAT) == 0) { 1025 rme96->wcreg &= ~(RME96_WCR_PRO | RME96_WCR_DOLBY | RME96_WCR_EMP); 1026 writel(rme96->wcreg |= rme96->wcreg_spdif_stream, rme96->iobase + RME96_IO_CONTROL_REGISTER); 1027 } 1028 1029 err = 0; 1030 error: 1031 spin_unlock_irq(&rme96->lock); 1032 if (apply_dac_volume) { 1033 usleep_range(3000, 10000); 1034 snd_rme96_apply_dac_volume(rme96); 1035 } 1036 1037 return err; 1038 } 1039 1040 static int 1041 snd_rme96_capture_hw_params(struct snd_pcm_substream *substream, 1042 struct snd_pcm_hw_params *params) 1043 { 1044 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1045 struct snd_pcm_runtime *runtime = substream->runtime; 1046 int err, isadat, rate; 1047 1048 runtime->dma_area = (void __force *)(rme96->iobase + 1049 RME96_IO_REC_BUFFER); 1050 runtime->dma_addr = rme96->port + RME96_IO_REC_BUFFER; 1051 runtime->dma_bytes = RME96_BUFFER_SIZE; 1052 1053 spin_lock_irq(&rme96->lock); 1054 if ((err = snd_rme96_capture_setformat(rme96, params_format(params))) < 0) { 1055 spin_unlock_irq(&rme96->lock); 1056 return err; 1057 } 1058 if (snd_rme96_getinputtype(rme96) == RME96_INPUT_ANALOG) { 1059 if ((err = snd_rme96_capture_analog_setrate(rme96, 1060 params_rate(params))) < 0) 1061 { 1062 spin_unlock_irq(&rme96->lock); 1063 return err; 1064 } 1065 } else if ((rate = snd_rme96_capture_getrate(rme96, &isadat)) > 0) { 1066 if ((int)params_rate(params) != rate) { 1067 spin_unlock_irq(&rme96->lock); 1068 return -EIO; 1069 } 1070 if ((isadat && runtime->hw.channels_min == 2) || 1071 (!isadat && runtime->hw.channels_min == 8)) 1072 { 1073 spin_unlock_irq(&rme96->lock); 1074 return -EIO; 1075 } 1076 } 1077 snd_rme96_setframelog(rme96, params_channels(params), 0); 1078 if (rme96->playback_periodsize != 0) { 1079 if (params_period_size(params) << rme96->capture_frlog != 1080 rme96->playback_periodsize) 1081 { 1082 spin_unlock_irq(&rme96->lock); 1083 return -EBUSY; 1084 } 1085 } 1086 rme96->capture_periodsize = 1087 params_period_size(params) << rme96->capture_frlog; 1088 snd_rme96_set_period_properties(rme96, rme96->capture_periodsize); 1089 spin_unlock_irq(&rme96->lock); 1090 1091 return 0; 1092 } 1093 1094 static void 1095 snd_rme96_trigger(struct rme96 *rme96, 1096 int op) 1097 { 1098 if (op & RME96_TB_RESET_PLAYPOS) 1099 writel(0, rme96->iobase + RME96_IO_RESET_PLAY_POS); 1100 if (op & RME96_TB_RESET_CAPTUREPOS) 1101 writel(0, rme96->iobase + RME96_IO_RESET_REC_POS); 1102 if (op & RME96_TB_CLEAR_PLAYBACK_IRQ) { 1103 rme96->rcreg = readl(rme96->iobase + RME96_IO_CONTROL_REGISTER); 1104 if (rme96->rcreg & RME96_RCR_IRQ) 1105 writel(0, rme96->iobase + RME96_IO_CONFIRM_PLAY_IRQ); 1106 } 1107 if (op & RME96_TB_CLEAR_CAPTURE_IRQ) { 1108 rme96->rcreg = readl(rme96->iobase + RME96_IO_CONTROL_REGISTER); 1109 if (rme96->rcreg & RME96_RCR_IRQ_2) 1110 writel(0, rme96->iobase + RME96_IO_CONFIRM_REC_IRQ); 1111 } 1112 if (op & RME96_TB_START_PLAYBACK) 1113 rme96->wcreg |= RME96_WCR_START; 1114 if (op & RME96_TB_STOP_PLAYBACK) 1115 rme96->wcreg &= ~RME96_WCR_START; 1116 if (op & RME96_TB_START_CAPTURE) 1117 rme96->wcreg |= RME96_WCR_START_2; 1118 if (op & RME96_TB_STOP_CAPTURE) 1119 rme96->wcreg &= ~RME96_WCR_START_2; 1120 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 1121 } 1122 1123 1124 1125 static irqreturn_t 1126 snd_rme96_interrupt(int irq, 1127 void *dev_id) 1128 { 1129 struct rme96 *rme96 = (struct rme96 *)dev_id; 1130 1131 rme96->rcreg = readl(rme96->iobase + RME96_IO_CONTROL_REGISTER); 1132 /* fastpath out, to ease interrupt sharing */ 1133 if (!((rme96->rcreg & RME96_RCR_IRQ) || 1134 (rme96->rcreg & RME96_RCR_IRQ_2))) 1135 { 1136 return IRQ_NONE; 1137 } 1138 1139 if (rme96->rcreg & RME96_RCR_IRQ) { 1140 /* playback */ 1141 snd_pcm_period_elapsed(rme96->playback_substream); 1142 writel(0, rme96->iobase + RME96_IO_CONFIRM_PLAY_IRQ); 1143 } 1144 if (rme96->rcreg & RME96_RCR_IRQ_2) { 1145 /* capture */ 1146 snd_pcm_period_elapsed(rme96->capture_substream); 1147 writel(0, rme96->iobase + RME96_IO_CONFIRM_REC_IRQ); 1148 } 1149 return IRQ_HANDLED; 1150 } 1151 1152 static unsigned int period_bytes[] = { RME96_SMALL_BLOCK_SIZE, RME96_LARGE_BLOCK_SIZE }; 1153 1154 static struct snd_pcm_hw_constraint_list hw_constraints_period_bytes = { 1155 .count = ARRAY_SIZE(period_bytes), 1156 .list = period_bytes, 1157 .mask = 0 1158 }; 1159 1160 static void 1161 rme96_set_buffer_size_constraint(struct rme96 *rme96, 1162 struct snd_pcm_runtime *runtime) 1163 { 1164 unsigned int size; 1165 1166 snd_pcm_hw_constraint_single(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 1167 RME96_BUFFER_SIZE); 1168 if ((size = rme96->playback_periodsize) != 0 || 1169 (size = rme96->capture_periodsize) != 0) 1170 snd_pcm_hw_constraint_single(runtime, 1171 SNDRV_PCM_HW_PARAM_PERIOD_BYTES, 1172 size); 1173 else 1174 snd_pcm_hw_constraint_list(runtime, 0, 1175 SNDRV_PCM_HW_PARAM_PERIOD_BYTES, 1176 &hw_constraints_period_bytes); 1177 } 1178 1179 static int 1180 snd_rme96_playback_spdif_open(struct snd_pcm_substream *substream) 1181 { 1182 int rate, dummy; 1183 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1184 struct snd_pcm_runtime *runtime = substream->runtime; 1185 1186 snd_pcm_set_sync(substream); 1187 spin_lock_irq(&rme96->lock); 1188 if (rme96->playback_substream != NULL) { 1189 spin_unlock_irq(&rme96->lock); 1190 return -EBUSY; 1191 } 1192 rme96->wcreg &= ~RME96_WCR_ADAT; 1193 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 1194 rme96->playback_substream = substream; 1195 spin_unlock_irq(&rme96->lock); 1196 1197 runtime->hw = snd_rme96_playback_spdif_info; 1198 if (!(rme96->wcreg & RME96_WCR_MASTER) && 1199 snd_rme96_getinputtype(rme96) != RME96_INPUT_ANALOG && 1200 (rate = snd_rme96_capture_getrate(rme96, &dummy)) > 0) 1201 { 1202 /* slave clock */ 1203 runtime->hw.rates = snd_pcm_rate_to_rate_bit(rate); 1204 runtime->hw.rate_min = rate; 1205 runtime->hw.rate_max = rate; 1206 } 1207 rme96_set_buffer_size_constraint(rme96, runtime); 1208 1209 rme96->wcreg_spdif_stream = rme96->wcreg_spdif; 1210 rme96->spdif_ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE; 1211 snd_ctl_notify(rme96->card, SNDRV_CTL_EVENT_MASK_VALUE | 1212 SNDRV_CTL_EVENT_MASK_INFO, &rme96->spdif_ctl->id); 1213 return 0; 1214 } 1215 1216 static int 1217 snd_rme96_capture_spdif_open(struct snd_pcm_substream *substream) 1218 { 1219 int isadat, rate; 1220 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1221 struct snd_pcm_runtime *runtime = substream->runtime; 1222 1223 snd_pcm_set_sync(substream); 1224 runtime->hw = snd_rme96_capture_spdif_info; 1225 if (snd_rme96_getinputtype(rme96) != RME96_INPUT_ANALOG && 1226 (rate = snd_rme96_capture_getrate(rme96, &isadat)) > 0) 1227 { 1228 if (isadat) { 1229 return -EIO; 1230 } 1231 runtime->hw.rates = snd_pcm_rate_to_rate_bit(rate); 1232 runtime->hw.rate_min = rate; 1233 runtime->hw.rate_max = rate; 1234 } 1235 1236 spin_lock_irq(&rme96->lock); 1237 if (rme96->capture_substream != NULL) { 1238 spin_unlock_irq(&rme96->lock); 1239 return -EBUSY; 1240 } 1241 rme96->capture_substream = substream; 1242 spin_unlock_irq(&rme96->lock); 1243 1244 rme96_set_buffer_size_constraint(rme96, runtime); 1245 return 0; 1246 } 1247 1248 static int 1249 snd_rme96_playback_adat_open(struct snd_pcm_substream *substream) 1250 { 1251 int rate, dummy; 1252 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1253 struct snd_pcm_runtime *runtime = substream->runtime; 1254 1255 snd_pcm_set_sync(substream); 1256 spin_lock_irq(&rme96->lock); 1257 if (rme96->playback_substream != NULL) { 1258 spin_unlock_irq(&rme96->lock); 1259 return -EBUSY; 1260 } 1261 rme96->wcreg |= RME96_WCR_ADAT; 1262 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 1263 rme96->playback_substream = substream; 1264 spin_unlock_irq(&rme96->lock); 1265 1266 runtime->hw = snd_rme96_playback_adat_info; 1267 if (!(rme96->wcreg & RME96_WCR_MASTER) && 1268 snd_rme96_getinputtype(rme96) != RME96_INPUT_ANALOG && 1269 (rate = snd_rme96_capture_getrate(rme96, &dummy)) > 0) 1270 { 1271 /* slave clock */ 1272 runtime->hw.rates = snd_pcm_rate_to_rate_bit(rate); 1273 runtime->hw.rate_min = rate; 1274 runtime->hw.rate_max = rate; 1275 } 1276 rme96_set_buffer_size_constraint(rme96, runtime); 1277 return 0; 1278 } 1279 1280 static int 1281 snd_rme96_capture_adat_open(struct snd_pcm_substream *substream) 1282 { 1283 int isadat, rate; 1284 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1285 struct snd_pcm_runtime *runtime = substream->runtime; 1286 1287 snd_pcm_set_sync(substream); 1288 runtime->hw = snd_rme96_capture_adat_info; 1289 if (snd_rme96_getinputtype(rme96) == RME96_INPUT_ANALOG) { 1290 /* makes no sense to use analog input. Note that analog 1291 expension cards AEB4/8-I are RME96_INPUT_INTERNAL */ 1292 return -EIO; 1293 } 1294 if ((rate = snd_rme96_capture_getrate(rme96, &isadat)) > 0) { 1295 if (!isadat) { 1296 return -EIO; 1297 } 1298 runtime->hw.rates = snd_pcm_rate_to_rate_bit(rate); 1299 runtime->hw.rate_min = rate; 1300 runtime->hw.rate_max = rate; 1301 } 1302 1303 spin_lock_irq(&rme96->lock); 1304 if (rme96->capture_substream != NULL) { 1305 spin_unlock_irq(&rme96->lock); 1306 return -EBUSY; 1307 } 1308 rme96->capture_substream = substream; 1309 spin_unlock_irq(&rme96->lock); 1310 1311 rme96_set_buffer_size_constraint(rme96, runtime); 1312 return 0; 1313 } 1314 1315 static int 1316 snd_rme96_playback_close(struct snd_pcm_substream *substream) 1317 { 1318 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1319 int spdif = 0; 1320 1321 spin_lock_irq(&rme96->lock); 1322 if (RME96_ISPLAYING(rme96)) { 1323 snd_rme96_trigger(rme96, RME96_STOP_PLAYBACK); 1324 } 1325 rme96->playback_substream = NULL; 1326 rme96->playback_periodsize = 0; 1327 spdif = (rme96->wcreg & RME96_WCR_ADAT) == 0; 1328 spin_unlock_irq(&rme96->lock); 1329 if (spdif) { 1330 rme96->spdif_ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE; 1331 snd_ctl_notify(rme96->card, SNDRV_CTL_EVENT_MASK_VALUE | 1332 SNDRV_CTL_EVENT_MASK_INFO, &rme96->spdif_ctl->id); 1333 } 1334 return 0; 1335 } 1336 1337 static int 1338 snd_rme96_capture_close(struct snd_pcm_substream *substream) 1339 { 1340 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1341 1342 spin_lock_irq(&rme96->lock); 1343 if (RME96_ISRECORDING(rme96)) { 1344 snd_rme96_trigger(rme96, RME96_STOP_CAPTURE); 1345 } 1346 rme96->capture_substream = NULL; 1347 rme96->capture_periodsize = 0; 1348 spin_unlock_irq(&rme96->lock); 1349 return 0; 1350 } 1351 1352 static int 1353 snd_rme96_playback_prepare(struct snd_pcm_substream *substream) 1354 { 1355 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1356 1357 spin_lock_irq(&rme96->lock); 1358 if (RME96_ISPLAYING(rme96)) { 1359 snd_rme96_trigger(rme96, RME96_STOP_PLAYBACK); 1360 } 1361 writel(0, rme96->iobase + RME96_IO_RESET_PLAY_POS); 1362 spin_unlock_irq(&rme96->lock); 1363 return 0; 1364 } 1365 1366 static int 1367 snd_rme96_capture_prepare(struct snd_pcm_substream *substream) 1368 { 1369 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1370 1371 spin_lock_irq(&rme96->lock); 1372 if (RME96_ISRECORDING(rme96)) { 1373 snd_rme96_trigger(rme96, RME96_STOP_CAPTURE); 1374 } 1375 writel(0, rme96->iobase + RME96_IO_RESET_REC_POS); 1376 spin_unlock_irq(&rme96->lock); 1377 return 0; 1378 } 1379 1380 static int 1381 snd_rme96_playback_trigger(struct snd_pcm_substream *substream, 1382 int cmd) 1383 { 1384 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1385 struct snd_pcm_substream *s; 1386 bool sync; 1387 1388 snd_pcm_group_for_each_entry(s, substream) { 1389 if (snd_pcm_substream_chip(s) == rme96) 1390 snd_pcm_trigger_done(s, substream); 1391 } 1392 1393 sync = (rme96->playback_substream && rme96->capture_substream) && 1394 (rme96->playback_substream->group == 1395 rme96->capture_substream->group); 1396 1397 switch (cmd) { 1398 case SNDRV_PCM_TRIGGER_START: 1399 if (!RME96_ISPLAYING(rme96)) { 1400 if (substream != rme96->playback_substream) 1401 return -EBUSY; 1402 snd_rme96_trigger(rme96, sync ? RME96_START_BOTH 1403 : RME96_START_PLAYBACK); 1404 } 1405 break; 1406 1407 case SNDRV_PCM_TRIGGER_SUSPEND: 1408 case SNDRV_PCM_TRIGGER_STOP: 1409 if (RME96_ISPLAYING(rme96)) { 1410 if (substream != rme96->playback_substream) 1411 return -EBUSY; 1412 snd_rme96_trigger(rme96, sync ? RME96_STOP_BOTH 1413 : RME96_STOP_PLAYBACK); 1414 } 1415 break; 1416 1417 case SNDRV_PCM_TRIGGER_PAUSE_PUSH: 1418 if (RME96_ISPLAYING(rme96)) 1419 snd_rme96_trigger(rme96, sync ? RME96_STOP_BOTH 1420 : RME96_STOP_PLAYBACK); 1421 break; 1422 1423 case SNDRV_PCM_TRIGGER_RESUME: 1424 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: 1425 if (!RME96_ISPLAYING(rme96)) 1426 snd_rme96_trigger(rme96, sync ? RME96_RESUME_BOTH 1427 : RME96_RESUME_PLAYBACK); 1428 break; 1429 1430 default: 1431 return -EINVAL; 1432 } 1433 1434 return 0; 1435 } 1436 1437 static int 1438 snd_rme96_capture_trigger(struct snd_pcm_substream *substream, 1439 int cmd) 1440 { 1441 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1442 struct snd_pcm_substream *s; 1443 bool sync; 1444 1445 snd_pcm_group_for_each_entry(s, substream) { 1446 if (snd_pcm_substream_chip(s) == rme96) 1447 snd_pcm_trigger_done(s, substream); 1448 } 1449 1450 sync = (rme96->playback_substream && rme96->capture_substream) && 1451 (rme96->playback_substream->group == 1452 rme96->capture_substream->group); 1453 1454 switch (cmd) { 1455 case SNDRV_PCM_TRIGGER_START: 1456 if (!RME96_ISRECORDING(rme96)) { 1457 if (substream != rme96->capture_substream) 1458 return -EBUSY; 1459 snd_rme96_trigger(rme96, sync ? RME96_START_BOTH 1460 : RME96_START_CAPTURE); 1461 } 1462 break; 1463 1464 case SNDRV_PCM_TRIGGER_SUSPEND: 1465 case SNDRV_PCM_TRIGGER_STOP: 1466 if (RME96_ISRECORDING(rme96)) { 1467 if (substream != rme96->capture_substream) 1468 return -EBUSY; 1469 snd_rme96_trigger(rme96, sync ? RME96_STOP_BOTH 1470 : RME96_STOP_CAPTURE); 1471 } 1472 break; 1473 1474 case SNDRV_PCM_TRIGGER_PAUSE_PUSH: 1475 if (RME96_ISRECORDING(rme96)) 1476 snd_rme96_trigger(rme96, sync ? RME96_STOP_BOTH 1477 : RME96_STOP_CAPTURE); 1478 break; 1479 1480 case SNDRV_PCM_TRIGGER_RESUME: 1481 case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: 1482 if (!RME96_ISRECORDING(rme96)) 1483 snd_rme96_trigger(rme96, sync ? RME96_RESUME_BOTH 1484 : RME96_RESUME_CAPTURE); 1485 break; 1486 1487 default: 1488 return -EINVAL; 1489 } 1490 1491 return 0; 1492 } 1493 1494 static snd_pcm_uframes_t 1495 snd_rme96_playback_pointer(struct snd_pcm_substream *substream) 1496 { 1497 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1498 return snd_rme96_playback_ptr(rme96); 1499 } 1500 1501 static snd_pcm_uframes_t 1502 snd_rme96_capture_pointer(struct snd_pcm_substream *substream) 1503 { 1504 struct rme96 *rme96 = snd_pcm_substream_chip(substream); 1505 return snd_rme96_capture_ptr(rme96); 1506 } 1507 1508 static struct snd_pcm_ops snd_rme96_playback_spdif_ops = { 1509 .open = snd_rme96_playback_spdif_open, 1510 .close = snd_rme96_playback_close, 1511 .ioctl = snd_pcm_lib_ioctl, 1512 .hw_params = snd_rme96_playback_hw_params, 1513 .prepare = snd_rme96_playback_prepare, 1514 .trigger = snd_rme96_playback_trigger, 1515 .pointer = snd_rme96_playback_pointer, 1516 .copy = snd_rme96_playback_copy, 1517 .silence = snd_rme96_playback_silence, 1518 .mmap = snd_pcm_lib_mmap_iomem, 1519 }; 1520 1521 static struct snd_pcm_ops snd_rme96_capture_spdif_ops = { 1522 .open = snd_rme96_capture_spdif_open, 1523 .close = snd_rme96_capture_close, 1524 .ioctl = snd_pcm_lib_ioctl, 1525 .hw_params = snd_rme96_capture_hw_params, 1526 .prepare = snd_rme96_capture_prepare, 1527 .trigger = snd_rme96_capture_trigger, 1528 .pointer = snd_rme96_capture_pointer, 1529 .copy = snd_rme96_capture_copy, 1530 .mmap = snd_pcm_lib_mmap_iomem, 1531 }; 1532 1533 static struct snd_pcm_ops snd_rme96_playback_adat_ops = { 1534 .open = snd_rme96_playback_adat_open, 1535 .close = snd_rme96_playback_close, 1536 .ioctl = snd_pcm_lib_ioctl, 1537 .hw_params = snd_rme96_playback_hw_params, 1538 .prepare = snd_rme96_playback_prepare, 1539 .trigger = snd_rme96_playback_trigger, 1540 .pointer = snd_rme96_playback_pointer, 1541 .copy = snd_rme96_playback_copy, 1542 .silence = snd_rme96_playback_silence, 1543 .mmap = snd_pcm_lib_mmap_iomem, 1544 }; 1545 1546 static struct snd_pcm_ops snd_rme96_capture_adat_ops = { 1547 .open = snd_rme96_capture_adat_open, 1548 .close = snd_rme96_capture_close, 1549 .ioctl = snd_pcm_lib_ioctl, 1550 .hw_params = snd_rme96_capture_hw_params, 1551 .prepare = snd_rme96_capture_prepare, 1552 .trigger = snd_rme96_capture_trigger, 1553 .pointer = snd_rme96_capture_pointer, 1554 .copy = snd_rme96_capture_copy, 1555 .mmap = snd_pcm_lib_mmap_iomem, 1556 }; 1557 1558 static void 1559 snd_rme96_free(void *private_data) 1560 { 1561 struct rme96 *rme96 = (struct rme96 *)private_data; 1562 1563 if (rme96 == NULL) { 1564 return; 1565 } 1566 if (rme96->irq >= 0) { 1567 snd_rme96_trigger(rme96, RME96_STOP_BOTH); 1568 rme96->areg &= ~RME96_AR_DAC_EN; 1569 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 1570 free_irq(rme96->irq, (void *)rme96); 1571 rme96->irq = -1; 1572 } 1573 if (rme96->iobase) { 1574 iounmap(rme96->iobase); 1575 rme96->iobase = NULL; 1576 } 1577 if (rme96->port) { 1578 pci_release_regions(rme96->pci); 1579 rme96->port = 0; 1580 } 1581 #ifdef CONFIG_PM_SLEEP 1582 vfree(rme96->playback_suspend_buffer); 1583 vfree(rme96->capture_suspend_buffer); 1584 #endif 1585 pci_disable_device(rme96->pci); 1586 } 1587 1588 static void 1589 snd_rme96_free_spdif_pcm(struct snd_pcm *pcm) 1590 { 1591 struct rme96 *rme96 = pcm->private_data; 1592 rme96->spdif_pcm = NULL; 1593 } 1594 1595 static void 1596 snd_rme96_free_adat_pcm(struct snd_pcm *pcm) 1597 { 1598 struct rme96 *rme96 = pcm->private_data; 1599 rme96->adat_pcm = NULL; 1600 } 1601 1602 static int 1603 snd_rme96_create(struct rme96 *rme96) 1604 { 1605 struct pci_dev *pci = rme96->pci; 1606 int err; 1607 1608 rme96->irq = -1; 1609 spin_lock_init(&rme96->lock); 1610 1611 if ((err = pci_enable_device(pci)) < 0) 1612 return err; 1613 1614 if ((err = pci_request_regions(pci, "RME96")) < 0) 1615 return err; 1616 rme96->port = pci_resource_start(rme96->pci, 0); 1617 1618 rme96->iobase = ioremap_nocache(rme96->port, RME96_IO_SIZE); 1619 if (!rme96->iobase) { 1620 dev_err(rme96->card->dev, 1621 "unable to remap memory region 0x%lx-0x%lx\n", 1622 rme96->port, rme96->port + RME96_IO_SIZE - 1); 1623 return -ENOMEM; 1624 } 1625 1626 if (request_irq(pci->irq, snd_rme96_interrupt, IRQF_SHARED, 1627 KBUILD_MODNAME, rme96)) { 1628 dev_err(rme96->card->dev, "unable to grab IRQ %d\n", pci->irq); 1629 return -EBUSY; 1630 } 1631 rme96->irq = pci->irq; 1632 1633 /* read the card's revision number */ 1634 pci_read_config_byte(pci, 8, &rme96->rev); 1635 1636 /* set up ALSA pcm device for S/PDIF */ 1637 if ((err = snd_pcm_new(rme96->card, "Digi96 IEC958", 0, 1638 1, 1, &rme96->spdif_pcm)) < 0) 1639 { 1640 return err; 1641 } 1642 rme96->spdif_pcm->private_data = rme96; 1643 rme96->spdif_pcm->private_free = snd_rme96_free_spdif_pcm; 1644 strcpy(rme96->spdif_pcm->name, "Digi96 IEC958"); 1645 snd_pcm_set_ops(rme96->spdif_pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_rme96_playback_spdif_ops); 1646 snd_pcm_set_ops(rme96->spdif_pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_rme96_capture_spdif_ops); 1647 1648 rme96->spdif_pcm->info_flags = 0; 1649 1650 /* set up ALSA pcm device for ADAT */ 1651 if (pci->device == PCI_DEVICE_ID_RME_DIGI96) { 1652 /* ADAT is not available on the base model */ 1653 rme96->adat_pcm = NULL; 1654 } else { 1655 if ((err = snd_pcm_new(rme96->card, "Digi96 ADAT", 1, 1656 1, 1, &rme96->adat_pcm)) < 0) 1657 { 1658 return err; 1659 } 1660 rme96->adat_pcm->private_data = rme96; 1661 rme96->adat_pcm->private_free = snd_rme96_free_adat_pcm; 1662 strcpy(rme96->adat_pcm->name, "Digi96 ADAT"); 1663 snd_pcm_set_ops(rme96->adat_pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_rme96_playback_adat_ops); 1664 snd_pcm_set_ops(rme96->adat_pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_rme96_capture_adat_ops); 1665 1666 rme96->adat_pcm->info_flags = 0; 1667 } 1668 1669 rme96->playback_periodsize = 0; 1670 rme96->capture_periodsize = 0; 1671 1672 /* make sure playback/capture is stopped, if by some reason active */ 1673 snd_rme96_trigger(rme96, RME96_STOP_BOTH); 1674 1675 /* set default values in registers */ 1676 rme96->wcreg = 1677 RME96_WCR_FREQ_1 | /* set 44.1 kHz playback */ 1678 RME96_WCR_SEL | /* normal playback */ 1679 RME96_WCR_MASTER | /* set to master clock mode */ 1680 RME96_WCR_INP_0; /* set coaxial input */ 1681 1682 rme96->areg = RME96_AR_FREQPAD_1; /* set 44.1 kHz analog capture */ 1683 1684 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 1685 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 1686 1687 /* reset the ADC */ 1688 writel(rme96->areg | RME96_AR_PD2, 1689 rme96->iobase + RME96_IO_ADDITIONAL_REG); 1690 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 1691 1692 /* reset and enable the DAC (order is important). */ 1693 snd_rme96_reset_dac(rme96); 1694 rme96->areg |= RME96_AR_DAC_EN; 1695 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 1696 1697 /* reset playback and record buffer pointers */ 1698 writel(0, rme96->iobase + RME96_IO_RESET_PLAY_POS); 1699 writel(0, rme96->iobase + RME96_IO_RESET_REC_POS); 1700 1701 /* reset volume */ 1702 rme96->vol[0] = rme96->vol[1] = 0; 1703 if (RME96_HAS_ANALOG_OUT(rme96)) { 1704 snd_rme96_apply_dac_volume(rme96); 1705 } 1706 1707 /* init switch interface */ 1708 if ((err = snd_rme96_create_switches(rme96->card, rme96)) < 0) { 1709 return err; 1710 } 1711 1712 /* init proc interface */ 1713 snd_rme96_proc_init(rme96); 1714 1715 return 0; 1716 } 1717 1718 /* 1719 * proc interface 1720 */ 1721 1722 static void 1723 snd_rme96_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) 1724 { 1725 int n; 1726 struct rme96 *rme96 = entry->private_data; 1727 1728 rme96->rcreg = readl(rme96->iobase + RME96_IO_CONTROL_REGISTER); 1729 1730 snd_iprintf(buffer, rme96->card->longname); 1731 snd_iprintf(buffer, " (index #%d)\n", rme96->card->number + 1); 1732 1733 snd_iprintf(buffer, "\nGeneral settings\n"); 1734 if (rme96->wcreg & RME96_WCR_IDIS) { 1735 snd_iprintf(buffer, " period size: N/A (interrupts " 1736 "disabled)\n"); 1737 } else if (rme96->wcreg & RME96_WCR_ISEL) { 1738 snd_iprintf(buffer, " period size: 2048 bytes\n"); 1739 } else { 1740 snd_iprintf(buffer, " period size: 8192 bytes\n"); 1741 } 1742 snd_iprintf(buffer, "\nInput settings\n"); 1743 switch (snd_rme96_getinputtype(rme96)) { 1744 case RME96_INPUT_OPTICAL: 1745 snd_iprintf(buffer, " input: optical"); 1746 break; 1747 case RME96_INPUT_COAXIAL: 1748 snd_iprintf(buffer, " input: coaxial"); 1749 break; 1750 case RME96_INPUT_INTERNAL: 1751 snd_iprintf(buffer, " input: internal"); 1752 break; 1753 case RME96_INPUT_XLR: 1754 snd_iprintf(buffer, " input: XLR"); 1755 break; 1756 case RME96_INPUT_ANALOG: 1757 snd_iprintf(buffer, " input: analog"); 1758 break; 1759 } 1760 if (snd_rme96_capture_getrate(rme96, &n) < 0) { 1761 snd_iprintf(buffer, "\n sample rate: no valid signal\n"); 1762 } else { 1763 if (n) { 1764 snd_iprintf(buffer, " (8 channels)\n"); 1765 } else { 1766 snd_iprintf(buffer, " (2 channels)\n"); 1767 } 1768 snd_iprintf(buffer, " sample rate: %d Hz\n", 1769 snd_rme96_capture_getrate(rme96, &n)); 1770 } 1771 if (rme96->wcreg & RME96_WCR_MODE24_2) { 1772 snd_iprintf(buffer, " sample format: 24 bit\n"); 1773 } else { 1774 snd_iprintf(buffer, " sample format: 16 bit\n"); 1775 } 1776 1777 snd_iprintf(buffer, "\nOutput settings\n"); 1778 if (rme96->wcreg & RME96_WCR_SEL) { 1779 snd_iprintf(buffer, " output signal: normal playback\n"); 1780 } else { 1781 snd_iprintf(buffer, " output signal: same as input\n"); 1782 } 1783 snd_iprintf(buffer, " sample rate: %d Hz\n", 1784 snd_rme96_playback_getrate(rme96)); 1785 if (rme96->wcreg & RME96_WCR_MODE24) { 1786 snd_iprintf(buffer, " sample format: 24 bit\n"); 1787 } else { 1788 snd_iprintf(buffer, " sample format: 16 bit\n"); 1789 } 1790 if (rme96->areg & RME96_AR_WSEL) { 1791 snd_iprintf(buffer, " sample clock source: word clock\n"); 1792 } else if (rme96->wcreg & RME96_WCR_MASTER) { 1793 snd_iprintf(buffer, " sample clock source: internal\n"); 1794 } else if (snd_rme96_getinputtype(rme96) == RME96_INPUT_ANALOG) { 1795 snd_iprintf(buffer, " sample clock source: autosync (internal anyway due to analog input setting)\n"); 1796 } else if (snd_rme96_capture_getrate(rme96, &n) < 0) { 1797 snd_iprintf(buffer, " sample clock source: autosync (internal anyway due to no valid signal)\n"); 1798 } else { 1799 snd_iprintf(buffer, " sample clock source: autosync\n"); 1800 } 1801 if (rme96->wcreg & RME96_WCR_PRO) { 1802 snd_iprintf(buffer, " format: AES/EBU (professional)\n"); 1803 } else { 1804 snd_iprintf(buffer, " format: IEC958 (consumer)\n"); 1805 } 1806 if (rme96->wcreg & RME96_WCR_EMP) { 1807 snd_iprintf(buffer, " emphasis: on\n"); 1808 } else { 1809 snd_iprintf(buffer, " emphasis: off\n"); 1810 } 1811 if (rme96->wcreg & RME96_WCR_DOLBY) { 1812 snd_iprintf(buffer, " non-audio (dolby): on\n"); 1813 } else { 1814 snd_iprintf(buffer, " non-audio (dolby): off\n"); 1815 } 1816 if (RME96_HAS_ANALOG_IN(rme96)) { 1817 snd_iprintf(buffer, "\nAnalog output settings\n"); 1818 switch (snd_rme96_getmontracks(rme96)) { 1819 case RME96_MONITOR_TRACKS_1_2: 1820 snd_iprintf(buffer, " monitored ADAT tracks: 1+2\n"); 1821 break; 1822 case RME96_MONITOR_TRACKS_3_4: 1823 snd_iprintf(buffer, " monitored ADAT tracks: 3+4\n"); 1824 break; 1825 case RME96_MONITOR_TRACKS_5_6: 1826 snd_iprintf(buffer, " monitored ADAT tracks: 5+6\n"); 1827 break; 1828 case RME96_MONITOR_TRACKS_7_8: 1829 snd_iprintf(buffer, " monitored ADAT tracks: 7+8\n"); 1830 break; 1831 } 1832 switch (snd_rme96_getattenuation(rme96)) { 1833 case RME96_ATTENUATION_0: 1834 snd_iprintf(buffer, " attenuation: 0 dB\n"); 1835 break; 1836 case RME96_ATTENUATION_6: 1837 snd_iprintf(buffer, " attenuation: -6 dB\n"); 1838 break; 1839 case RME96_ATTENUATION_12: 1840 snd_iprintf(buffer, " attenuation: -12 dB\n"); 1841 break; 1842 case RME96_ATTENUATION_18: 1843 snd_iprintf(buffer, " attenuation: -18 dB\n"); 1844 break; 1845 } 1846 snd_iprintf(buffer, " volume left: %u\n", rme96->vol[0]); 1847 snd_iprintf(buffer, " volume right: %u\n", rme96->vol[1]); 1848 } 1849 } 1850 1851 static void snd_rme96_proc_init(struct rme96 *rme96) 1852 { 1853 struct snd_info_entry *entry; 1854 1855 if (! snd_card_proc_new(rme96->card, "rme96", &entry)) 1856 snd_info_set_text_ops(entry, rme96, snd_rme96_proc_read); 1857 } 1858 1859 /* 1860 * control interface 1861 */ 1862 1863 #define snd_rme96_info_loopback_control snd_ctl_boolean_mono_info 1864 1865 static int 1866 snd_rme96_get_loopback_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 1867 { 1868 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 1869 1870 spin_lock_irq(&rme96->lock); 1871 ucontrol->value.integer.value[0] = rme96->wcreg & RME96_WCR_SEL ? 0 : 1; 1872 spin_unlock_irq(&rme96->lock); 1873 return 0; 1874 } 1875 static int 1876 snd_rme96_put_loopback_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 1877 { 1878 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 1879 unsigned int val; 1880 int change; 1881 1882 val = ucontrol->value.integer.value[0] ? 0 : RME96_WCR_SEL; 1883 spin_lock_irq(&rme96->lock); 1884 val = (rme96->wcreg & ~RME96_WCR_SEL) | val; 1885 change = val != rme96->wcreg; 1886 rme96->wcreg = val; 1887 writel(val, rme96->iobase + RME96_IO_CONTROL_REGISTER); 1888 spin_unlock_irq(&rme96->lock); 1889 return change; 1890 } 1891 1892 static int 1893 snd_rme96_info_inputtype_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 1894 { 1895 static const char * const _texts[5] = { 1896 "Optical", "Coaxial", "Internal", "XLR", "Analog" 1897 }; 1898 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 1899 const char *texts[5] = { 1900 _texts[0], _texts[1], _texts[2], _texts[3], _texts[4] 1901 }; 1902 int num_items; 1903 1904 switch (rme96->pci->device) { 1905 case PCI_DEVICE_ID_RME_DIGI96: 1906 case PCI_DEVICE_ID_RME_DIGI96_8: 1907 num_items = 3; 1908 break; 1909 case PCI_DEVICE_ID_RME_DIGI96_8_PRO: 1910 num_items = 4; 1911 break; 1912 case PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST: 1913 if (rme96->rev > 4) { 1914 /* PST */ 1915 num_items = 4; 1916 texts[3] = _texts[4]; /* Analog instead of XLR */ 1917 } else { 1918 /* PAD */ 1919 num_items = 5; 1920 } 1921 break; 1922 default: 1923 snd_BUG(); 1924 return -EINVAL; 1925 } 1926 return snd_ctl_enum_info(uinfo, 1, num_items, texts); 1927 } 1928 static int 1929 snd_rme96_get_inputtype_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 1930 { 1931 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 1932 unsigned int items = 3; 1933 1934 spin_lock_irq(&rme96->lock); 1935 ucontrol->value.enumerated.item[0] = snd_rme96_getinputtype(rme96); 1936 1937 switch (rme96->pci->device) { 1938 case PCI_DEVICE_ID_RME_DIGI96: 1939 case PCI_DEVICE_ID_RME_DIGI96_8: 1940 items = 3; 1941 break; 1942 case PCI_DEVICE_ID_RME_DIGI96_8_PRO: 1943 items = 4; 1944 break; 1945 case PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST: 1946 if (rme96->rev > 4) { 1947 /* for handling PST case, (INPUT_ANALOG is moved to INPUT_XLR */ 1948 if (ucontrol->value.enumerated.item[0] == RME96_INPUT_ANALOG) { 1949 ucontrol->value.enumerated.item[0] = RME96_INPUT_XLR; 1950 } 1951 items = 4; 1952 } else { 1953 items = 5; 1954 } 1955 break; 1956 default: 1957 snd_BUG(); 1958 break; 1959 } 1960 if (ucontrol->value.enumerated.item[0] >= items) { 1961 ucontrol->value.enumerated.item[0] = items - 1; 1962 } 1963 1964 spin_unlock_irq(&rme96->lock); 1965 return 0; 1966 } 1967 static int 1968 snd_rme96_put_inputtype_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 1969 { 1970 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 1971 unsigned int val; 1972 int change, items = 3; 1973 1974 switch (rme96->pci->device) { 1975 case PCI_DEVICE_ID_RME_DIGI96: 1976 case PCI_DEVICE_ID_RME_DIGI96_8: 1977 items = 3; 1978 break; 1979 case PCI_DEVICE_ID_RME_DIGI96_8_PRO: 1980 items = 4; 1981 break; 1982 case PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST: 1983 if (rme96->rev > 4) { 1984 items = 4; 1985 } else { 1986 items = 5; 1987 } 1988 break; 1989 default: 1990 snd_BUG(); 1991 break; 1992 } 1993 val = ucontrol->value.enumerated.item[0] % items; 1994 1995 /* special case for PST */ 1996 if (rme96->pci->device == PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST && rme96->rev > 4) { 1997 if (val == RME96_INPUT_XLR) { 1998 val = RME96_INPUT_ANALOG; 1999 } 2000 } 2001 2002 spin_lock_irq(&rme96->lock); 2003 change = (int)val != snd_rme96_getinputtype(rme96); 2004 snd_rme96_setinputtype(rme96, val); 2005 spin_unlock_irq(&rme96->lock); 2006 return change; 2007 } 2008 2009 static int 2010 snd_rme96_info_clockmode_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2011 { 2012 static const char * const texts[3] = { "AutoSync", "Internal", "Word" }; 2013 2014 return snd_ctl_enum_info(uinfo, 1, 3, texts); 2015 } 2016 static int 2017 snd_rme96_get_clockmode_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2018 { 2019 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2020 2021 spin_lock_irq(&rme96->lock); 2022 ucontrol->value.enumerated.item[0] = snd_rme96_getclockmode(rme96); 2023 spin_unlock_irq(&rme96->lock); 2024 return 0; 2025 } 2026 static int 2027 snd_rme96_put_clockmode_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2028 { 2029 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2030 unsigned int val; 2031 int change; 2032 2033 val = ucontrol->value.enumerated.item[0] % 3; 2034 spin_lock_irq(&rme96->lock); 2035 change = (int)val != snd_rme96_getclockmode(rme96); 2036 snd_rme96_setclockmode(rme96, val); 2037 spin_unlock_irq(&rme96->lock); 2038 return change; 2039 } 2040 2041 static int 2042 snd_rme96_info_attenuation_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2043 { 2044 static const char * const texts[4] = { 2045 "0 dB", "-6 dB", "-12 dB", "-18 dB" 2046 }; 2047 2048 return snd_ctl_enum_info(uinfo, 1, 4, texts); 2049 } 2050 static int 2051 snd_rme96_get_attenuation_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2052 { 2053 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2054 2055 spin_lock_irq(&rme96->lock); 2056 ucontrol->value.enumerated.item[0] = snd_rme96_getattenuation(rme96); 2057 spin_unlock_irq(&rme96->lock); 2058 return 0; 2059 } 2060 static int 2061 snd_rme96_put_attenuation_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2062 { 2063 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2064 unsigned int val; 2065 int change; 2066 2067 val = ucontrol->value.enumerated.item[0] % 4; 2068 spin_lock_irq(&rme96->lock); 2069 2070 change = (int)val != snd_rme96_getattenuation(rme96); 2071 snd_rme96_setattenuation(rme96, val); 2072 spin_unlock_irq(&rme96->lock); 2073 return change; 2074 } 2075 2076 static int 2077 snd_rme96_info_montracks_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2078 { 2079 static const char * const texts[4] = { "1+2", "3+4", "5+6", "7+8" }; 2080 2081 return snd_ctl_enum_info(uinfo, 1, 4, texts); 2082 } 2083 static int 2084 snd_rme96_get_montracks_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2085 { 2086 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2087 2088 spin_lock_irq(&rme96->lock); 2089 ucontrol->value.enumerated.item[0] = snd_rme96_getmontracks(rme96); 2090 spin_unlock_irq(&rme96->lock); 2091 return 0; 2092 } 2093 static int 2094 snd_rme96_put_montracks_control(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2095 { 2096 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2097 unsigned int val; 2098 int change; 2099 2100 val = ucontrol->value.enumerated.item[0] % 4; 2101 spin_lock_irq(&rme96->lock); 2102 change = (int)val != snd_rme96_getmontracks(rme96); 2103 snd_rme96_setmontracks(rme96, val); 2104 spin_unlock_irq(&rme96->lock); 2105 return change; 2106 } 2107 2108 static u32 snd_rme96_convert_from_aes(struct snd_aes_iec958 *aes) 2109 { 2110 u32 val = 0; 2111 val |= (aes->status[0] & IEC958_AES0_PROFESSIONAL) ? RME96_WCR_PRO : 0; 2112 val |= (aes->status[0] & IEC958_AES0_NONAUDIO) ? RME96_WCR_DOLBY : 0; 2113 if (val & RME96_WCR_PRO) 2114 val |= (aes->status[0] & IEC958_AES0_PRO_EMPHASIS_5015) ? RME96_WCR_EMP : 0; 2115 else 2116 val |= (aes->status[0] & IEC958_AES0_CON_EMPHASIS_5015) ? RME96_WCR_EMP : 0; 2117 return val; 2118 } 2119 2120 static void snd_rme96_convert_to_aes(struct snd_aes_iec958 *aes, u32 val) 2121 { 2122 aes->status[0] = ((val & RME96_WCR_PRO) ? IEC958_AES0_PROFESSIONAL : 0) | 2123 ((val & RME96_WCR_DOLBY) ? IEC958_AES0_NONAUDIO : 0); 2124 if (val & RME96_WCR_PRO) 2125 aes->status[0] |= (val & RME96_WCR_EMP) ? IEC958_AES0_PRO_EMPHASIS_5015 : 0; 2126 else 2127 aes->status[0] |= (val & RME96_WCR_EMP) ? IEC958_AES0_CON_EMPHASIS_5015 : 0; 2128 } 2129 2130 static int snd_rme96_control_spdif_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2131 { 2132 uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; 2133 uinfo->count = 1; 2134 return 0; 2135 } 2136 2137 static int snd_rme96_control_spdif_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2138 { 2139 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2140 2141 snd_rme96_convert_to_aes(&ucontrol->value.iec958, rme96->wcreg_spdif); 2142 return 0; 2143 } 2144 2145 static int snd_rme96_control_spdif_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2146 { 2147 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2148 int change; 2149 u32 val; 2150 2151 val = snd_rme96_convert_from_aes(&ucontrol->value.iec958); 2152 spin_lock_irq(&rme96->lock); 2153 change = val != rme96->wcreg_spdif; 2154 rme96->wcreg_spdif = val; 2155 spin_unlock_irq(&rme96->lock); 2156 return change; 2157 } 2158 2159 static int snd_rme96_control_spdif_stream_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2160 { 2161 uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; 2162 uinfo->count = 1; 2163 return 0; 2164 } 2165 2166 static int snd_rme96_control_spdif_stream_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2167 { 2168 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2169 2170 snd_rme96_convert_to_aes(&ucontrol->value.iec958, rme96->wcreg_spdif_stream); 2171 return 0; 2172 } 2173 2174 static int snd_rme96_control_spdif_stream_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2175 { 2176 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2177 int change; 2178 u32 val; 2179 2180 val = snd_rme96_convert_from_aes(&ucontrol->value.iec958); 2181 spin_lock_irq(&rme96->lock); 2182 change = val != rme96->wcreg_spdif_stream; 2183 rme96->wcreg_spdif_stream = val; 2184 rme96->wcreg &= ~(RME96_WCR_PRO | RME96_WCR_DOLBY | RME96_WCR_EMP); 2185 rme96->wcreg |= val; 2186 writel(rme96->wcreg, rme96->iobase + RME96_IO_CONTROL_REGISTER); 2187 spin_unlock_irq(&rme96->lock); 2188 return change; 2189 } 2190 2191 static int snd_rme96_control_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2192 { 2193 uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; 2194 uinfo->count = 1; 2195 return 0; 2196 } 2197 2198 static int snd_rme96_control_spdif_mask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) 2199 { 2200 ucontrol->value.iec958.status[0] = kcontrol->private_value; 2201 return 0; 2202 } 2203 2204 static int 2205 snd_rme96_dac_volume_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) 2206 { 2207 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2208 2209 uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; 2210 uinfo->count = 2; 2211 uinfo->value.integer.min = 0; 2212 uinfo->value.integer.max = RME96_185X_MAX_OUT(rme96); 2213 return 0; 2214 } 2215 2216 static int 2217 snd_rme96_dac_volume_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *u) 2218 { 2219 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2220 2221 spin_lock_irq(&rme96->lock); 2222 u->value.integer.value[0] = rme96->vol[0]; 2223 u->value.integer.value[1] = rme96->vol[1]; 2224 spin_unlock_irq(&rme96->lock); 2225 2226 return 0; 2227 } 2228 2229 static int 2230 snd_rme96_dac_volume_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *u) 2231 { 2232 struct rme96 *rme96 = snd_kcontrol_chip(kcontrol); 2233 int change = 0; 2234 unsigned int vol, maxvol; 2235 2236 2237 if (!RME96_HAS_ANALOG_OUT(rme96)) 2238 return -EINVAL; 2239 maxvol = RME96_185X_MAX_OUT(rme96); 2240 spin_lock_irq(&rme96->lock); 2241 vol = u->value.integer.value[0]; 2242 if (vol != rme96->vol[0] && vol <= maxvol) { 2243 rme96->vol[0] = vol; 2244 change = 1; 2245 } 2246 vol = u->value.integer.value[1]; 2247 if (vol != rme96->vol[1] && vol <= maxvol) { 2248 rme96->vol[1] = vol; 2249 change = 1; 2250 } 2251 if (change) 2252 snd_rme96_apply_dac_volume(rme96); 2253 spin_unlock_irq(&rme96->lock); 2254 2255 return change; 2256 } 2257 2258 static struct snd_kcontrol_new snd_rme96_controls[] = { 2259 { 2260 .iface = SNDRV_CTL_ELEM_IFACE_PCM, 2261 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT), 2262 .info = snd_rme96_control_spdif_info, 2263 .get = snd_rme96_control_spdif_get, 2264 .put = snd_rme96_control_spdif_put 2265 }, 2266 { 2267 .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE, 2268 .iface = SNDRV_CTL_ELEM_IFACE_PCM, 2269 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM), 2270 .info = snd_rme96_control_spdif_stream_info, 2271 .get = snd_rme96_control_spdif_stream_get, 2272 .put = snd_rme96_control_spdif_stream_put 2273 }, 2274 { 2275 .access = SNDRV_CTL_ELEM_ACCESS_READ, 2276 .iface = SNDRV_CTL_ELEM_IFACE_PCM, 2277 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK), 2278 .info = snd_rme96_control_spdif_mask_info, 2279 .get = snd_rme96_control_spdif_mask_get, 2280 .private_value = IEC958_AES0_NONAUDIO | 2281 IEC958_AES0_PROFESSIONAL | 2282 IEC958_AES0_CON_EMPHASIS 2283 }, 2284 { 2285 .access = SNDRV_CTL_ELEM_ACCESS_READ, 2286 .iface = SNDRV_CTL_ELEM_IFACE_PCM, 2287 .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PRO_MASK), 2288 .info = snd_rme96_control_spdif_mask_info, 2289 .get = snd_rme96_control_spdif_mask_get, 2290 .private_value = IEC958_AES0_NONAUDIO | 2291 IEC958_AES0_PROFESSIONAL | 2292 IEC958_AES0_PRO_EMPHASIS 2293 }, 2294 { 2295 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 2296 .name = "Input Connector", 2297 .info = snd_rme96_info_inputtype_control, 2298 .get = snd_rme96_get_inputtype_control, 2299 .put = snd_rme96_put_inputtype_control 2300 }, 2301 { 2302 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 2303 .name = "Loopback Input", 2304 .info = snd_rme96_info_loopback_control, 2305 .get = snd_rme96_get_loopback_control, 2306 .put = snd_rme96_put_loopback_control 2307 }, 2308 { 2309 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 2310 .name = "Sample Clock Source", 2311 .info = snd_rme96_info_clockmode_control, 2312 .get = snd_rme96_get_clockmode_control, 2313 .put = snd_rme96_put_clockmode_control 2314 }, 2315 { 2316 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 2317 .name = "Monitor Tracks", 2318 .info = snd_rme96_info_montracks_control, 2319 .get = snd_rme96_get_montracks_control, 2320 .put = snd_rme96_put_montracks_control 2321 }, 2322 { 2323 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 2324 .name = "Attenuation", 2325 .info = snd_rme96_info_attenuation_control, 2326 .get = snd_rme96_get_attenuation_control, 2327 .put = snd_rme96_put_attenuation_control 2328 }, 2329 { 2330 .iface = SNDRV_CTL_ELEM_IFACE_MIXER, 2331 .name = "DAC Playback Volume", 2332 .info = snd_rme96_dac_volume_info, 2333 .get = snd_rme96_dac_volume_get, 2334 .put = snd_rme96_dac_volume_put 2335 } 2336 }; 2337 2338 static int 2339 snd_rme96_create_switches(struct snd_card *card, 2340 struct rme96 *rme96) 2341 { 2342 int idx, err; 2343 struct snd_kcontrol *kctl; 2344 2345 for (idx = 0; idx < 7; idx++) { 2346 if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_rme96_controls[idx], rme96))) < 0) 2347 return err; 2348 if (idx == 1) /* IEC958 (S/PDIF) Stream */ 2349 rme96->spdif_ctl = kctl; 2350 } 2351 2352 if (RME96_HAS_ANALOG_OUT(rme96)) { 2353 for (idx = 7; idx < 10; idx++) 2354 if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_rme96_controls[idx], rme96))) < 0) 2355 return err; 2356 } 2357 2358 return 0; 2359 } 2360 2361 /* 2362 * Card initialisation 2363 */ 2364 2365 #ifdef CONFIG_PM_SLEEP 2366 2367 static int rme96_suspend(struct device *dev) 2368 { 2369 struct snd_card *card = dev_get_drvdata(dev); 2370 struct rme96 *rme96 = card->private_data; 2371 2372 snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); 2373 snd_pcm_suspend(rme96->playback_substream); 2374 snd_pcm_suspend(rme96->capture_substream); 2375 2376 /* save capture & playback pointers */ 2377 rme96->playback_pointer = readl(rme96->iobase + RME96_IO_GET_PLAY_POS) 2378 & RME96_RCR_AUDIO_ADDR_MASK; 2379 rme96->capture_pointer = readl(rme96->iobase + RME96_IO_GET_REC_POS) 2380 & RME96_RCR_AUDIO_ADDR_MASK; 2381 2382 /* save playback and capture buffers */ 2383 memcpy_fromio(rme96->playback_suspend_buffer, 2384 rme96->iobase + RME96_IO_PLAY_BUFFER, RME96_BUFFER_SIZE); 2385 memcpy_fromio(rme96->capture_suspend_buffer, 2386 rme96->iobase + RME96_IO_REC_BUFFER, RME96_BUFFER_SIZE); 2387 2388 /* disable the DAC */ 2389 rme96->areg &= ~RME96_AR_DAC_EN; 2390 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 2391 return 0; 2392 } 2393 2394 static int rme96_resume(struct device *dev) 2395 { 2396 struct snd_card *card = dev_get_drvdata(dev); 2397 struct rme96 *rme96 = card->private_data; 2398 2399 /* reset playback and record buffer pointers */ 2400 writel(0, rme96->iobase + RME96_IO_SET_PLAY_POS 2401 + rme96->playback_pointer); 2402 writel(0, rme96->iobase + RME96_IO_SET_REC_POS 2403 + rme96->capture_pointer); 2404 2405 /* restore playback and capture buffers */ 2406 memcpy_toio(rme96->iobase + RME96_IO_PLAY_BUFFER, 2407 rme96->playback_suspend_buffer, RME96_BUFFER_SIZE); 2408 memcpy_toio(rme96->iobase + RME96_IO_REC_BUFFER, 2409 rme96->capture_suspend_buffer, RME96_BUFFER_SIZE); 2410 2411 /* reset the ADC */ 2412 writel(rme96->areg | RME96_AR_PD2, 2413 rme96->iobase + RME96_IO_ADDITIONAL_REG); 2414 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 2415 2416 /* reset and enable DAC, restore analog volume */ 2417 snd_rme96_reset_dac(rme96); 2418 rme96->areg |= RME96_AR_DAC_EN; 2419 writel(rme96->areg, rme96->iobase + RME96_IO_ADDITIONAL_REG); 2420 if (RME96_HAS_ANALOG_OUT(rme96)) { 2421 usleep_range(3000, 10000); 2422 snd_rme96_apply_dac_volume(rme96); 2423 } 2424 2425 snd_power_change_state(card, SNDRV_CTL_POWER_D0); 2426 2427 return 0; 2428 } 2429 2430 static SIMPLE_DEV_PM_OPS(rme96_pm, rme96_suspend, rme96_resume); 2431 #define RME96_PM_OPS &rme96_pm 2432 #else 2433 #define RME96_PM_OPS NULL 2434 #endif /* CONFIG_PM_SLEEP */ 2435 2436 static void snd_rme96_card_free(struct snd_card *card) 2437 { 2438 snd_rme96_free(card->private_data); 2439 } 2440 2441 static int 2442 snd_rme96_probe(struct pci_dev *pci, 2443 const struct pci_device_id *pci_id) 2444 { 2445 static int dev; 2446 struct rme96 *rme96; 2447 struct snd_card *card; 2448 int err; 2449 u8 val; 2450 2451 if (dev >= SNDRV_CARDS) { 2452 return -ENODEV; 2453 } 2454 if (!enable[dev]) { 2455 dev++; 2456 return -ENOENT; 2457 } 2458 err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE, 2459 sizeof(struct rme96), &card); 2460 if (err < 0) 2461 return err; 2462 card->private_free = snd_rme96_card_free; 2463 rme96 = card->private_data; 2464 rme96->card = card; 2465 rme96->pci = pci; 2466 if ((err = snd_rme96_create(rme96)) < 0) { 2467 snd_card_free(card); 2468 return err; 2469 } 2470 2471 #ifdef CONFIG_PM_SLEEP 2472 rme96->playback_suspend_buffer = vmalloc(RME96_BUFFER_SIZE); 2473 if (!rme96->playback_suspend_buffer) { 2474 dev_err(card->dev, 2475 "Failed to allocate playback suspend buffer!\n"); 2476 snd_card_free(card); 2477 return -ENOMEM; 2478 } 2479 rme96->capture_suspend_buffer = vmalloc(RME96_BUFFER_SIZE); 2480 if (!rme96->capture_suspend_buffer) { 2481 dev_err(card->dev, 2482 "Failed to allocate capture suspend buffer!\n"); 2483 snd_card_free(card); 2484 return -ENOMEM; 2485 } 2486 #endif 2487 2488 strcpy(card->driver, "Digi96"); 2489 switch (rme96->pci->device) { 2490 case PCI_DEVICE_ID_RME_DIGI96: 2491 strcpy(card->shortname, "RME Digi96"); 2492 break; 2493 case PCI_DEVICE_ID_RME_DIGI96_8: 2494 strcpy(card->shortname, "RME Digi96/8"); 2495 break; 2496 case PCI_DEVICE_ID_RME_DIGI96_8_PRO: 2497 strcpy(card->shortname, "RME Digi96/8 PRO"); 2498 break; 2499 case PCI_DEVICE_ID_RME_DIGI96_8_PAD_OR_PST: 2500 pci_read_config_byte(rme96->pci, 8, &val); 2501 if (val < 5) { 2502 strcpy(card->shortname, "RME Digi96/8 PAD"); 2503 } else { 2504 strcpy(card->shortname, "RME Digi96/8 PST"); 2505 } 2506 break; 2507 } 2508 sprintf(card->longname, "%s at 0x%lx, irq %d", card->shortname, 2509 rme96->port, rme96->irq); 2510 2511 if ((err = snd_card_register(card)) < 0) { 2512 snd_card_free(card); 2513 return err; 2514 } 2515 pci_set_drvdata(pci, card); 2516 dev++; 2517 return 0; 2518 } 2519 2520 static void snd_rme96_remove(struct pci_dev *pci) 2521 { 2522 snd_card_free(pci_get_drvdata(pci)); 2523 } 2524 2525 static struct pci_driver rme96_driver = { 2526 .name = KBUILD_MODNAME, 2527 .id_table = snd_rme96_ids, 2528 .probe = snd_rme96_probe, 2529 .remove = snd_rme96_remove, 2530 .driver = { 2531 .pm = RME96_PM_OPS, 2532 }, 2533 }; 2534 2535 module_pci_driver(rme96_driver); 2536 This page was automatically generated by LXR 0.3.1 (source).  •  Linux is a registered trademark of Linus Torvalds  •  Contact us
__label__pos
0.984915
pygame – Layer sprites according to their vertical position I need advanced blitting options in my game. It’s a 2D game that has trees’ sprites along with the player’s sprite. I want that every tree sprite to be displayed either in front of or behind the player sprite, depending on whether the player is standing higher or lower on the screen than the tree’s base. These are the possible cases : cases I have an idea in mind, which is to check for the player’s coordinates and depending on them, blit the tree’s sprite underneath it or above it (respecting the layers system). However, I think that this won’t work or will make the tree’s sprite flicker in case there is more than one player (or another object that can pass beside the tree). So what is a good solution for that ? The reason why I want to solve this problem is adding some depth and reality into the game though it’s a 2D one.
__label__pos
0.938803
Extending Zend Auth - A Zend Config Adapter So in the last installment of this series, I provided an introduction to Zend_Auth, Zend_Auth_Adapter_Interface and Zend_Auth_Result and how to implement Zend_Auth_Adapter_Interface to implement a basic test adapter that can be used as a mock object in your testing. If you missed it, check it out now, then come back and we’ll continue on. If you’ve already read it, then let’s continue now. As I indicated last time, whilst being a perfectly valid implementation, the Test adapter was rather basic and didn’t do very much. Like all good testing, you need flexibility and options. So in this installment, we’re going to build an adapter based around Zend_Config. This will lead quite nicely in to the last part in the series which uses the wonderful MongoDB as the underlying resource for the adapter. So in the last installment of this series, I provided an introduction to Zend_Auth, Zend_Auth_Adapter_Interface and Zend_Auth_Result and how to implement Zend_Auth_Adapter_Interface to implement a basic test adapter that can be used as a mock object in your testing. If you missed it, check it out now, then come back and we’ll continue on. If you’ve already read it, then let’s continue now. As I indicated last time, whilst being a perfectly valid implementation, the Test adapter was rather basic and didn’t do very much. Like all good testing, you need flexibility and options. So in this installment, we’re going to build an adapter based around Zend_Config. This will lead quite nicely in to the last part in the series which uses the wonderful MongoDB as the underlying resource for the adapter. A Zend_Config Primer If you’re not familiar with Zend_Config, the manual states: “…is designed to simplify the access to, and the use of, configuration data within applications”. Just like Zend_Auth, Zend_Db and a host of the other components of the Zend Framework, Zend_Config also allows for the use of a series of config types through config adapters. The ones that are currently implemented are: • Ini • Xml • Json • Yaml So no matter what type of file your configuration information is stored in, if it’s one of these, or can be converted to one of them, you can use Zend_Config quickly and easily to retrieve configuration data for your application. Given that, it makes it a good choice as the next level in advancement of adapters for us to create. So in this version, we’re going to have a simple Xml file that contains the details of a number of users. How will it work? We’re going to create a Zend_Config object from the Xml file, set it as a member variable of our new adapter and then, when the authenticate method is called, we’re going to search in it to see if we have a user with the credentials set in username and password. Not much too it right? Exactly. Our XML Configuration File   <configdata> <production> <login> <users> <settermjd> <password>5f4dcc3b5aa765d61d8327deb882cf99</host> <firstname>matthew</firstname> <lastname>setter</lastname> <company>malt blue</company> <email>[email protected]</email> </settermjd> <citizenj> <password>56266a582ccab096b63eceaea36d1f4c</host> <firstname>john</firstname> <lastname>citizen</lastname> <company>malt blue</company> <email>[email protected]</email> </citizenj> </users> </login> </production> <staging extends="production"> <login> <users> <settermjd> <password>3c0e32a23e491092f5966071bdeda367</host> <firstname>matthew</firstname> <lastname>setter</lastname> <company>malt blue</company> <email>[email protected]</email> </settermjd> </users> </login> </staging> </configdata> You can see in the xml above, that in production, we have 2 users, settermjd and citizenj. Both of them have the properties: password, firstname, lastname, company and email. Having a look in the staging environment configuration, you can see that only settermjd is there. Now I’m not that narcissistic, but it shows how we can differentiate between different environments, making testing and development easier. Now on successful login, the information contained in the users details will be set in the identity object and returned in the Zend_Auth_Result object. Arguably nice, clean and efficient. **NB: **Now what it’s not is likely the way that you would build an adapter for heavy production use, but it does show another way to progress. The Constructor public function __construct(Zend_Config $config=null, $username = null, $password = null) { if (!empty($config)) { if (!($config instanceof Zend_Config)) { throw new Zend_Auth_Adapter_Exception(); } $this->_config = $config; } if (!empty($password)) { $this->_password = $password; } if (!empty($username) && ) { $this->_username = $username; } } This constructor augments the Test adapter constructor and takes a Zend_Config object as its first parameter. The original username and password continue to be used. We then add an extra check to ensure that the object passed in is a valid Zend_Config object before assigning it if it is; the method type hinting should take care of that for us for the most part. The Authenticate Method public function authenticate() { if (empty($this->_username) || empty($this->_password)) { throw new Zend_Auth_Adapter_Exception(); } // search for the username/password combination in the available list $userConfig = $this->_config->users->get($this->_username, null); if (is_null($userConfig)) { return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, array() ); } else { if (!empty($this->_credentialTreatment)) { $credential = $this->_credentialTreatment; if (!in_array($credential, $this->_allowedCredentials)) { return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_UNCATEGORIZED, array() ); } if ($userConfig->password != $credential($this->_password)) { return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array() ); } } else { if ($userConfig->password != $this->_password) { return new Zend_Auth_Result( Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, array() ); } } return new Zend_Auth_Result( Zend_Auth_Result::SUCCESS, array( 'username' => $this->_username, 'firstName' => $userConfig->firstname, 'lastName' => $userConfig->lastname, 'emailAddress' => $userConfig->email, 'company' => $userConfig->company, ) ); } You can see that the authenticate method is also largely the same. As before, we check if we have a valid username and password. But now, that we also have a valid config object we validate that as well. Following this, we search in the config object for the user to see if we have one that matches the username passed in. If we found them, we then move to validate the password. As we’re getting more detailed this time, we’ve also lifted a method from Zend_Auth_DbTable; setCredentialTreatment. This allows us to set how we’re going to treat the user credentials – in our case, the password field. public function setCredentialTreatment($treatment) { $this->_credentialTreatment = $treatment; return $this; } If it’s not called, then the password is compared as is. If it’s called, then the method that’s set in it is used to compare the password value entered against the value we have stored. You’ll note in the XML config that the password for each user is an MD5 hash. So later on we’re going to call the method, setting md5 as the treatment. Another point to note is that this is a fairly simple implementation. We’ve added an array **$_allowedCredentials **which restricts the allowed choices of credential functions; specifically to md5 and sha1. We could use call_func_array or something like that to expand this, but well, why take all the fun out of it. If the user is available and the password matches we then retrieve the details of the user config object and create an identity object with that information and return it as normal. If the user is not available, then we return the code Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID and an empty identity object. If the password’s don’t match, then we return the code Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND and an empty identity object. If the user attempts to set an invalid credential function then we return the code Zend_Auth_Result::FAILURE_UNCATEGORIZED and an empty identity object. So, what did you think? • Too easy, too simplistic? • Didn’t go far enough? I’d love to hear your thoughts where you think this could go and where it could be done better. You might also be interested in... comments powered by Disqus Books Buy Mezzio Essentials. Learn the fundamentals that you need, to begin building applications with the Mezzio framework today! Buy Now Latest YouTube Video Learn how to write SQL queries in PhpStorm
__label__pos
0.851472
0 I have read the wiki page and I would like some further and more technical(if possible) confirmation for a few things. A bitcoin node is a user which is connected to the network through a client. This node can perform transactions, try to build a block inside a mining pool, or just exist in the network. Are there any further actions for a node? If a node exists inside the network how can he verify the transactions? Furthermore is there a paper or something that explains things in a lower level of how exactly the system works in case of transactions and mining? I do not want a description but something more technical. 1 A bitcoin node is a user which is connected to the network through a client. This node can perform transactions, try to build a block inside a mining pool, or just exist in the network. Are there any further actions for a node? Nodes also relay blocks and transactions to other nodes. They also validate incoming blocks and transactions and keep track of the current, longest valid blockchain. That's pretty much it. If a node exists inside the network how can he verify the transactions? There are a set of mathematical rules that determine if transactions are valid. The nodes check the transactions against those rules. If they meet the rules, they are valid. Furthermore is there a paper or something that explains things in a lower level of how exactly the system works in case of transactions and mining? I do not want a description but something more technical. Almost every question you can think of is answered, in technical detail, somewhere in the Bitcoin wiki. 2 • I am seeking more information about how transactions / blocks are relayed and how they are validated. Can you point me to some reference in the wiki or to some other point? Jan 5 '14 at 14:19 • @angellimneos Start with the whitepaper. Jan 5 '14 at 18:44 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.948586
Varnish介绍安装及应用 简介: +关注继续查看 一、关于Varnish 1、varnish系统架构 varnish主要运行两个进程:Management进程和Child进程(也叫Cache进程)。 Management进程主要实现应用新的配置、编译VCL、监控varnish、初始化varnish以及提供一个命令行接口等。Management进程会每隔几秒钟探测一下Child进程以判断其是否正常运行,如果在指定的时长内未得到Child进程的回应,Management将会重启此Child进程。 Child进程包含多种类型的线程,常见的如: Acceptor线程:接收新的连接请求并响应; Worker线程:child进程会为每个会话启动一个worker线程,因此,在高并发的场景中可能会出现数百个worker线程甚至更多; Expiry线程:从缓存中清理过期内容; Varnish依赖“工作区(workspace)”以降低线程在申请或修改内存时出现竞争的可能性。在varnish内部有多种不同的工作区,其中最关键的当属用于管理会话数据的session工作区。 2、varnish日志 为了与系统的其它部分进行交互,Child进程使用了可以通过文件系统接口进行访问的共享内存日志(shared memory log),因此,如果某线程需要记录信息,其仅需要持有一个锁,而后向共享内存中的某内存区域写入数据,再释放持有的锁即可。而为了减少竞争,每个worker线程都使用了日志数据缓存。 共享内存日志大小一般为90M,其分为两部分,前一部分为计数器,后半部分为客户端请求的数据。varnish提供了多个不同的工具如varnishlog、varnishncsa或varnishstat等来分析共享内存日志中的信息并能够以指定的方式进行显示。 3、VCL Varnish Configuration Language (VCL)是varnish配置缓存策略的工具,它是一种基于“域”(domain specific)的简单编程语言,它支持有限的算术运算和逻辑运算操作、允许使用正则表达式进行字符串匹配、允许用户使用set自定义变量、支持if判断语句,也有内置的函数和变量等。使用VCL编写的缓存策略通常保存至.vcl文件中,其需要编译成二进制的格式后才能由varnish调用。事实上,整个缓存策略就是由几个特定的子例程如vcl_recv、vcl_fetch等组成,它们分别在不同的位置(或时间)执行,如果没有事先为某个位置自定义子例程,varnish将会执行默认的定义。 VCL策略在启用前,会由management进程将其转换为C代码,而后再由gcc编译器将C代码编译成二进制程序。编译完成后,management负责将其连接至varnish实例,即child进程。正是由于编译工作在child进程之外完成,它避免了装载错误格式VCL的风险。因此,varnish修改配置的开销非常小,其可以同时保有几份尚在引用的旧版本配置,也能够让新的配置即刻生效。编译后的旧版本配置通常在varnish重启时才会被丢弃,如果需要手动清理,则可以使用varnishadm的vcl.discard命令完成。 4、varnish的后端存储 varnish支持多种不同类型的后端存储,这可以在varnishd启动时使用-s选项指定。后端存储的类型包括: (1)file:使用特定的文件存储全部的缓存数据,并通过操作系统的mmap()系统调用将整个缓存文件映射至内存区域(如果条件允许); (2)malloc:使用malloc()库调用在varnish启动时向操作系统申请指定大小的内存空间以存储缓存对象; (3)persistent(experimental):与file的功能相同,但可以持久存储数据(即重启varnish数据时不会被清除);仍处于测试期; varnish无法追踪某缓存对象是否存入了缓存文件,从而也就无从得知磁盘上的缓存文件是否可用,因此,file存储方法在varnish停止或重启时会清除数据。而persistent方法的出现对此有了一个弥补,但persistent仍处于测试阶段,例如目前尚无法有效处理要缓存对象总体大小超出缓存空间的情况,所以,其仅适用于有着巨大缓存空间的场景。 选择使用合适的存储方式有助于提升系统性,从经验的角度来看,建议在内存空间足以存储所有的缓存对象时使用malloc的方法,反之,file存储将有着更好的性能的表现。然而,需要注意的是,varnishd实际上使用的空间比使用-s选项指定的缓存空间更大,一般说来,其需要为每个缓存对象多使用差不多1K左右的存储空间,这意味着,对于100万个缓存对象的场景来说,其使用的缓存空间将超出指定大小1G左右。另外,为了保存数据结构等,varnish自身也会占去不小的内存空间。 为varnishd指定使用的缓存类型时,-s选项可接受的参数格式如下: malloc[,size] 或     file[,path[,size[,granularity]]] 或 persistent,path,size {experimental} file中的granularity用于设定缓存空间分配单位,默认单位是字节,所有其它的大小都会被圆整。 二、安装varnish 三、HTTP协议与varnish 1、缓存相关的HTTP首部 HTTP协议提供了多个首部用以实现页面缓存及缓存失效的相关功能,这其中最常用的有: (1)Expires:用于指定某web对象的过期日期/时间,通常为GMT格式;一般不应该将此设定的未来过长的时间,一年的长度对大多场景来说足矣;其常用于为纯静态内容如JavaScripts样式表或图片指定缓存周期; (2)Cache-Control:用于定义所有的缓存机制都必须遵循的缓存指示,这些指示是一些特定的指令,包括public、private、no-cache(表示可以存储,但在重新验正其有效性之前不能用于响应客户端请求)、no-store、max-age、s-maxage以及must-revalidate等;Cache-Control中设定的时间会覆盖Expires中指定的时间; (3)Etag:响应首部,用于在响应报文中为某web资源定义版本标识符; (4)Last-Mofified:响应首部,用于回应客户端关于Last-Modified-Since或If-None-Match首部的请求,以通知客户端其请求的web对象最近的修改时间; (5)If-Modified-Since:条件式请求首部,如果在此首部指定的时间后其请求的web内容发生了更改,则服务器响应更改后的内容,否则,则响应304(not modified); (6)If-None-Match:条件式请求首部;web服务器为某web内容定义了Etag首部,客户端请求时能获取并保存这个首部的值(即标签);而后在后续的请求中会通过If-None-Match首部附加其认可的标签列表并让服务器端检验其原始内容是否有可以与此列表中的某标签匹配的标签;如果有,则响应304,否则,则返回原始内容; (7)Vary:响应首部,原始服务器根据请求来源的不同响应的可能会有所不同的首部,最常用的是Vary: Accept-Encoding,用于通知缓存机制其内容看起来可能不同于用户请求时Accept-Encoding-header首部标识的编码格式; (8)Age:缓存服务器可以发送的一个额外的响应首部,用于指定响应的有效期限;浏览器通常根据此首部决定内容的缓存时长;如果响应报文首部还使用了max-age指令,那么缓存的有效时长为“max-age减去Age”的结果; 四、Varnish状态引擎(state engine) VCL用于让管理员定义缓存策略,而定义好的策略将由varnish的management进程分析、转换成C代码、编译成二进制程序并连接至child进程。varnish内部有几个所谓的状态(state),在这些状态上可以附加通过VCL定义的策略以完成相应的缓存处理机制,因此VCL也经常被称作“域专用”语言或状态引擎,“域专用”指的是有些数据仅出现于特定的状态中。 1、VCL状态引擎 在VCL状态引擎中,状态之间具有相关性,但彼此间互相隔离,每个引擎使用return(x)来退出当前状态并指示varnish进入下一个状态。 varnish开始处理一个请求时,首先需要分析HTTP请求本身,比如从首部获取请求方法、验正其是否为一个合法的HTT请求等。当这些基本分析结束后就需要做出第一个决策,即varnish是否从缓存中查找请求的资源。这个决定的实现则需要由VCL来完成,简单来说,要由vcl_recv方法来完成。如果管理员没有自定义vcl_recv函数,varnish将会执行默认的vcl_recv函数。然而,即便管理员自定义了vcl_recv,但如果没有为自定义的vcl_recv函数指定其终止操作(terminating),其仍将执行默认的vcl_recv函数。事实上,varnish官方强烈建议让varnish执行默认的vcl_recv以便处理自定义vcl_recv函数中的可能出现的漏洞。 2、VCL语法 VCL的设计参考了C和Perl语言,因此,对有着C或Perl编程经验者来说,其非常易于理解。其基本语法说明如下: (1)//、#或/* comment */用于注释 (2)sub $name 定义函数 (3)不支持循环,有内置变量 (4)使用终止语句,没有返回值 (5)域专用 (6)操作符:=(赋值)、==(等值比较)、~(模式匹配)、!(取反)、&&(逻辑与)、||(逻辑或) VCL的函数不接受参数并且没有返回值,因此,其并非真正意义上的函数,这也限定了VCL内部的数据传递只能隐藏在HTTP首部内部进行。VCL的return语句用于将控制权从VCL状态引擎返回给Varnish,而非默认函数,这就是为什么VCL只有终止语句而没有返回值的原因。同时,对于每个“域”来说,可以定义一个或多个终止语句,以告诉Varnish下一步采取何种操作,如查询缓存或不查询缓存等。 3、VCL的内置函数 VCL提供了几个函数来实现字符串的修改,添加bans,重启VCL状态引擎以及将控制权转回Varnish等。 regsub(str,regex,sub) regsuball(str,regex,sub):这两个用于基于正则表达式搜索指定的字符串并将其替换为指定的字符串;但regsuball()可以将str中能够被regex匹配到的字符串统统替换为sub,regsub()只替换一次; ban(expression): ban_url(regex):Bans所有其URL能够由regex匹配的缓存对象; purge:从缓存中挑选出某对象以及其相关变种一并删除,这可以通过HTTP协议的PURGE方法完成; hash_data(str): return():当某VCL域运行结束时将控制权返回给Varnish,并指示Varnish如何进行后续的动作;其可以返回的指令包括:lookup、pass、pipe、hit_for_pass、fetch、deliver和hash等;但某特定域可能仅能返回某些特定的指令,而非前面列出的全部指令; return(restart):重新运行整个VCL,即重新从vcl_recv开始进行处理;每一次重启都会增加req.restarts变量中的值,而max_restarts参数则用于限定最大重启次数。 4、vcl_recv vcl_recv是在Varnish完成对请求报文的解码为基本数据结构后第一个要执行的子例程,它通常有四个主要用途: (1)修改客户端数据以减少缓存对象差异性;比如删除URL中的www.等字符; (2)基于客户端数据选用缓存策略;比如仅缓存特定的URL请求、不缓存POST请求等; (3)为某web应用程序执行URL重写规则; (4)挑选合适的后端Web服务器; 可以使用下面的终止语句,即通过return()向Varnish返回的指示操作: pass:绕过缓存,即不从缓存中查询内容或不将内容存储至缓存中; pipe:不对客户端进行检查或做出任何操作,而是在客户端与后端服务器之间建立专用“管道”,并直接将数据在二者之间进行传送;此时,keep-alive连接中后续传送的数据也都将通过此管道进行直接传送,并不会出现在任何日志中; lookup:在缓存中查找用户请求的对象,如果缓存中没有其请求的对象,后续操作很可能会将其请求的对象进行缓存; error:由Varnish自己合成一个响应报文,一般是响应一个错误类信息、重定向类信息或负载均衡器返回的后端web服务器健康状态检查类信息; vcl_recv也可以通过精巧的策略完成一定意义上的安全功能,以将某些特定的攻击扼杀于摇篮中。同时,它也可以检查出一些拼写类的错误并将其进行修正等。 Varnish默认的vcl_recv专门设计用来实现安全的缓存策略,它主要完成两种功能: (1)仅处理可以识别的HTTP方法,并且只缓存GET和HEAD方法; (2)不缓存任何用户特有的数据; 安全起见,一般在自定义的vcl_recv中不要使用return()终止语句,而是再由默认vcl_recv进行处理,并由其做出相应的处理决策。 下面是一个自定义的使用示例: sub vcl_recv { if (req.http.User-Agent ~ "iPad" || req.http.User-Agent ~ "iPhone" || req.http.User-Agent ~ "Android") { set req.http.X-Device = "mobile"; } else { set req.http.X-Device = "desktop"; } } 此例中的VCL创建一个X-Device请求首部,其值可能为mobile或desktop,于是web服务器可以基于此完成不同类型的响应,以提高用户体验。 5、vcl_fetch 如前面所述,相对于vcl_recv是根据客户端的请求作出缓存决策来说,vcl_fetch则是根据服务器端的响应作出缓存决策。在任何VCL状态引擎中返回的pass操作都将由vcl_fetch进行后续处理。vcl_fetch中有许多可用的内置变量,比如最常用的用于定义某对象缓存时长的beresp.ttl变量。通过return()返回给arnish的操作指示有: (1)deliver:缓存此对象,并将其发送给客户端(经由vcl_deliver); (2)hit_for_pass:不缓存此对象,但可以导致后续对此对象的请求直接送达到vcl_pass进行处理; (3)restart:重启整个VCL,并增加重启计数;超出max_restarts限定的最大重启次数后将会返回错误信息; (4)error code [reason]:返回指定的错误代码给客户端并丢弃此请求; 默认的vcl_fetch放弃了缓存任何使用了Set-Cookie首部的响应。 五、修剪缓存对象 1、缓存内容修剪 提高缓存命中率的最有效途径之一是增加缓存对象的生存时间(TTL),但是这也可能会带来副作用,比如缓存的内容在到达为其指定的有效期之间已经失效。因此,手动检验缓存对象的有效性或者刷新缓存是缓存很有可能成为服务器管理员的日常工作之一,相应地,Varnish为完成这类的任务提供了三种途径:HTTP 修剪(HTTP purging)、禁用某类缓存对象(banning)和强制缓存未命令(forced cache misses)。 这里需要特殊说明的是,Varnish 2中的purge()操作在Varnish 3中被替换为了ban()操作,而Varnish 3也使用了purge操作,但为其赋予了新的功能,且只能用于vcl_hit或vcl_miss中替换Varnish 2中常用的set obj.ttl=0s。 在具体执行某清理工作时,需要事先确定如下问题: (1)仅需要检验一个特定的缓存对象,还是多个? (2)目的是释放内存空间,还是仅替换缓存的内容? (3)是不是需要很长时间才能完成内容替换? (4)这类操作是个日常工作,还是仅此一次的特殊需求? 2、移除单个缓存对象 purge用于清理缓存中的某特定对象及其变种(variants),因此,在有着明确要修剪的缓存对象时可以使用此种方式。HTTP协议的PURGE方法可以实现purge功能,不过,其仅能用于vcl_hit和vcl_miss中,它会释放内存工作并移除指定缓存对象的所有Vary:-变种,并等待下一个针对此内容的客户端请求到达时刷新此内容。另外,其一般要与return(restart)一起使用。下面是个在VCL中配置的示例。 acl purgers { "127.0.0.1"; "192.168.0.0"/24; } sub vcl_recv { if (req.request == "PURGE") { if (!client.ip ~ purgers) { error 405 "Method not allowed"; } return (lookup); } } sub vcl_hit { if (req.request == "PURGE") { purge; error 200 "Purged"; } } sub vcl_miss { if (req.request == "PURGE") { purge; error 404 "Not in cache"; } } sub vcl_pass { if (req.request == "PURGE") { error 502 "PURGE on a passed object"; } } 客户端在发起HTTP请求时,只需要为所请求的URL使用PURGE方法即可,其命令使用方式如下: # curl -I -X PURGE http://varniship/path/to/someurl 3、强制缓存未命中 在vcl_recv中使用return(pass)能够强制到上游服务器取得请求的内容,但这也会导致无法将其缓存。使用purge会移除旧的缓存对象,但如果上游服务器宕机而无法取得新版本的内容时,此内容将无法再响应给客户端。使用req.has_always_miss=ture,可以让Varnish在缓存中搜寻相应的内容但却总是回应“未命中”,于是vcl_miss将后续地负责启动vcl_fetch从上游服务器取得新内容,并以新内容缓存覆盖旧内容。此时,如果上游服务器宕机或未响应,旧的内容将保持原状,并能够继续服务于那些未使用req.has_always_miss=true的客户端,直到其过期失效或由其它方法移除。 4、Banning ban()是一种从已缓存对象中过滤(filter)出某此特定的对象并将其移除的缓存内容刷新机制,不过,它并不阻止新的内容进入缓存或响应于请求。在Varnish中,ban的实现是指将一个ban添加至ban列表(ban-list)中,这可以通过命令行接口或VCL实现,它们的使用语法是相同的。ban本身就是一个或多个VCL风格的语句,它会在Varnish从缓存哈希(cache hash)中查找某缓存对象时对搜寻的对象进行比较测试,因此,一个ban语句就是类似匹配所有“以/downloads开头的URL”,或“响应首部中包含nginx的对象”。例如: ban req.http.host == "wzlinux.com" && req.url ~ "\.gif$" 定义好的所有ban语句会生成一个ban列表(ban-list),新添加的ban语句会被放置在列表的首部。缓存中的所有对象在响应给客户端之前都会被ban列表检查至少一次,检查完成后将会为每个缓存创建一个指向与其匹配的ban语句的指针。Varnish在从缓存中获取对象时,总是会检查此缓存对象的指针是否指向了ban列表的首部。如果没有指向ban列表的首部,其将对使用所有的新添加的ban语句对此缓存对象进行测试,如果没有任何ban语句能够匹配,则更新ban列表。 对ban这种实现方式持反对意见有有之,持赞成意见者亦有之。反对意见主要有两种,一是ban不会释放内存,缓存对象仅在有客户端访问时被测试一次;二是如果缓存对象曾经被访问到,但却很少被再次访问时ban列表将会变得非常大。赞成的意见则主要集中在ban可以让Varnish在恒定的时间内完成向ban列表添加ban的操作,例如在有着数百万个缓存对象的场景中,添加一个ban也只需要在恒定的时间内即可完成。其实现方法本处不再详细说明。 六、Varnish检测后端主机的健康状态 Varnish可以检测后端主机的健康状态,在判定后端主机失效时能自动将其从可用后端主机列表中移除,而一旦其重新变得可用还可以自动将其设定为可用。为了避免误判,Varnish在探测后端主机的健康状态发生转变时(比如某次探测时某后端主机突然成为不可用状态),通常需要连续执行几次探测均为新状态才将其标记为转换后的状态。 每个后端服务器当前探测的健康状态探测方法通过.probe进行设定,其结果可由req.backend.healthy变量获取,也可通过varnishlog中的Backend_health查看或varnishadm的debug.health查看。 backend web1 { .host = "www.wzlinux.com"; .probe = { .url = "/.healthtest.html"; .interval = 1s; .window = 5; .threshold = 2; } } .probe中的探测指令常用的有: (1) .url:探测后端主机健康状态时请求的URL,默认为“/”; (2) .request: 探测后端主机健康状态时所请求内容的详细格式,定义后,它会替换.url指定的探测方式;比如: .request = "GET /.healthtest.html HTTP/1.1" "Host: www.wzlinux.com" "Connection: close"; (3) .window:设定在判定后端主机健康状态时基于最近多少次的探测进行,默认是8; (4) .threshold:在.window中指定的次数中,至少有多少次是成功的才判定后端主机正健康运行;默认是3; (5) .initial:Varnish启动时对后端主机至少需要多少次的成功探测,默认同.threshold; (6) .expected_response:期望后端主机响应的状态码,默认为200; (7) .interval:探测请求的发送周期,默认为5秒; (8) .timeout:每次探测请求的过期时长,默认为2秒; 因此,如上示例中表示每隔1秒对此后端主机www.wzlinux.com探测一次,请求的URL为http://www.wzlinux.com/.healthtest.html,在最近5次的探测请求中至少有2次是成功的(响应码为200)就判定此后端主机为正常工作状态。 如果Varnish在某时刻没有任何可用的后端主机,它将尝试使用缓存对象的“宽容副本”(graced copy),当然,此时VCL中的各种规则依然有效。因此,更好的办法是在VCL规则中判断req.backend.healthy变量显示某后端主机不可用时,为此后端主机增大req.grace变量的值以设定适用的宽容期限长度。 七、Varnish使用多台后端主机 Varnish中可以使用director指令将一个或多个近似的后端主机定义为一个逻辑组,并可以指定的调度方式(也叫挑选方法)来轮流将请求发送至这些主机上。不同的director可以使用同一个后端主机,而某director也可以使用“匿名”后端主机(在director中直接进行定义)。每个director都必须有其专用名,且在定义后必须在VCL中进行调用,VCL中任何可以指定后端主机的位置均可以按需将其替换为调用某已定义的director。 backend web1 { .host = "backweb1.wzlinux.com"; .port = "80"; } director webservers random {   .retries = 5;   {     .backend = web1;     .weight  = 2;   }   {     .backend  = {       .host = "backweb2.wzlinux.com";  .port = "80";     }   .weight         = 3;   } } 如上示例中,web1为显式定义的后端主机,而webservers这个directors还包含了一个“匿名”后端主机(backweb2.wzlinux.com)。webservers从这两个后端主机中挑选一个主机的方法为random,即以随机方式挑选。 Varnish的director支持的挑选方法中比较简单的有round-robin和random两种。其中,round-robin类型没有任何参数,只需要为其指定各后端主机即可,挑选方式为“轮叫”,并在某后端主机故障时不再将其视作挑选对象;random方法随机从可用后端主机中进行挑选,每一个后端主机都需要一个.weight参数以指定其权重,同时还可以director级别使用.retires参数来设定查找一个健康后端主机时的尝试次数。 Varnish 2.1.0后,random挑选方法又多了两种变化形式client和hash。client类型的director使用client.identity作为挑选因子,这意味着client.identity相同的请求都将被发送至同一个后端主机。client.identity默认为cliet.ip,但也可以在VCL中将其修改为所需要的标识符。类似地,hash类型的director使用hash数据作为挑选因子,这意味着对同一个URL的请求将被发往同一个后端主机,其常用于多级缓存的场景中。然而,无论是client还hash,当其倾向于使用后端主机不可用时将会重新挑选新的后端其机。 另外还有一种称作fallback的director,用于定义备用服务器,如下所示: director b3 fallback {   { .backend = www1; }   { .backend = www2; } // will only be used if www1 is unhealthy.   { .backend = www3; } // will only be used if both www1 and www2                        // are unhealthy. } 八、varnish管理进阶 1、可调参数 Varnish有许多参数,虽然大多数场景中这些参数的默认值都可以工作得很好,然而特定的工作场景中要想有着更好的性能的表现,则需要调整某些参数。可以在管理接口中使用param.show命令查看这些参数,而使用param.set则能修改这些参数的值。然而,在命令行接口中进行的修改不会保存至任何位置,因此,重启varnish后这些设定会消失。此时,可以通过启动脚本使用-p选项在varnishd启动时为其设定参数的值。然而,除非特别需要对其进行修改,保持这些参数为默认值可以有效降低管理复杂度。 2、共享内存日志 共享内存日志(shared memory log)通常被简称为shm-log,它用于记录日志相关的数据,大小为80M。varnish以轮转(round-robin)的方式使用其存储空间。一般不需要对shm-log做出更多的设定,但应该避免其产生I/O,这可以使用tmpfs实现,其方法为在/etc/fstab中设定一个挂载至/var/lib/varnish目录(或其它自定义的位置)临时文件系统即可。 3、线程模型(Trheading model) varnish的child进程由多种不同的线程组成,分别用于完成不同的工作。例如: cache-worker线程:每连接一个,用于处理请求; cache-main线程:全局只有一个,用于启动cache; ban lurker线程:一个,用于清理bans; acceptor线程:一个,用于接收新的连接请求; epoll/kqueue线程:数量可配置,默认为2,用于管理线程池; expire线程:一个,用于移除老化的内容; backend poll线程:每个后端服务器一个,用于检测后端服务器的健康状况; 在配置varnish时,一般只需为关注cache-worker线程,而且也只能配置其线程池的数量,而除此之外的其它均非可配置参数。与此同时,线程池的数量也只能在流量较大的场景下才需要增加,而且经验表明其多于2个对提升性能并无益处。 4、线程相关的参数(Threading parameters) varnish为每个连接使用一个线程,因此,其worker线程的最大数决定了varnish的并发响应能力。下面是线程池相关的各参数及其配置: thread_pool_add_delay      2 [milliseconds] thread_pool_add_threshold  2 [requests] thread_pool_fail_delay     200 [milliseconds] thread_pool_max            500 [threads] thread_pool_min            5 [threads] thread_pool_purge_delay    1000 [milliseconds] thread_pool_stack          65536 [bytes] thread_pool_timeout        120 [seconds] thread_pool_workspace      16384 [bytes] thread_pools               2 [pools] thread_stats_rate          10 [requests] 其中最关键的当属thread_pool_max和thread_pool_min,它们分别用于定义每个线程池中的最大线程数和最少线程数。因此,在某个时刻,至少有thread_pool_min*thread_pools个worker线程在运行,但至多不能超出thread_pool_max*thread_pools个。根据需要,这两个参数的数量可以进行调整,varnishstat命令的n_wrk_queued可以显示当前varnish的线程数量是否足够,如果队列中始终有不少的线程等待运行,则可以适当调大thread_pool_max参数的值。但一般建议每台varnish服务器上最多运行的worker线程数不要超出5000个。 当某连接请求到达时,varnish选择一个线程池负责处理此请求。而如果此线程池中的线程数量已经达到最大值,新的请求将会被放置于队列中或被直接丢弃。默认线程池的数量为2,这对最繁忙的varnish服务器来说也已经足够。 5、 九、Varnish的命令行工具 1、varnishadm命令 命令语法:varnishadm [-t timeout] [-S secret_file] [-T address:port] [-n name] [command [...]] 通过命令行的方式连接至varnishd进行管理操作的工具,指定要连接的varnish实例的方法有两种: -n name —— 连接至名称为“name”的实例; -T address:port —— 连接至指定套接字上的实例; 其运行模式有两种,当不在命令行中给出要执行的"command"时,其将进入交互式模式;否则,varnishadm将执行指定的"command"并退出。要查看本地启用的缓存,可使用如下命令进行。 # varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082 storage.list      本文转自 wzlinux 51CTO博客,原文链接:http://blog.51cto.com/wzlinux/1690728,如需转载请自行联系原作者 相关实践学习 日志服务之使用Nginx模式采集日志 本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。 相关文章 | 存储 缓存 监控 | 缓存 前端开发 区块链 | 存储 Web App开发 缓存 | Web App开发 存储 缓存 | Web App开发 缓存 测试技术 | 缓存 前端开发 JavaScript 推荐文章 更多
__label__pos
0.554048
CI/CD Tools Integration Features that help you use SnapLogic with your CI/CD process. Overview Continuous Integration / Continuous Delivery/Deployment (CI/CD) is a set of automated processes that enable frequent testing, delivery, and deployment of software to users. SnapLogic provides several features to help you streamline your CI/CD processes, including: • SnapLogic - Git Integration. Link your SnapLogic projects to your Git repositories and manage them. • Workflows and pipelines. Start with Git workflow examples, Dev Ops pipeline examples, and GitHub Action examples. Then customize them for your own processes. • Secrets Management. Secure your CI/CD processes by integrating with secrets management tools. • SnapLogic Public APIs. Use the SnapLogic Public APIs to automate your CI/CD processes. CI/CD Strategies Each organization has its own requirements and methods for CI/CD; therefore, each organization's strategy is unique. The following example CI/CD strategies illustrate different ways of deploying from your dev/test environment to your production environment. Migration The migration CI/CD strategy uses migration tools to deploy changes from the dev/test environment to the production environment. To set up the migration CI/CD strategy: 1. In the production Org, set up accounts. 2. In the dev/test Org, create a project. 3. In the dev/test Org, make the required changes. 4. Migrate the project to the production Org. Accounts must already be set up in the destination environment. Accounts with the same name across all Orgs are considered the same account. Import/Export The import/export CI/CD strategy uses import and export tools to deploy changes from the dev/test environment to the production environment. To set up the import/export CI/CD strategy: 1. In the dev/test Org, create a project. 2. In the dev/test Org, make the required changes. 3. Export the project. The export process creates a zip file. 4. Import the zip file into your production environment, as well as the accounts (accounts.json) and expression libraries (expression.zip) specific to the environment. To undo, import a previously exported .zip file. Repository The repository CI/CD strategy uses a repository between the dev/test environment and the production environment. Updated files are committed from the dev/test environment into the repository and then pulled from the repository into the production environment. To set up the repository CI/CD strategy: 1. In the production Org, set up accounts. 2. In the dev/test Org, create a project. 3. Create a new branch in your repository. 4. In the dev/test Org, make the required changes. 5. Commit the changes. 6. Create a pull request to review and test the changes. 7. Merge the pull request with the main branch. 8. Associate a tag with the latest files in the main branch. 9. In the production environment, perform a pull using the defined tag. Accounts with the same name across all Orgs are considered the same account. To undo, perform a pull using a tag defined for an earlier version of the main branch files. Concurrent Editing The concurrent editing CI/CD strategy allows changes from multiple branches to be merged into a single branch which is deployed to the production environment. To set up the concurrent editing CI/CD strategy, set up a CI/CD workflow that is automatically triggered whenever the main branch is updated. The CI/CD workflow performs a pull of the updated files into the production environment. Each user performs the following: 1. Create a new project in their own project space. 2. Create a new branch in the repository for their own project. 3. Make the required changes. 4. Commit the changes. 5. Create a pull request to review and test the changes. An admin reviews the pull requests and merges them into the main branch. The merge triggers the automated CI/CD workflow which copies the changes from the main branch to the production environment.
__label__pos
0.915919
0 How do I redefine the image anchor in tikz? For example I would like the position the text "Top Left" on the north west corner of the image and the "Top Right" on the north east. The following code I have positions them both on the north west. \documentclass{article} \usepackage{amsmath} \usepackage{mathtools} \usepackage{tikz}% loads graphicx \begin{document} \begin{tikzpicture} \node[anchor=north west,inner sep=0] (image) at (0,0) {\includegraphics{example-image-a}}; \begin{scope}[anchor=north west] \node[draw,fill=white] at (0,0) {Top Left}; \end{scope} \begin{scope}[anchor=image.north east] \node[anchor=north east,draw,fill=white] at (0,0) {Top Right}; \end{scope} \end{tikzpicture} \end{document} enter image description here But I would like it anchored on the north east of the image enter image description here 1 Answer 1 3 Like this? enter image description here For this you not need to use scope, nodes at upper corners of figure you can insert without them: \documentclass{article} \usepackage{tikz}% loads graphicx \begin{document} \begin{tikzpicture}[ lbl/.style = {draw, outer sep=2\pgflinewidth, fill=white} ] \node[anchor=north west,inner sep=0] (image) {\includegraphics{example-image-a}}; % \node[lbl,below right] at (image.north west) {Top Left}; \node[lbl,below left] at (image.north east) {Top Right}; \end{tikzpicture} \end{document} Edit: or with defining of labels anchors: \documentclass{article} \usepackage{tikz}% loads graphicx \begin{tikzpicture}[ lbl/.style = {draw, outer sep=2\pgflinewidth, fill=white, anchor=#1} ] \node[anchor=north west, inner sep=0] (image) {\includegraphics{example-image-a}}; % \node[lbl=north west] at (image.north west) {Top Left}; \node[lbl=north east] at (image.north east) {Top Right}; \end{tikzpicture} \end{document} Result is the same as before. You must log in to answer this question. Not the answer you're looking for? Browse other questions tagged .
__label__pos
1
Do I have to implement Flux.testmode! for my own models? Hi, I implemented a U-Net and would like to switch between train and test mode for the BN layers. struct Unet encoder # tuple of chains decoder # tuple of UpBlocks segmentation_head # normal conv layer end Flux.@functor Unet ... As of now testmode!(unet) just returns the input with nothing changed. Do I have to manually implement it for the building blocks and the model itself or is there some smart way to circumvent this? Some models are simply not a Chain in their structure… Edit: By chance I found this issue, which suggests that I have to do so. Can the user somehow be warned if testmode! changes nothing? As I mentioned on the issue thread, the straightforward fix would be to recurse via trainable in testmode! so that it automatically works with functors. However, this would mean that most of the recursive calls are no-ops, so warning on them would likely generate a great deal of superfluous warnings.
__label__pos
0.84606
1. 8.2.x core/modules/field/field.module field 2. 8.0.x core/modules/field/field.module field 3. 8.1.x core/modules/field/field.module field 4. 8.3.x core/modules/field/field.module field 5. 7.x modules/field/field.module field Attaches custom data fields to Drupal entities. The Field API allows custom data fields to be attached to Drupal entities and takes care of storing, loading, editing, and rendering field data. Any entity type (node, user, etc.) can use the Field API to make itself "fieldable" and thus allow fields to be attached to it. Other modules can provide a user interface for managing custom fields via a web browser as well as a wide and flexible variety of data type, form element, and display format capabilities. The Field API defines two primary data structures, FieldStorage and Field, and the concept of a Bundle. A FieldStorage defines a particular type of data that can be attached to entities. A Field is attached to a single Bundle. A Bundle is a set of fields that are treated as a group by the Field Attach API and is related to a single fieldable entity type. For example, suppose a site administrator wants Article nodes to have a subtitle and photo. Using the Field API or Field UI module, the administrator creates a field named 'subtitle' of type 'text' and a field named 'photo' of type 'image'. The administrator (again, via a UI) creates two Field Instances, one attaching the field 'subtitle' to the 'node' bundle 'article' and one attaching the field 'photo' to the 'node' bundle 'article'. When the node storage loads an Article node, it loads the values of the 'subtitle' and 'photo' fields because they are both attached to the 'node' bundle 'article'. • Field Types API: Defines field types, widget types, and display formatters. Field modules use this API to provide field types like Text and Node Reference along with the associated form elements and display formatters. File core/modules/field/field.module, line 27 Attach custom data fields to Drupal entities. Functions Namesort descending Location Description field_cron core/modules/field/field.module Implements hook_cron(). field_entity_bundle_delete core/modules/field/field.module Implements hook_entity_bundle_delete(). field_entity_bundle_field_info core/modules/field/field.module Implements hook_entity_bundle_field_info(). field_entity_field_storage_info core/modules/field/field.module Implements hook_entity_field_storage_info(). field_help core/modules/field/field.module Implements hook_help().
__label__pos
0.918241
This is an archived post. You won't be able to vote or comment. all 6 comments [–]amanojaku 1 point2 points  (4 children) Wes's poles are 1 and 2. Andy's are 3 and 4. Write down the possible combination of all results: Hook one Hook 2. 1 & 2 3 & 4 1 & 3 2 & 4 keep going until you have done all possible combo's. Then count the results that will give you a correct pair and divide it by the total number of possible results. [–]mrcj22[S] 1 point2 points  (3 children) Thanks, I actually just figured it out! [–]amanojaku 1 point2 points  (2 children) What did you get? [–]mrcj22[S] 0 points1 point  (1 child) 1/3 and (1/5)*(1/3). [–]amanojaku 1 point2 points  (0 children) That's it, well done. [–]mrcj22[S] 0 points1 point  (0 children) Got it: answers are 1/3 and (1/5)*(1/3).
__label__pos
0.78074
Perimeter of an Ellipse (HP-42S) #1 00 { 48-Byte Prgm } 01>LBL "P" 02 RCL- ST Y 03 X<>Y 04 RCL+ ST L 05 / 06 LASTX 07 PI 08 * 09 X<>Y 10 X^2 11 STO ST Z 12 4 13 + 14 RCL* ST Z 15 RCL* ST Z 16 -3 17 * 18 256 19 / 20 R^ 21 4 22 / 23 1 24 - 25 1/X 26 - 27 * 28 .END. Exact formula: p = 4*a*E(1-b^2/a^2) where E(x) is the complete elliptic integral of the second kind a is the semi-major axis and b is the semi-minor axis Example: a = 2, b = 1 p = 4*2*E(3/4) = 9.68844822054767619842850319639... http://www.wolframalpha.com/input/?i=4*2*E%281-1%2F4%29 Approximate formula: p ~ pi*(a + b)*(4/(4-h) - 3/256*h^2*(4 + h)) where h = ((a - b)/(a + b))^2 The approximate formula is a rework of the Infinite Series 2 in this reference, whose terms are a subset of the infinite series SUM(k=0,inf,(h/4)^k), which converges to 4/(4-h). The resulting expression is 4/(4-h) - 3/64*h^2 - 3/256*h^3 - 39/16384*h^4 - 15/65536*h^5 + 185/1048576*h^6 ... This was done by hand and haven't been doublechecked. Anyway, the approximation formula above uses only terms up to h^3. The percent error ranges from 0% (circle) to about 0.1% in the worst case (two coincidental lines). +-----+-----+---------------+---------------+ | a | b | approximate | exact | +-----+-----+---------------+---------------+ | 1 | 0 | 4.00471251023 | 4.00000000000 | | 2 | 1 | 9.68845167284 | 9.68844822055 | | 3 | 2 | 15.8654396854 | 15.8654395893 | | 4 | 3 | 22.1034921699 | 22.1034921607 | | 5 | 4 | 28.3616678905 | 28.3616678890 | | 5 | 5 | 31.4159265359 | 31.4159265359 | +-----+-----+---------------+---------------+ Thanks Eduardo Duenez for his recent post below. Edited to fix a typo per Ernie's observation below Edited again to correct an error in the parameter of the elliptic function per Eduardo's observatin below Edited: 24 May 2013, 4:44 p.m. after one or more responses were posted #2 I don't have an HP-42S, but you may be able to improve on this by computing the line integral from 0 to pi/2 using the numeric integrator on the 42S p = 4 * a * integral(sqrt(1-(a*a-b*b)/(a*a)*sin^2(t), t, 0, pi/2) http://www.wolframalpha.com/input/?i=4+*+3+*+integrate+sqrt%281-%283*3-2*2%29%2F%283*3%29*sin%5E2%28t%29%29%2Ct%2C0%2Cpi%2F2 BTW quoted "exact" answer for a=3,b=2 should be 15.8654395893 not 15.8654396893 #3 Problem is numerical integration is rather slow to full accuracy on the HP-42S, but I'll check this later. Quote: BTW quoted "exact" answer for a=3,b=2 should be 15.8654395893 not 15.8654396893 Fixed, thanks! #4 Quote: I don't have an HP-42S, but you may be able to improve on this by computing the line integral from 0 to pi/2 using the numeric integrator on the 42S p = 4 * a * integral(sqrt(1-(a*a-b*b)/(a*a)*sin^2(t), t, 0, pi/2) The drawback is a somewhat long running time, but that's an option. Regards, Gerson. 00 { 41-Byte Prgm } 01>LBL "E2" 02 MVAR "A" 03 MVAR "B" 04 MVAR "T" 05 4 06 RCL* "A" 07 1 08 1 09 RCL "B" 10 RCL/ "A" 11 X^2 12 - 13 RCL "T" 14 SIN 15 X^2 16 * 17 - 18 SQRT 19 * 20 .END. LLIM = 0 ULIM = 1.5707963268 (pi/2) ACC = 0.0000000010 +-----+-----+---------------+------+ | a | b | integral | t(s) | +-----+-----+---------------+------+ | 1 | 0 | 3.99999999999 | 44.9 | | 2 | 1 | 9.68844822056 | 45.6 | | 3 | 2 | 15.8654395893 | 46.2 | | 4 | 3 | 22.1034921608 | 45.7 | | 5 | 4 | 28.3616678889 | 45.8 | | 5 | 5 | 31.4159265360 | 2.9 | +-----+-----+---------------+------+ #5 Hi. Good stuff! Here's another way i found a while back, using a variation of arithmetic and geometric means. The iteration is fairly rapid and small to code. This program is in C, but i hope you can see the method: #include <math.h> #include <stdio.h> double agm2(double b) { double s = (1 + b*b)/2; double a = 1; double t = 1; for (;;) { double a1 = (a + b)/2; if (a == a1) break; double c = (a - b)/2; b = sqrt(a*b); a = a1; s = s - t*c*c; t = t * 2; } return s/a; } #define _PI 3.141592653589793238462643 double ellipse(double a, double b) { // perimeter of an ellipse // a semi-major axis // b semi-minor axis // e = eccentricity = sqrt(1-(b/a)^2) // p = 4*a*E(e) // use AGM variant return 2*_PI*a*agm2(b/a); } #6 Quote: Exact formula: p = 4*a*E((a + b)/(a + b*(b + 1))) where E(x) is the complete elliptic integral of the second kind a is the semi-major axis and b is the semi-minor axis The above is not the correct relation between the complete elliptic integral E(x) and the perimeter p(a,b) of the ellipse. The argument "x" (usually denoted k, "the modulus") of E(k) is dimensionless, whereas (a+b)/(a+b(b+1)) is not. The correct relation is p(a,b) = 4*a*E(c/a) where a is the major semiaxis and c = sqrt(a^2-b^2) is the focal semidistance (so c/a is the eccentricity of the ellipse). Note that c/a is dimensionless. Eduardo EDIT: Coincidentally enough, Hugh Steers' C program above (posted as I was writing this, a few minutes earlier) documents the correct relation as well. Edited: 24 May 2013, 11:25 a.m. #7 The algorithm used in Hugh Steers' C program is Semjon Adlaj's, upon which my earlier post for the WP34s is based. (As an academic I feel the urge to always credit original ideas to their source.) Eduardo #8 Quote: Quote: Exact formula: p = 4*a*E((a + b)/(a + b*(b + 1))) where E(x) is the complete elliptic integral of the second kind a is the semi-major axis and b is the semi-minor axis The above is not the correct relation between the complete elliptic integral E(x) and the perimeter p(a,b) of the ellipse. The argument "x" (usually denoted k, "the modulus") of E(k) is dimensionless, whereas (a+b)/(a+b(b+1)) is not. The correct relation is p(a,b) = 4*a*E(c/a) I'd found the formula p(a,b) = 4*a*E(pi/2,e), where e is the eccentricity, sqrt(1 - (b/a)^2) However, trying this on WolframAlpha for a = 3 and b =2 I get 14.567698609052450048.. instead of 15.865439589290589791.. http://www.wolframalpha.com/input/?i=4*3*E%28pi%2F2%2Csqrt%281-%282%2F3%29%5E2%29+%29 Oddly enough my wrong parameter works when the difference between a and b is 1 (at least for integer values) and when a = b or one of the semi-axis is 0, as in all of my examples. I should have tried a = 5 and b = 3, for instance, for which it fails. I wasn't able to find the right WolframAlpha syntax for this function. As soon as I find it, I will correct my original post. Thanks again. Gerson. #9 Thanks for the C code, Hugh! I am not proficient in C, but this appears to be easier to follow than RPL code. Anyway, my goal is a simple and short approximation formula that is accurate enough for practical cases, something that would give an error of a few meters in the length of the Earth's orbit for instance and takes about 20 or so steps on the HP-42S and no more than 1 second to run. Perhaps the approximate formula above meets this goal, but I haven't checked yet. Other approximate formulas are welcome, in case anyone knows about them (I've found only a few -- it appears measuring ellipses is not a popular sport :-) Gerson. #10 To add a log to the fire, here´s the program on the 41 + SandMath: Assumes a in Y and b in X, where ELI2 is the Incomplete Elliptic Integral of the second kind.- 01 LBL "ELIPER" 02 X^2 03 CHS 04 X<>Y 05 STO 05 06 X^2 07 + 08 SQRT 09 RCL 05 10 / 11 90 12 DEG 13 ELI2 14 RCL 05 15 * 16 4 17 * 18 RCL 05 19 * 20 END For a=3, b=2 I get: p = 14.56769861 in 1.8 seconds on the CL (gotta love this machine :-) Cheers, 'AM #11 Hi Ángel, What is the physical meaning of this result? Not the perimeter, I presume. That should be about 15.9, according to the best approximations I've seen. Regards, Gerson. #12 This is what happens when rushing thru not paying attention to the details:- I checked the formula and corrected the program accordingly, the result is now as yours: http://www.wolframalpha.com/input/?i=perimeter+of+ellipse 01 LBL "ELIPER" 02 X<>Y 03 STO 05 04 / 05 X^2 06 CHS 07 1 08 + 09 90 10 DEG 11 LEI2 12 RCL 05 13 ST+ X 14 * 15 ST+ X 16 END 3, ENTER^, 2, XEQ"ELIPER" --> 15,86543959 Cheers, 'AM Edited: 24 May 2013, 4:24 p.m. #13 Thanks, Ángel! The parameter required by WolframAlpha is the square of the eccentricity, not the eccentricity. That's what I was doing wrong. Cheers, Gerson. #14 Quote: I'd found the formula p(a,b) = 4*a*E(pi/2,e), where e is the eccentricity, sqrt(1 - (b/a)^2) However, trying this on WolframAlpha for a = 3 and b =2 I get 14.567698609052450048.. instead of 15.865439589290589791.. http://www.wolframalpha.com/input/?i=4*3*E%28pi%2F2%2Csqrt%281-%282%2F3%29%5E2%29+%29 I know why. The documentation linked to from Wolfram Alpha is inconsistent with Mathematica's definition. What Wolfram Alpha's EllipticE(.) takes as an argument is the modulus k *squared*, and *not* k (in other words the eccentricity *squared*). The convention used by W.Alpha is the one used by the function elliptic_ec(m) in venerable open-source program Maxima as correctly documented at: http://maxima.sourceforge.net/docs/manual/en/maxima_16.html Try: http://maxima-online.org/#?in=4*3*elliptic_ec%20(5.0%2F9)%0A%20%09 Eduardo #15 Quote: What Wolfram Alpha's EllipticE(.) takes as an argument is the modulus k *squared*, and *not* k (in other words the eccentricity *squared*). Yes, we'd just found that out too (see my reply to Ángel above). Thanks again! Gerson. #16 Exactly, so beating this dead horse just once more, this is the correct syntax for WolframAlpha: 4*3*E(pi/2,(1-(2/3)^2) ) [url:http://www.wolframalpha.com/input/?i=4*3*E%28pi%2F2%2C%281-%282%2F3%29^2%29+%29] Best, ÁM Edited: 25 May 2013, 1:41 a.m. #17 In your program ELC you use both, the built-in routine AGM and your own program MAG which implements N(x), the modified arithmetic-geometric mean of 1 and x from the paper you mentioned. However Hugh Steers' program uses just one method agm2 to calculate the perimeter of the ellipse. I see that numerically both methods produce the same result but I don't understand how Hugh's method is related to the paper you cited. Could you explain that? Kind regards Thomas Possibly Related Threads... Thread Author Replies Views Last Post   42s questions and 42s vs 35s snaggs 13 4,059 09-19-2011, 02:44 AM Last Post: snaggs Forum Jump:
__label__pos
0.725966
All Questions Filter by Sorted by Tagged with 2 votes 1answer 62 views Solving complex differential equation with ParametricNDSolveValue I am trying to solve a complex differential equation for the function $S(u,v)$ depending on the parameter $\omega$. The code is: ... 3 votes 1answer 105 views Cryptic NDSolve::nlnum when working with matrices This problem was initially formulated in quaternions, but I had to rewrite them to complex matrices (as they seem to be supported better). Possibly introducing some errors along the way. So the ... 1 vote 0answers 43 views Ordinary differential equation in the real domain If I have the following equation (y - 1) ^5 == 32 I can select the real solution with Solve[(y - 1) ^5 == 32, x, Reals] Now, I ... 2 votes 2answers 190 views Removing numerically vanishing complex part within NDSolve [closed] I am using functions that are only well-defined for real values (e.g. HeavisideTheta) within NDSolve. Internally ... 0 votes 0answers 59 views How to deal with first order complex differential equation? I am trying to solve these two equations but find an error of fewer than the dependent variable and list of replacement rules nor a valid dispatch table, and so cannot be used for replacing. I don't ... 0 votes 1answer 72 views Can I simplify a PDE with Mathematica? I'm a beginner in Mathematica and I search for help with a calculation problem with some derivatives and basic operations. I need to simplify a PDE that depends of a smooth function $f:U\subset\... 1 vote 1answer 37 views Issue with Compile for Complex Input/Output I'm writing a Runge-Kutta algorithm for solving a system of coupled differential equations. My code works fine when defined as a module, but when I try to compile it, I get the following error: ... 1 vote 1answer 81 views How to solve first order complex differential equation? I want to solve these differential equations and want to get the value of 'a1'. I used this code given below but it is not showing any result. If anyone can resolve this will be appreciated. ... 1 vote 0answers 34 views Solving ODEs in the Complex Plane for General z I saw with the new 12.0 update, they have introduced expanded functionality for solving complex ODEs. In the given example, they solve for $y(t)$ and plot results using the new ... 1 vote 1answer 46 views Using AbsArgPlot on parametricNDSolve output [closed] I have solved following equation using ParametricNDSolve $$ \frac{\mathrm d^2y}{\mathrm dx^2} + \left(a + \frac{2}{\pi} b\ \arctan x\right)y = 0 $$ ... 1 vote 0answers 30 views Errors in NDSolve for complex matrices This is the problem. It is quite simple, and looks unwieldy only because I had to rewrite quaternions as complex matrices. ... 0 votes 0answers 50 views I want to plot root of the following complex equation I am trying to plot the roots of the following equation as mentioned in the code below But it is not giving me output. If anyone can resolve this problem for me is most welcome. ... 0 votes 1answer 65 views How to substitute by NDSolve solution to plot a new function Assume I got some function by NDSolve , like y(t) ... 0 votes 1answer 122 views How to chop a complex number? I'm solving some differential equations by iterating and I want to use Chop to get rid of noice smaller than a certain threshold. However, I found that Chop only "chops" the real part, not the ... 3 votes 1answer 124 views Problem with complex eigenvalues in periodic Sturm-Liouville problem I'm having trouble using NDEigenvalues to obtain the first few eigenvalues for a differential operator on the circle of radius one-half. $\qquad Lf(x) = f''(x)+ (-... 3 votes 1answer 248 views How to solve PDE with periodic and anti-periodic b.c.? I need to solve the PDE for a complex function $A(x,t)=A_r(x,t)+iA_i(x,t)$ ... 3 votes 2answers 144 views Complex solutions to ODEs How do I solve the following IVP problem in Mathematica so that I get real solutions? $Q'(t)=b - \dfrac{Q(t)}{100-t}; \quad Q(0)=250$ I tried the following: $\text{$\$$Assumptions}=b>0;\text{$\$$... 3 votes 1answer 176 views Complex first-order differential equation I have a differential equation $\frac{dx}{dt} = \sqrt{1+x^4}$ $x$ is a complex variable. I want to solve it for some given initial condition, and plot the solution (real part vs. imaginary part). ... -3 votes 3answers 177 views Gives me a complex solution [closed] A := DSolve[{D[((It - Ir) * x / L + Ir) * w''[x], {x, 2}] - p/Y, w[x] == 0, w'[0] == 0, w''[L] == M0/(Y*Ir), w'''[L] == -P/(Y*Ir)}, w[x], x] I want a real ... 10 votes 1answer 284 views FiniteElement v.s. TensorProductGrid: which is reliable for Schrödinger equation with periodic b.c.? This is a problem comes up in the discussion under this post and I think it's worth starting a new question for it. I suspect the underlying issue is the same as in this post, but not sure. Consider ... 3 votes 3answers 279 views Problem of `Integrate` and `DSolve` with inhomogeneous Legendre differential equation I have the following inhomogeneous Legendre differential equation $(m=n=2)$: ... 7 votes 2answers 196 views Portion of Curve Omitted by Plot In the course of addressing question 104559, I encountered the following problem with Plot. Begin with ... 2 votes 3answers 507 views How to take derivative of the argument of an interpolating function I am trying to plot the derivative of the argument of an interpolating function u[t, x] with respect to $x$. Here, u[t, x] is ... 0 votes 0answers 54 views How can I eliminate InverseLaplaceTransform returning complex I tried this: F = InverseLaplaceTransform[ 1/((1 + s^2) (1 + (s + 1/2)^2)) + Exp[-Pi*s]*1/((1 + s^2) (1 + (s + 1/2)^2)), s, t] But it returns an answer ... 6 votes 2answers 359 views How to solve this trigonometric complex ODE system? The system of nonlinear ODE is $$ \mathrm{i}\,s(\ddot p-\frac{1}{2}\sin{2p}\;\dot q^2)=\mathrm{i}\,c\sin p\;\dot q-a\sin p+b\cos p\cos q\,,\\ \mathrm{i}\,s(\sin^2p\;\ddot q+\sin{2p}\;\dot p\dot q)=-\... 2 votes 2answers 215 views DSolve Solutions are sometimes not as simple as they could be Why doesn't DSolve output a solution in a nice format? DSolve[y'[x] == (x + y[x] + 3)^2, y[x], x] ... 3 votes 2answers 143 views How to make an organised investigation of branch cuts from a solution to a differential equation I am attempting to solve two differential equations. The solution gives equations that have branch cuts. I need to choose appropriate branch cuts for my boundary conditions. How do I find the correct ... 1 vote 1answer 361 views NDSolve error (not a real number when the arguments are?) For the NDSolve, I have problem. It seems to be non-zero imaginary part of the number. How can I get over this issue? The following is the script. ... 4 votes 1answer 481 views Orbit followed by a particle around Schwarzschild Black Hole The following is a equation which describes various possible orbits of a particle around the Schwarzschild black hole spacetime in general relativity. I want to solve it from ... 1 vote 0answers 162 views Chop intermediate results of NDSolve after each step [closed] Using NDSolve for a set of three ordinary differential equations, I ran into the problem that intermediate results quickly develop negligible imaginary parts. I get ... 0 votes 2answers 1k views Bifurcation with a system of equations I'm trying to plot a flip bifurcation diagram for a dynamical system of equations as follows: x'[t] == v[t] v'[t] == x[t] - A x[t]^3 + R*Cos[ω*t] - B v[t] but am ... 1 vote 0answers 86 views Instructing DSolve not to return answers with explicit complex numbers DSolve sometimes returns solutions containing explicit complex numbers, even though the ODE does not. For instance (drawn from question 126072), ... 6 votes 2answers 320 views Second order differential equation of a complex function I am curious about whether Mathematica can help me solve a second order differential equation of a function in the complex plane. The equation that I am looking to solve is: $\dfrac{d^2}{dz^2}(u+iv) ... 2 votes 1answer 207 views FiniteDifferenceDerivative of complex function in 2D--bug? I want to compute partial derivatives of complex functions via finite difference approximation on two dimensional grid using NDsolve`FiniteDifferenceDerivative ... 9 votes 1answer 436 views NDSolve for complex BVPs and FindRoot NDSolve works for complex valued ODE initial value problems (IVP). However, for a simple boundary value problem (BVP) with complex coefficients it fails: ... 1 vote 1answer 428 views NDSolve for complex variables I am trying to simulate a multiple pendulum system with damping as follows: ... 2 votes 3answers 283 views NDSolve and differentiation of Abs I have found several questions about the derivative of Abs and how it is not defined in the complex plane. What I have not found yet is a precise and simple ... 7 votes 1answer 312 views Confirming conservation laws for complex valued functions Consider the nonlinear Schrödinger equation (I would like to do this for a more complicated set of equations, but to gain understanding I'll consider this simplified case) $$A_t+iA_{xx}+i|A|^2A =0,$$ ... 3 votes 0answers 110 views Solving a differential equation with a complex (independent) varible I'm trying to plug in complex values in the numerical solutions of ODEs without success. For instance y[I] /. NDSolve[{y'[x] == 0, y[0] == 3}, y, {x, -10, 10}] ... 2 votes 1answer 4k views Solving a complex-valued differential equation with NDSolve I am trying to solve $dx/dt=\sqrt{1+(ix)^{1.8}}$ for initial condition $x[0] =-0.9877 + i 0.1563$, where $x$ is a complex variable. I would like to plot the imaginary part of the solution versus the ... 1 vote 0answers 863 views Differential equations with a complex variable Is Mathematica able to handle ordinary differential equations where the variable itself is complex? I am looking for solutions of ODE systems of the form $$\left\{ \begin{align} i\frac{da_1}{dt} &=... 5 votes 1answer 2k views How to plot the solution of a Partial Differential Equation? My attempt. I need to solve numerically the Complex Ginzburg-Laudau Equation (CGLE): $$ \frac{\partial A}{\partial t}=\epsilon A-(1+i\beta)|A|^2A+(1+i\alpha)\nabla^2A $$ I'm using a uniform initial ... 4 votes 1answer 2k views Real and Imaginary parts of solutions to a complex linear ODE system Consider a complex linear ODE system $x'=Ax$, where $$A=\left( \begin{matrix} 0&1\\ -2&-i \end{matrix}\right). $$ One can first find the eigenvalues and eigenvectors using ... 3 votes 1answer 697 views Differential Equation in Complex Plane and Parametric Plot I would like to solve $dx/dt=\sqrt{1 + (I x)^3}$, where x is complex, for some initial condition like $1 - 5 I$ and plot the imaginary part of the solution versus the real part. (A somewhat similar ... 1 vote 2answers 938 views Complex differential equation I want to solve $dx/dt=\sqrt{(1-x^2)}$, where $x$ is complex. When I solve it by hand and analytically for some initial value and draw the imaginary part versus the real part, I obtain an ellipse, as ... 13 votes 1answer 5k views Bifurcation diagrams for multiple equation systems I am interested in constructing a bifurcation diagram for some of my parameters (especially for β and γ) in the dynamical system given in the code below. I want to see how parameter changes affect the ...
__label__pos
0.853998
42 $\begingroup$ I was thinking about the best way to include Mathematica code in a $\LaTeX$ document with a nice syntax highlighting. I have tried the packages listings and minted (with pygments), which both claim to include Mathematica syntax highlighting. There is also a separate Mathematica lexer for pygments on github. Having looked at the output from these packages, I'm not entirely happy. I was hoping to obtain a result resembling as closely as possible Mathematica's native syntax highlighting or the highlighting used here on mma.SE (is that halirutan's prettify extension?) My question is: What are users' preferred ways to include Mathematica code in $\LaTeX$ files that preserve syntax highlighting? $\endgroup$ • 1 $\begingroup$ possible duplicate of Saving a notebook as a $\LaTeX$ file, with syntax highlighting preserved $\endgroup$ – Dr. belisarius Feb 23 '14 at 21:27 • 1 $\begingroup$ Thanks for the link @belisarius: The answer in that thread concludes with "This code reduces your problem to implementing the syntax highlighter in Mathematica, or finding a LATEX package to do it for you" which is precisely what I'm asking for. I'm happy to manually copy and pasty Mathematica expressions into a LaTeX file, a process that the linked thread seems to automate. $\endgroup$ – Eckhard Feb 23 '14 at 21:34 • 2 $\begingroup$ @Eckhard The short answer is: there is no such thing, because the highlighting as done by Mathematica requires a lot of work which is not done by any of the listing, minted, etc packages. Even the highlighter on SE that I wrote is only faking, especially the highlighting for pattern variables will not work reliably. The best way I see is to use my IDEA plugin and write an action to export highlighted and indented code. In IDEA, I have everything at hand and the complex highlighting is real. $\endgroup$ – halirutan Feb 24 '14 at 4:35 • 3 $\begingroup$ @Eckhard This is because the IDEA plugin understand Mathematica syntax and semantic and can highlight and annotate very complex code constructs correctly. The hard part is: Even if I have all characters, their coloring and spaces, then this needs to be converted to colored LaTeX text where every character appears exactly as I want. I had already a look into the listing package and creating such output in TeX goes really beyond my user knowledge of TeX. $\endgroup$ – halirutan Feb 24 '14 at 4:39 • 2 $\begingroup$ If I had the knowledge how to convert annotated code text into TeX commands so that the output is correct, one could use IDEA to copy Mathematica code there, autoamtically indent it correctly and then with one key-press you would have the LaTeX code in your clipboard ready to paste it into your document. $\endgroup$ – halirutan Feb 24 '14 at 4:42 24 $\begingroup$ I too had a need for a better syntax highlighting engine for Mathematica that can be used in different formats (so the javascript plugin is ruled out), so I wrote a better lexer and highlighter for Pygments than the one that ships with pygments. From the README: It can currently lex and highlight: • All builtin functions in the System` context including unicode symbols like π except those that use characters from the private unicode space (e.g. \[FormalA]) • User defined symbols, including those in a context. • Comments, including multi line and nested. • Strings, including multi line and escaped quotes. • Patterns, slots (including named slots #name introduced in version 10) and slot sequences. • Message names (e.g. the ivar in General::ivar) • Numbers including base notation (e.g. 8 ^^ 23 == 19) and scientific notation (e.g. 1 *^ 3 == 1000). • Local variables in Block, With and Module. Installing it is as simple as executing pip install pygments-mathematica. Here's an example of using it in a $\LaTeX$ document: \documentclass{article} \usepackage[english]{babel} \usepackage{fontspec} \setmonofont{Menlo} \usepackage{minted} \usemintedstyle{mathematica} \begin{document} \begin{minted}[linenos=true]{wolfram} (* An example highlighting the features of this Pygments plugin for Mathematica *) lissajous::usage = "An example Lissajous curve.\n" <> "Definition: f(t) = (sin(3t + Pi/2), sin(t))" lissajous = {Sin[2^^11 # + 0.005`10 * 1*^2 * Pi], Sin[#]} &; ParametricPlot[lissajous[t], {t, 0, 2 Pi}] /. x_Line :> {Dashed, x} \end{minted} \end{document} Assuming the file is called mma.tex, run xelatex --shell-escape mma.tex to generate a pdf that looks like this: mma latex screenshot The style mathematica is shipped with this plugin and if you'd like to change the colors, you can just update them in mathematica/style.py and then (re)install the plugin. If you like the default notebook colors, you can use the style mathematicanotebook. $\endgroup$ • $\begingroup$ Note that the displayed colors are not the default ones used in Mathematica. E.g., by default the entire definition of the usage message, except for the beginning lissajous::, is colored a gray shade; the numbers on the right-hand side of the definition of lissajous are by default black. Do you have a set of color definitions consistent with what Mathematica actually uses by default? $\endgroup$ – murray Feb 15 '16 at 15:36 • $\begingroup$ @murray I'm aware and it was a conscious decision to not stick to the default Mathematica style too closely. I don't think primary colors do well in latex documents/HTML where you don't have the luxury of pressing F1 or Ctrl-W as in the notebook. Besides, using gray for ::bar, (* comment *) and "a string" is confusing as well. It is easy to change the colors though. If there is sufficient interest for it, I can even provide a theme mathematica-default that uses the exact default palette from the notebook. $\endgroup$ – rm -rf Feb 15 '16 at 15:46 • 1 $\begingroup$ You mention \[FormalA], and without having tried it, I think this will also mean \[Element] doesn't get displayed correctly, doesn't it? I had the same issue in the listings package but figured out how to fix it there (by escaping to $\LaTeX$). I wonder if one can fix this in your approach to get nicer display of such glyphs... it does improve readability a lot. (already upvoted without trying - I definitely will give it a shot soon). $\endgroup$ – Jens Feb 15 '16 at 17:58 • 1 $\begingroup$ @Jens It's coming soon... I'll make the release sometime tomorrow :) $\endgroup$ – rm -rf Feb 16 '16 at 6:23 • 1 $\begingroup$ @Jens Thanks for the feedback. I'll add the \[...] to unicode mapping in the next release :) $\endgroup$ – rm -rf Feb 21 '16 at 14:47 13 $\begingroup$ To get syntax highlighting for Mathematica in a latex code listing, try this: \usepackage{listings} \usepackage{color} \definecolor{listinggray}{gray}{0.9} \definecolor{graphgray}{gray}{0.7} \definecolor{blue}{rgb}{0,0,1} \definecolor{mygreen}{rgb}{0,0.6,0} \definecolor{mygray}{rgb}{0.5,0.5,0.5} \definecolor{mymauve}{rgb}{0.58,0,0.82} % define a custom mathematica language for syntax highlighting \lstdefinelanguage{myMMA}{ keywords={SetDirectory, NotebookDirectory, Exp, IdentityMatrix, Eigenvalues, ListPlot, PlotRange, PlotStyle, Directive, PointSize, AspectRatio, Blue, Graphics, Line, Manipulate, Show, Sqrt, UniformDistribution, GammaDistribution, BetaDistribution, Nintegrate, For, DataRange, AxesLabel, PlotLabel, Transpose, Export, Plot, Append, Infinity}, keywordstyle=\color{black}, commentstyle=\color{gray}, stringstyle=\color{mymauve}, identifierstyle=\color{blue}, sensitive=false, comment=[l]{(*}, morecomment=[s]{/*}{*/}, morestring=[b]', morestring=[b]" } Keep in mind that the keywords I've listed here are far from exhaustive. I tried to find a list of Mathematica keywords but gave up. So I just used the keywords that I actually used in my code. Edit Here is a list of the keywords in a .txt file: https://www.dropbox.com/s/i3m8do7uof5uval/keywords.txt?dl=0 I found them by using Names["System`*"] $\endgroup$ • 2 $\begingroup$ Have a look at Names. BTW welcome here at Mathematica.SE! You might want to consider changing your user name as it coincides with one of the top users here and it may create some confusion. $\endgroup$ – Sjoerd C. de Vries May 19 '15 at 5:47 • $\begingroup$ Thanks a ton, that was frustrating me. And I'll change the name as soon as SE lets me. $\endgroup$ – Guilty Spark May 19 '15 at 6:02 • $\begingroup$ Actually, you don't need to add all the keywords. The listings package already understands the option language=Mathematica! You just have to add the newest keywords that it doesn't know yet, using, e.g., otherkeywords={DiscretizeRegion}. $\endgroup$ – Jens Feb 15 '16 at 17:51 • 1 $\begingroup$ @Jens: Can you show a short but complete example of using the listings package for Mathematica that will produce syntax coloring. I tried it, being sure to load the color package, too, but I only get boldface and gray. $\endgroup$ – murray Feb 21 '16 at 18:22 • $\begingroup$ @murray OK, let me try to make a complete but minimal $\LaTeX$ file. I'll probably post it as a separate answer for space reasons... I use this in bigger files so I have to eliminate some unnecessary customizations, but not too many... $\endgroup$ – Jens Feb 21 '16 at 18:28 9 $\begingroup$ The answer by @R.M. is what I would recommend to anyone who has the ability to install the required prerequisites. But as requested by @murray, here is an example of a complete $\LaTeX$ document that should have all the commands required for use with regular pdflatex (i.e., it doesn't require xelatex): \documentclass[11pt,english]{scrartcl} \usepackage{babel} \usepackage{beramono} \usepackage[T1]{fontenc} \usepackage[latin9]{inputenc} \usepackage{color} \definecolor{identifiercolor}{rgb}{.4,.6,.56} \definecolor{stringcolor}{gray}{0.5} \definecolor{inactivecolor}{rgb}{0.15,0.15,0.5} \usepackage{listings} \lstset{basicstyle={\footnotesize\def\fvm@Scale{.85}\fontfamily{fvm}\selectfont}, breaklines=true, escapeinside={\%*}{*)}, keywordstyle={\bfseries\color{inactivecolor}}, stringstyle={\bfseries\color{stringcolor}}, identifierstyle={\bfseries\color{identifiercolor}}, language=Mathematica, otherkeywords={DiscretizeRegion}, showstringspaces=false} \renewcommand{\lstlistingname}{Listing} \begin{document} Here I tell Mathematica to make a wave function plot: \begin{lstlisting}[extendedchars=true,language=Mathematica] Block[ {region=DiscretizeRegion[Polygon[{{0,0},{-1/2,Sqrt[3]/2},{1/2,Sqrt[3]/2}}]]}, ContourPlot[ 2 Cos[4 Pi x] Sin[(4 Pi y)/Sqrt[3]] - Sin[(8 Pi y)/Sqrt[3]], {x,y} %*$\in$*) region, PlotPoints ->70, Contours ->10, AspectRatio ->Automatic, FrameLabel ->{"x","y"}, PlotLabel ->"Excited state of the equilateral triangle" ] ] \end{lstlisting} To get some characters such as \textbackslash{}[Element] in the output, I manually have to escpape from the listings environment and use the corresponding \LaTeX{} command. \end{document} Save this as listingsExample.tex and run pdflatex listingsExample. Make sure your editor doesn't automatically convert quotes " to $\LaTeX$ code (emacs does this by default). We want the code to be copied verbatim because it's supposed to be a source listing. The output should look like this: PDF screen shot I used the beramono font to get the arrows -> to come out in a form that allows the code to work directly when copied back to Mathematica. With the default font, the arrows look OK in the PDF but don't get translated back correctly inside Mathematica. Also, I use the line basicstyle={\footnotesize\def\fvm@Scale{.85}\fontfamily{fvm}\selectfont}, to switch the font in the listing from serif to something closer to the Mathematica style. This font switching code comes from this answer on TeX.SE by Jubobs. I also added a keyword not yet recognized by the package in its current version, using the line otherkeywords={DiscretizeRegion}. For simplicity, the colors were chosen to look like the notebook display before any evaluation (i.e., keywords are blue). That way, I don't have to think about different colors for symbols that already have values. The line escapeinside={\%*}{*)} defines two character sequences that are recognized as delimiters surrounding the escape to $\LaTeX$ code inside the listings environment. $\endgroup$ • $\begingroup$ @murray I hope this works for you - it's taken directly from a homework assignment I used last year... $\endgroup$ – Jens Feb 21 '16 at 18:59 • $\begingroup$ Ok, that helps. Of course much of the $\text{\LaTeX}$ code you use is unnecessary, e.g., package scrartcl, use of babel ad `beramono, etc. $\endgroup$ – murray Feb 21 '16 at 20:40 • $\begingroup$ The example as shown does not at all color such things as syntax errors (e.g., an unmatched parenthesis or missing bracket). How does one handle those? $\endgroup$ – murray Feb 21 '16 at 20:41 • 1 $\begingroup$ @murray As far as I know it's not possible, because listings is for syntactically correct code only... displaying an active notebook faithfully is probably a job for screen shots - anything else would be too much work. Of course it wouldn't be doable with Pygments, either. Actually - listings could do it if you finger-paint using `$\LaTeX$ escapes. But that's kind of silly. $\endgroup$ – Jens Feb 21 '16 at 20:43 • $\begingroup$ The most useful reason I can think of for using Mathematica syntax coloring in a $\text{LaTeX}$ article is to show how the coloring tells you when something is wrong! $\endgroup$ – murray Feb 21 '16 at 20:55 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.832205
7/7 You deserved it! Why did CodeAcademy write these pieces? #1 I passed this one but wonder what CodeAcademy tutor meant by adding || 0 var cashRegister = { total:0, lastTransactionAmount: 0, add: function(itemCost){ this.total += (itemCost || 0); this.lastTransactionAmount = itemCost; }, and this .toFixed(2) console.log('Your bill is '+cashRegister.total.toFixed(2) #2 I still don't get (itemCost || 0). But toFixed(2) is how many digits you want after the dot. .toFixed(2) = 13.74 .toFixed(3) = 13.744 (you can try and check) #3 This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
__label__pos
0.959488
This topic describes how to use the Go SDK to quickly call API operations to obtain services, create functions, call functions, delete functions, and delete services. Prerequisites Before you begin, make sure that you have completed the following operations: Sample code Sample code: package main import ( "fmt" "os" "github.com/aliyun/fc-go-sdk" ) func main() { serviceName := "service555" client, _ := fc.NewClient(os.Getenv("ENDPOINT"), "2016-08-15", os.Getenv("ACCESS_KEY_ID"), os.Getenv("ACCESS_KEY_SECRET")) fmt.Println("Creating service") createServiceOutput, err := client.CreateService(fc.NewCreateServiceInput(). WithServiceName(serviceName). WithDescription("this is a smoke test for go sdk")) if err ! = nil { fmt.Fprintln(os.Stderr, err) } if createServiceOutput ! = nil { fmt.Printf("CreateService response: %s \n", createServiceOutput) } // Obtain services. fmt.Println("Getting service") getServiceOutput, err := client.GetService(fc.NewGetServiceInput(serviceName)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("GetService response: %s \n", getServiceOutput) } // Update the service. fmt.Println("Updating service") updateServiceInput := fc.NewUpdateServiceInput(serviceName).WithDescription("new description") updateServiceOutput, err := client.UpdateService(updateServiceInput) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("UpdateService response: %s \n", updateServiceOutput) } // Update the service that complies with the IfMatch parameter description. fmt.Println("Updating service with IfMatch") updateServiceInput2 := fc.NewUpdateServiceInput(serviceName).WithDescription("new description2"). WithIfMatch(updateServiceOutput.Header.Get("ETag")) updateServiceOutput2, err := client.UpdateService(updateServiceInput2) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("UpdateService response: %s \n", updateServiceOutput2) } // Update the services that do not comply with the IfMatch parameter description. fmt.Println("Updating service with wrong IfMatch") updateServiceInput3 := fc.NewUpdateServiceInput(serviceName).WithDescription("new description2"). WithIfMatch("1234") updateServiceOutput3, err := client.UpdateService(updateServiceInput3) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("UpdateService response: %s \n", updateServiceOutput3) } // Obtain the service list. fmt.Println("Listing services") listServicesOutput, err := client.ListServices(fc.NewListServicesInput().WithLimit(100)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("ListServices response: %s \n", listServicesOutput) } // Create a function. fmt.Println("Creating function1") createFunctionInput1 := fc.NewCreateFunctionInput(serviceName).WithFunctionName("testf1"). WithDescription("go sdk test function"). WithHandler("main.my_handler").WithRuntime("python2.7"). WithCode(fc.NewCode().WithFiles("./testCode/hello_world.zip")). WithTimeout(5) createFunctionOutput, err := client.CreateFunction(createFunctionInput1) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("CreateFunction response: %s \n", createFunctionOutput) } fmt.Println("Creating function2") createFunctionOutput2, err := client.CreateFunction(createFunctionInput1.WithFunctionName("testf2")) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("CreateFunction response: %s \n", createFunctionOutput2) } // Obtain the function list. fmt.Println("Listing functions") listFunctionsOutput, err := client.ListFunctions(fc.NewListFunctionsInput(serviceName).WithPrefix("test")) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("ListFunctions response: %s \n", listFunctionsOutput) } // Update the function. fmt.Println("Updating function") updateFunctionOutput, err := client.UpdateFunction(fc.NewUpdateFunctionInput(serviceName, "testf1"). WithDescription("newdesc")) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("UpdateFunction response: %s \n", updateFunctionOutput) } // Call a function. fmt.Println("Invoking function, log type Tail") invokeInput := fc.NewInvokeFunctionInput(serviceName, "testf1").WithLogType("Tail") invokeOutput, err := client.InvokeFunction(invokeInput) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("InvokeFunction response: %s \n", invokeOutput) logResult, err := invokeOutput.GetLogResult() if err ! = nil { fmt.Printf("Failed to get LogResult due to %v\n", err) } else { fmt.Printf("Invoke function LogResult %s \n", logResult) } } fmt.Println("Invoking function, log type None") invokeInput = fc.NewInvokeFunctionInput(serviceName, "testf1").WithLogType("None") invokeOutput, err = client.InvokeFunction(invokeInput) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("InvokeFunction response: %s \n", invokeOutput) } // Publish the service version. fmt.Println("Publishing service version") publishServiceVersionInput := fc.NewPublishServiceVersionInput(serviceName) publishServiceVersionOutput, err := client.PublishServiceVersion(publishServiceVersionInput) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("PublishServiceVersion response: %s \n", publishServiceVersionOutput) } // Publish the service version that meets the description of the IfMatch parameter. fmt.Println("Publishing service version with IfMatch") publishServiceVersionInput2 := fc.NewPublishServiceVersionInput(serviceName). WithIfMatch(getServiceOutput.Header.Get("ETag")) publishServiceVersionOutput2, err := client.PublishServiceVersion(publishServiceVersionInput2) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("PublishServiceVersion response: %s \n", publishServiceVersionOutput2) } // Publish a service version that does not meet the description of the IfMatch parameter. fmt.Println("Publishing service with wrong IfMatch") publishServiceVersionInput3 := fc.NewPublishServiceVersionInput(serviceName). WithIfMatch("1234") publishServiceVersionOutput3, err := client.PublishServiceVersion(publishServiceVersionInput3) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("PublishServiceVersion response: %s \n", publishServiceVersionOutput3) } // Obtain the version list. fmt.Println("Listing service versions") listServiceVersionsOutput, err := client.ListServiceVersions(fc.NewListServiceVersionsInput(serviceName).WithLimit(10)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("ListServiceVersions response: %s \n", listServiceVersionsOutput) } // Obtain the services that meet the description of the qualifier parameter. fmt.Println("Getting service with qualifier") getServiceOutput2, err := client.GetService(fc.NewGetServiceInput(serviceName).WithQualifier(publishServiceVersionOutput.VersionID)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("GetService with qualifier response: %s \n", getServiceOutput2) } // Create an alias. aliasName := "alias" fmt.Println("Creating alias") createAliasOutput, err := client.CreateAlias(fc.NewCreateAliasInput(serviceName).WithAliasName(aliasName).WithVersionID(publishServiceVersionOutput.VersionID)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("CreateAlias response: %s \n", createAliasOutput) } // Obtain an alias. fmt.Println("Getting alias") getAliasOutput, err := client.GetAlias(fc.NewGetAliasInput(serviceName, aliasName)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("GetAlias response: %s \n", getAliasOutput) } // Update an alias. fmt.Println("Updating alias") updateAliasOutput, err := client.UpdateAlias(fc.NewUpdateAliasInput(serviceName, aliasName).WithVersionID(publishServiceVersionOutput2.VersionID)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("UpdateAlias response: %s \n", updateAliasOutput) } // Obtain an alias list. fmt.Println("Listing aliases") listAliasesOutput, err := client.ListAliases(fc.NewListAliasesInput(serviceName)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("ListAliases response: %s \n", listAliasesOutput) } // Delete an alias. fmt.Println("Deleting aliases") deleteAliasOutput, err := client.DeleteAlias(fc.NewDeleteAliasInput(serviceName, aliasName)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("DeleteAlias response: %s \n", deleteAliasOutput) } // Delete a service version. fmt.Println("Deleting service version") deleteServiceVersionOutput, err := client.DeleteServiceVersion(fc.NewDeleteServiceVersionInput(serviceName, publishServiceVersionOutput.VersionID)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("DeleteServiceVersion response: %s \n", deleteServiceVersionOutput) } deleteServiceVersionOutput2, err := client.DeleteServiceVersion(fc.NewDeleteServiceVersionInput(serviceName, publishServiceVersionOutput2.VersionID)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("DeleteServiceVersion response: %s \n", deleteServiceVersionOutput2) } // Delete a function. fmt.Println("Deleting functions") listFunctionsOutput, err = client.ListFunctions(fc.NewListFunctionsInput(serviceName).WithLimit(10)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("ListFunctions response: %s \n", listFunctionsOutput) for _, fuc := range listFunctionsOutput.Functions { fmt.Printf("Deleting function %s \n", *fuc.FunctionName) if output, err := client.DeleteFunction(fc.NewDeleteFunctionInput(serviceName, *fuc.FunctionName)); err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("DeleteFunction response: %s \n", output) } } } // Delete a service. fmt.Println("Deleting service") deleteServiceOutput, err := client.DeleteService(fc.NewDeleteServiceInput(serviceName)) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("DeleteService response: %s \n", deleteServiceOutput) } // Configure the reservation. fmt.Println("Putting provision config") putProvisionConfigOutput, err := client.PutProvisionConfig(fc.NewPutProvisionConfigInput(serviceName, "testAliasName", "testFunctionName").WithTarget(int64(100))) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("PutProvisionConfig response: %s \n", putProvisionConfigOutput) } // Obtain the reserved configuration. fmt.Println("Getting provision config") getProvisionConfigOutput, err := client.GetProvisionConfig(fc.NewGetProvisionConfigInput(serviceName, "testAliasName", "testFunctionName")) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("GetProvisionConfig response: %s \n", getProvisionConfigOutput) } // Obtain the reserved configuration list. fmt.Println("Listing provision configs") listProvisionConfigsOutput, err := client.ListProvisionConfigs(fc.NewListProvisionConfigsInput()) if err ! = nil { fmt.Fprintln(os.Stderr, err) } else { fmt.Printf("ListProvisionConfigs response: %s \n", listProvisionConfigsOutput) } }
__label__pos
0.997135
Post cover 5 Handy Applications of JavaScript Array.from() Posted August 27, 2019 Any programming language has functions that go beyond the basic usage. It happens thanks to a successful design and a wide area of problems it tries to solve. One such function in JavaScript is the Array.from(): a workhorse allowing lots of useful transformations on JavaScript collections (arrays, array-like objects, iterables like string, maps, sets, etc). In this post, I will describe 5 use cases of Array.from() that are both useful and interesting. Before I go on, let me recommend something to you. The path to becoming good at JavaScript isn't easy... but fortunately with a good teacher you can shortcut. Take "Modern JavaScript From The Beginning 2.0" course by Brad Traversy to become proficient in JavaScript in just a few weeks. Use the coupon code DMITRI and get your 20% discount! 1. Quick introduction Before starting, let's recall what Array.from() does. Here's how you would call the function: Array.from(arrayLikeOrIterable[, mapFunction[, thisArg]]); It's first obligatory argument arrayLikeOrIterable is an array-like object or an iterable. The second optional argument mapFunction(item, index) {...} is a function invoked on every item in the collection. The returned value is inserted into the new collection. Finally, the third optional argument thisArg is used as this value when invoking mapFunction. This argument is rarely used. For examples, let's multiply by 2 the numbers of an array-like object: const someNumbers = { '0': 10, '1': 15, length: 2 }; Array.from(someNumbers, value => value * 2); // => [20, 30] 2. Transform array-like into an array The first useful application of Array.from() is indicated directly from its definition: transform an array-like object into an array. Usually, you meet these strange creatures array-like objects as arguments special keyword inside of a function, or when working with DOM collections. In the following example, let's sum the arguments of a function: function sumArguments() { return Array.from(arguments).reduce((sum, num) => sum + num); } sumArguments(1, 2, 3); // => 6 Array.from(arguments) transforms the array-like arguments into an array. The new array is reduced to the sum of its elements. Moreover, you can use Array.from() with any object or primitive that implements the iterable protocol. Let's see a few examples: Array.from('Hey'); // => ['H', 'e', 'y'] Array.from(new Set(['one', 'two'])); // => ['one', 'two'] const map = new Map(); map.set('one', 1) map.set('two', 2); Array.from(map); // => [['one', 1], ['two', 2]] 3. Clone an array There is a tremendous number of ways to clone an array in JavaScript. As you might expect, Array.from() easily shallow copies an array: const numbers = [3, 6, 9]; const numbersCopy = Array.from(numbers); numbers === numbersCopy; // => false Array.from(numbers) creates a shallow copy of numbers array. The equality check numbers === numbersCopy is false, meaning that while having the same items, these are different array objects. Is it possible to use Array.from() to create a clone of the array, including all the nested ones? Challenge accepted! function recursiveClone(val) { return Array.isArray(val) ? Array.from(val, recursiveClone) : val; } const numbers = [[0, 1, 2], ['one', 'two', 'three']]; const numbersClone = recursiveClone(numbers); numbersClone; // => [[0, 1, 2], ['one', 'two', 'three']] numbers[0] === numbersClone[0] // => false recursiveClone() creates a deep clone of the supplied array. This is achieved by calling recursively recursiveClone() on array items that are arrays too. Can you write a shorter than mine version of recursive clone that uses Array.from()? If so, please write a comment below! 4. Fill an array with values In case if you need to initialize an array with the same values, Array.from() is at your service too. Let's define a function that creates an array filled with the same default values: const length = 3; const init = 0; const result = Array.from({ length }, () => init); result; // => [0, 0, 0] result contains a new array having 3 items initialized with zeros. This is done by invoking Array.from() with an array-like object { length }, and a map function that returns the initialization value. However, there is an alternative method array.fill() that can be used to achieve the same result: const length = 3; const init = 0; const result = Array(length).fill(init); fillArray2(0, 3); // => [0, 0, 0] fill() method fills the array correctly with initialization values, regardless of empty slots. 4.1 Fill an array with new objects When every item of the initialized array should be a new object, Array.from() is a better solution: const length = 3; const resultA = Array.from({ length }, () => ({})); const resultB = Array(length).fill({}); resultA; // => [{}, {}, {}] resultB; // => [{}, {}, {}] resultA[0] === resultA[1]; // => false resultB[0] === resultB[1]; // => true resultA created by Array.from() is initialized with different instances of empty objects {}. It happens because the map function () => ({}) on every invocation returns a new object. However, resultB created by fill() method is initialized with the same instance of an empty object. 4.2 What about array.map()? Is it possible to use array.map() method to achieve the same? Let's try that: const length = 3; const init = 0; const result = Array(length).map(() => init); result; // => [undefined, undefined, undefined] The map() approach seems to be incorrect. Instead of the expected array with three zeros, an array with 3 empty slots is created. It happens because Array(length) creates an array having 3 empty slots (also called sparse array), but map() method skips the iteration over these empty slots. 5. Generate ranges of numbers You can use Array.from() to generate ranges of values. For example, the following function range generates an array with items starting 0 until end - 1: function range(end) { return Array.from({ length: end }, (_, index) => index); } range(4); // => [0, 1, 2, 3] Inside range() function, Array.from() is supplied with the array-like { length: end }, and a map function that simply returns the current index. This way you can generate ranges of values. 6. Unique items of an array A nice trick resulting from the ability of Array.from() to accept iterable objects is to quickly remove duplicates from an array. It is achieved in combination with Set data structure: function unique(array) { return Array.from(new Set(array)); } unique([1, 1, 2, 3, 3]); // => [1, 2, 3] At first, new Set(array) creates a set containing the items of the array. Internally, the set removes the duplicates. Because the set is iterable, Array.from() extracts the unique items into a new array. 7. Conclusion Array.from() static method accepts array-like objects, as well as iterables. It accepts a mapping function. Moreover, the function does not skip iteration over empty holes. This combination of features gives Array.from() a lot of possibilities. As presented above, you can easily transform array-like objects to arrays, clone arrays, fill arrays with initial values, generates ranges and remove duplicated array items. Indeed, Array.from() is a combination of good design, configuration flexibility allowing a wide area of collection transformations. What other interesting use cases of Array.from() do you know? Please write a comment below! Like the post? Please share! Dmitri Pavlutin About Dmitri Pavlutin Software developer and sometimes writer. My daily routine consists of (but not limited to) drinking coffee, coding, writing, overcoming boredom 😉. Living in the sunny Barcelona. 🇪🇸
__label__pos
0.996504
2 I'm trying to highlight the keywords for my c++ project. So what I've done is to create a file here: ~/.vim/after/syntax/cpp.vim and put some custom configuration into it. For example, putting the lines as below can highlight the class name: hi CustomClassName guifg=NONE guibg=NONE guisp=NONE gui=bold ctermfg=lightgreen ctermbg=NONE cterm=bold syn match cCustomClassName "\(^class\s*\)\@<=\w\+" hi def link cCustomClassName CustomClassName However, this can only highlight the class name while the class declaration. enter image description here As you see, the Test at the line 8 is highlighted whereas the next Test at the line 9 isn't. In a word, I can set the highlight for the declaration class because I can use the regex to match the keyword class. But the codes like the line 9 can't be matched by the regex. It seems that I should use some method to find the codes like the line 9 dynamically and highlight them. I'm thinking if I can set an array to store all custom class name and highlight them but I don't know how to do it. 0 Your Answer By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy. Browse other questions tagged or ask your own question.
__label__pos
0.878266
* Got 'todo($message)' working for Testcases. [kakapo:kakapo.git] / src / Global.nqp 1 # Copyright (C) 2009-2010, Austin Hastings. See accompanying LICENSE file, or  2 # http://www.opensource.org/licenses/artistic-license-2.0.php for license. 3 4 # =NAME Global - provides global symbol manipulation functions. 5 # 6 # =DESCRIPTION 7 # 8 # This module exports (to the root namespace) a set of functions for perl-like management  9 # of global symbols.  10 # 11 # =SYNOPSIS 12 # 13 # =begin code 14 # 15 #        use( 'Any::Module' ); 16 #        use( 'Some::Other::Module', :tags('A', 'B')); 17 # 18 #       export('foo', 'bar', 'baz', :tags('SPECIAL', 'DEFAULT')); 19 # 20 # =end code 21 # 22 # B<NOTE:> This module is the I< very first > module initialized in the Kakapo library. Because of  23 # this, it must call no external functions that depend on being initialized. (In general, only calls to 24 # Opcode:: should be made.) 25 26 module Global; 27 28 # Special sub called when the Kakapo library is loaded or initialized. This is to guarantee this  29 # module is available during :init and :load processing for other modules. 30 31 our sub _pre_initload() { 32         inject_root_symbol(Global::use); 33         inject_root_symbol(Global::export); 34 } 35 36 # =signature    export($symbol [...], [ :namespace(_), ] [ :tags( [ string [...] ] ) ] ) 37 # =signature    export($symbol, :as(<name>), [:namespace(_), ] [ :tags( [ string [...]] ) ] ) 38 # 39 # Adds a list of symbols - either String names or Subs - to one or more export groups. If a String is passed  40 # to identify the symbol, then the String will be the export name of the symbol. 41 # 42 # If desired, a C< :namespace(_) > may be provided, either a String or a NameSpace object, that specifies 43 # the namespace of the symbol(s) being exported. This can be used to add a different namespace's symbols 44 # to the current module's export set. 45 # 46 # If no C< :tags > are given, the tag 'DEFAULT' is used. (This is the same tag used by C<import> when no  47 # other tags are specified.) The symbol is added to all of the export groups named in C< :tags >. This allows 48 # definition of partially overlapping tag sets, by adding the common symbols to multiple tags: 49 # 50 #       Global::export('c1', 'c2', 'c3', :tags('A', 'B')); 51 #       Global::export('a1', 'a2', :tags('A')); # A include a1, a2, c1, c2, c3 52 #       Global::export('b1', :tags('B'));               # B includes b1, c1, c2, c3 53 # 54 # The option C<:as($name)> can only be used with a single symbol. In this case, the symbol - which in this  55 # case may be an object, or the String name of an object - is added to the specified export tags under the  56 # C<$name> given. (This can be used to export dynamically created objects, or to export some other module's  57 # sub under a different name.) 58 # 59 # Note finally that there are two I< reserved > tag names: C< ALL > and C< DEFAULT >. The C< DEFAULT > 60 # tag, as mentioned above, is used if no C< :tags > are specified. Similarly, calls to L<C< use >> that do  61 # not specify any tags will import the C< DEFAULT > tag. The C< ALL > tag is automatically attached to  62 # every exported symbol. This is more to support L<C< use >>-ing a particular symbol than anything else, 63 # but it is a valid import tag. 64 65 our sub export($symbol, *@symbols, :$as?, :$namespace = Parrot::caller_namespace(), :@tags?) { 66         if pir::isa__IPS($symbol, 'String') || ! pir::does__IPS($symbol, 'array') { 67                 @symbols.unshift($symbol); 68         } 69         else { 70                 @symbols := $symbol;    # Array: <name name name> 71         } 72 73         if ! pir::isa__IPS(@tags, 'ResizablePMCArray') { @tags := Array::new(@tags); } 74         elsif +@tags == 0 { @tags.push('DEFAULT'); } 75 76         if Opcode::isa($namespace, 'String') { 77                 $namespace := Parrot::get_hll_namespace($namespace); 78         } 79 80         my $export_nsp := Parrot::caller_namespace().make_namespace('EXPORT'); 81          82         @tags.push('ALL'); 83          84         for @tags { 85                 my $tag_nsp := $export_nsp.make_namespace(~ $_); 86                  87                 if Opcode::defined($as) { 88                         my $export_sym := @symbols[0]; 89                         if Opcode::isa($export_sym, 'String') { 90                                 $export_sym := $namespace.get_sym($export_sym); 91                         } 92 93                         inject_symbol($export_sym, :as($as), :namespace($tag_nsp)); 94                 } 95                 else { 96                         $namespace.export_to($tag_nsp, @symbols); 97                 } 98         } 99 } 100 101 our sub inject_root_symbol($pmc, :$as, :$force) { 102         my $hll_namespace := pir::get_hll_namespace__P(); 103         inject_symbol($pmc, :as($as), :namespace($hll_namespace), :force($force)); 104 } 105 106 107 our sub inject_symbol($object, :$namespace, :$as?, :$force?) { 108 # Injects a PMC C< $object > into a C< $namespace >, optionally C< $as > a certain name. For C< Sub > and  109 # C< MultiSub > PMCs, the name is not a requirement since they know their own names. For other PMC types, 110 # including injecting variable rather than functions, the C< $as > name must be provided by the caller. If  111 # C< $force > is specified, any pre-existing symbol is overwritten. Otherwise, if a name collision occurs 112 # FIXME: an exception should be thrown, but currently isn't. 113 114         $as := $as // ~$object; # Subs carry their name. 115 116         unless pir::isa($namespace, 'NameSpace') { 117                 $namespace := Opcode::get_hll_namespace($namespace); 118         } 119 120         # NB: find_var searches for *anything*, while find_sub requires isa(sub). In this case, 121         # any collision is bad. 122         if ! $force && Opcode::defined($namespace.find_var($as)) { 123                 return 0; 124         } 125          126         $namespace.add_var($as, $object); 127 } 128 129 # Registers a symbol C< $name > in the C< Global:: > namespace, bound to C< $object >. 130 # 131 # This function is used to create global symbols. The C< :namespace() > option may be specified to use  132 # a different namespace than Global. The intended usage pattern is that the Global namespace serves  133 # as a I< Registry > for locating shared objects and services. 134 135 our sub register_global($name, $object, :$namespace? = 'Global') { 136         if Opcode::isa($namespace, 'String') { 137                 $namespace := $namespace.split('::'); 138         } 139          140         my $nsp := pir::get_hll_namespace__P(); 141         $nsp := $nsp.make_namespace($namespace); 142          143         $nsp{$name} := $object;  144         export($name, :namespace($nsp)); 145 } 146 147 our sub use($module = Parrot::caller_namespace(0), :@except?, :@tags?, :@symbols?) { 148 # Imports global symbols into the caller's namespace. If neither C<:tags> nor 149 # C<:symbols> are specified, C<:tags('DEFAULT')> is assumed. 150 151 # The strings given to C<:tags > are tag names. The C<DEFAULT> tag is one  152 # of two special tag names known to the system. Otherwise, each module may  153 # define its own tagging scheme. (The other predefined tag is C<ALL>.) 154 155 # If C<:symbols> are specified, specific symbol names may be imported. The  156 # symbols must be in the target module's C<ALL> export group, as this is where 157 # they are looked up. (This will normally be true, unless the same name has been 158 # used for different exports in different TAGS. In which case, don't do that.) 159 160 # If no source C< $module > is specified, the default is the Global:: module itself.  161 # This is a shortcut for defining global variables, in conjunction with the 162 # C<register_global> function. (q.v.) 163 164 # Any symbols listed in C< @except > will I< not > be imported, regardless of how the 165 # symbol list is generated. This allows the caller to block certain symbols, perhaps  166 # in order to rename or override them. 167 168 #       if ! Opcode::defined($module)           { $module       := Parrot::caller_namespace(0); } 169         if Opcode::isa(@tags, 'String')         { @tags := Array::new(@tags); } 170         if Opcode::isa(@symbols, 'String')              { @symbols      := Array::new(@symbols); } 171          172         if Opcode::isa($module, 'P6object')     { $module       := Opcode::typeof($module); } 173         if Opcode::isa($module, 'String')               { $module       := Parrot::get_hll_namespace($module); } 174 175         if +@tags == 0 && +@symbols == 0 { 176                 @tags.push('DEFAULT'); 177         }        178 179         my $export_nsp := $module.make_namespace('EXPORT'); 180         my $target_nsp := Parrot::caller_namespace(); 181 182         my %except; 183          184         for @except { 185                 %except{$_} := 1; 186         } 187          188         for @tags { 189                 my $source_nsp := $export_nsp.make_namespace(~ $_); 190                 my @tag_symbols; 191                  192                 for $source_nsp.keys { 193                         unless %except{$_} { 194                                 @tag_symbols.push(~ $_); 195                         } 196                 } 197                          198                 if +@tag_symbols { 199                         $source_nsp.export_to($target_nsp, @tag_symbols); 200                 } 201         } 202          203         if +@symbols { 204                 $export_nsp{'ALL'}.export_to($target_nsp, @symbols); 205         } 206 }
__label__pos
0.968434
2 csmilef Csmilef 于 2013.02.28 15:23 提问 点阵的datamatrix二维码,扫不出来 使用zxing开源框架做的扫二维码。点阵的datamatrix二维码,扫不出来,是什么原因啊? 如果是矩阵的就能很好的扫出来。是不是哪里需要设置呢?跪求大哥们的帮助。。。。!!! private void decode(byte[] data, int width, int height) { long start = System.currentTimeMillis(); Result rawResult = null; //扫描结果 //下面使用zxing提供的API进行解码 PlanarYUVLuminanceSource source = CameraManager.get() .buildLuminanceSource(data, width, height); if (source != null) { BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); try { rawResult = multiFormatReader.decodeWithState(bitmap); } catch (ReaderException re) { // continue } finally { multiFormatReader.reset(); } } ......... } 2个回答 qq_18463729 qq_18463729   2015.10.28 16:33 我的是可以扫描出来,但是扫描的时间太长了 你的解决了吗? qq_18463729 qq_18463729   2015.10.28 16:35 我的是可以扫描出来,但是扫描的时间太长了 你的解决了吗? Csdn user default icon 上传中... 上传图片 插入图片 准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了! 其他相关推荐 linux python实现data matrix 二维码显示和处理 Datamatrix原名Datacode,用于 Data Matrix二维码图像处理与应用 Data Matrix二维码图像处理与应用 摘要:以Meteor II Standard图像采集卡为基础,以识别金属零件上的Data Matrix二维码为目的, 对摄像头采集的图像进行处理。实现了该方法在工业流水线睥实时识别应用。 二维码是在平面二维方向上都记录信息的符号。它充分利用了平面上的二维空间,大大提升了信息密度,使得在小面积上编码大数据成为可能。其次由于 二维码Data Matrix编码、解码使用举例 二维码Data Matrix编码、解码使用举例 Halcon 实现对datamatrix工业二维码识别(包含c++程序) 用halcon实现对datamatrix工业二维码的检测,同时导录成c++代码(包含测试图像+halcon代码+c++代码) VC++识别Data-Matrix格式的二维码 图像识别Data-Matrix格式的二维码编写步骤详述 手机扫不到二维码怎么办 二维码扫不出来的原因 手机扫不到二维码怎么办?   二维码是一种比一维码更高级的条码格式。一维码只能在一个方向(一般是水平方向)上表达信息,而二维码在水平和垂直方向都可以存储信息。现在智能手机一般都支持二维码扫描。   下面,我们就来看看二维码扫不出来的原因。   1、好比看一行文字,光线不足的时候你肯定看不清楚上面写的是什么。同样的情况下,摄像头也无法捕捉清晰的二维码,这时可以通过开启闪光灯、增加其它光源等办法 二维码小图扫描不出来或者识别慢 要求一张60*60的二维码图标。       280*280的没有问题,可是缩小成60*60的就不行了。      干脆直接用草料二维码生成器,生成60*60的好了。但是,识别很慢,两三分钟才识别出来,或者放大图片才行。      为什么百度首页的二维码可以呢?      重新寻找二维码生成器,有百度应用的。          于是试了一下,默认是生成128px的,用ps缩小为60 的 免费在线二维DataMatrix码生成器 一款免费的在线二维码datamatrix生成器 应用barcode4j生成二维码 最近需要完成一个二维码生成功能,使用了barcode4j进行开发。 ps:附件即为barcode4j的src包和bin包 生成代码如下: Java代码  public class CodeService {       private static CodeService instance;       private static DefaultConfi Datamatrix二维码生成与解码,执行程序; Datamatrix二维码生成与解码,这是执行程序;不依赖其他DLL,独立程序
__label__pos
0.932884
Carrying out multiplication easily, speedily and executing mentally using Vedic Mathematics Feb 16 08:12 2009 KvLn KvLn • Share this article on Facebook • Share this article on Twitter • Share this article on Linkedin We deal with a method which is totally unconventional but help in Carrying out multiplication easily, speedily and executing mentally. The method, based on a sutra (Formula) of Ancient Indian Vedic Mathematics, called "The Urdhva Tiryak Sutra" which means Vertically and cross-wise is applied to multiplication of numbers. Here, we will apply it to multiplication of two digit numbers. We provide lucid explanation of the method with a number of Examples. mediaimage There are methods,Carrying out multiplication easily, speedily and executing mentally using Vedic Mathematics Articles which are totally unconventional but help in Carrying out tedious and cumbersome arithmetical operations, easily, speedily and in some cases executing them mentally. People who are deeply rooted in the conventional methods, may find it difficult, at first reading, to understand the methods. But, these methods, based on the Sutras (aphorisms or Formulas) of Ancient Indian Vedic Mathematics are simple and easy to understand, remember and apply, even by little children. Here, we will apply a sutra of Vedic Math as applied to multiplication of two digit numbers.  The Urdhva Tiryak Sutra  (meaning : Vertically and cross-wise) : This is a general Formula applicable to all cases of multiplication. Using this principle, we can find the product of two numbers easily. Multiply vertically and crosswise to get the digits of the product. Examples will clarify the method. Before seeing the examples, let us see the formula for finding the product of two digit numbers. Let us say the two digits of the first number be 'a' (tens' digit) and 'b'(units' digit). And those of the second number be 'p' (tens' digit) and 'q'(units' digit). Write the digits of the two numbers one below the other as follows.           a  b          p  q The product of these numbers has three parts which are given below seperated by '/'.           a  b          p  q          ------          ap/(aq+pb)/bq          ------ 'ap' is the Hundreds' part which is the vertical product of the first column. (aq+pb) is the Tens' part which is the sum of the cross-wise products 'aq' and 'pb'. 'bq' is the units' part which is the vertical product of the second column.  Let us see the method by examples.  Example 1 : To find 21 x 13           21                            13          -----          2x1/2x3+1x1/1x3          = 2/7/3          21 x 13 = 273 The product has three parts and each part is seperated by slash (/). First part of the product = product of first vertical digits = 2x1 = 2 Second part of the product = sum of the cross-wise products = 2x3+1x1 = 6+1 = 7 Third part of the product = product of second vertical digits = 1x3 = 3 Thus 21 x 13 = 273. Example 2 : To find 41 x 51           41          51          ----          4x5/4x1+5x1/1x1          =20/9/1          41x51 = 2091 The product has three parts and each part is seperated by slash (/). First part of the product = product of first vertical digits = 4x5 = 20 Second part of the product = sum of the cross-wise products  = 4x1+5x1 = 4+5 = 9 Third part of the product = product of second vertical digits = 1x1 = 1 Thus 41 x 51 = 2091.  Example 3 : To find 23 x 42           23          42          ----          2x4/2x2+4x3/3x2          =8/16/6          =8+1/6/6          =9/6/6          23x43 = 966 The product has three parts and each part is seperated by slash (/). First part of the product = product of first vertical digits = 2x4 = 8 Second part of the product = sum of the cross-wise products  = 2x2+4x3 = 4+12 = 16 This is a two digit number. Units digit (6) is retained and tens' digit (1) is carried over to the immediate left place. See that in 16, 1 is written in small letters indicating its carry over to the immediate left place and 6 is written normally indicating it is retained in its place. Third part of the product = product of second vertical digits = 3x2 = 6 Thus 23 x 42 = 966. To explain the procedure clearly, so many steps are shown. In practice we can do the calculations mentally and write the answer in fewer steps as follows.           23          42         ----          8/16/6          =9/6/6 (worked out from right)           23 x 42 = 966.  Example 4 : To find 37 x 29           37          29          ----          3x2/3x9+2x7/7x9          =6/27+14/63          =6/27+14+6/3          =6/47/3          =6+4/7/3          =10/7/3          37x29=1073 The product has three parts and each part is seperated by slash (/). First part of the product (before carry over from second part) = product of first vertical digits = 3x2 = 6 Second part of the product (before carry over from third part) = sum of the cross-wise products  = 3x9+2x7 = 27+14 Third part of the product = product of second vertical digits = 7x9 = 63 This is a two digit number. Units digit (3) is retained and tens' digit (6) is carried over to the immediate left place. See that in 63, 6 is written in small letters indicating its carry over to the immediate left place and 3 is written normally indicating it is retained in its place. Now, Second part of the product (after carry over from third part) = 27+14+6 = 47 This is a two digit number. Units digit (7) is retained and tens' digit (4) is carried over to the immediate left place. See that in 47, 4 is written in small letters indicating its carry over to the immediate left place and 7 is written normally indicating it is retained in its place. Now, First part of the product (after carry over from second part) = 6+4 = 10 Thus 37 x 29 = 1073. To explain the procedure clearly, so many steps are shown. In practice we can do the calculations mentally and write the answer in fewer steps as follows.           37          29          ----          6/41/63          =10/7/3 (worked out from right)           37 x 29 = 1073.  Example 5 :  To find 68 x 79           68          79          ----          6x7/6x9+7x8/8x9          =42/54+56/72          =42/110+7/2          =42/117/2          =42+11/7/2          =53/7/2          68x79=5372 By this time, you are familiar with the procedure and you can understand the above problem. Thus 68 x 79 = 5372. To explain the procedure clearly, so many steps are shown. In practice we can do the calculations mentally and write the answer in fewer steps as follows.           68          79          ----          42/110/72          =53/7/2 (worked out from right)          68 x 79 = 5372.  Proof of the method adopted : We know, (ay + b)(py + q) = y2(ap) + y(aq + bp) + bq Multiplying two digit numbers is similar with y = 10 10^2 term and units term are vertical products and 10 term is cross-wise products' sum. [a(10) + b][p(10) + q] = 102(ap) + 10(aq + bp) + bq  The digits of the two numbers :           a  b          p  q  The three parts of the product : ap/(aq + pb)/bq   (proved.) For More Vedic Math Problems, go to http://www.math-help-ace.com/Mental-Math.html
__label__pos
0.954033
CI/CD Integrations Overview Continuous Integration and Continuous Delivery (CI/CD) tools aim to increase efficiency by forming a standardized testing and deployment process for your engineering teams. Since correct tag implementation is often the responsibility of the development and/or QA team, it makes sense to put ObservePoint somewhere in that process. After working with many customers we have identified a few powerful use cases for ObservePoint integrations with CI/CD tools. • Kick off audits on a specific web site with a list of changed URLs • Kick off a list of audits and Journeys at the time of regularly scheduled releases to catch implementation issues • Kick off audits and Journeys during scheduled maintenance times in lower environments to prevent data loss • Use audit and Journey rule failure notifications to create new JIRA tickets requesting implementation fixes Since every team has a different testing and deployment workflow, whatever integration you build will likely be custom, but can still be guided by one of the use cases above. Building out this integration should be a simple process for those familiar with CI/CD tools. The core of the integration is leveraging the ObservePoint API to start a list of pre-determined Audits and Journeys. Below is a guide to help your quality assurance or devops team integrate ObservePoint with your development processes: Trigger by ID This example demonstrates how to use the API to start an Audit, Journey. To make this call, you can use the following ObservePoint endpoint with a POST method: https://api.observepoint.com/v2/cards/run You will need a header with a key named “Authorization” with the value api_key {your api key here} which you can find here. Finally, as this is a POST request you will need to attach a JSON payload to the request body. For this request, this will look like the following: {"auditIds":[], "webJourneyIds":[], "appJourneyIds":[] } For each of the empty arrays in the above payload, you can put IDs of the audits, Journeys you would like to have started at the time of execution. Here is an example of a JSON body for an API call that triggers 1 Audit and 1 Journey to run: {"auditIds":[84672], "webJourneyIds":[19845], "appJourneyIds":[]} Note: Not every parameter in the body is required. You can delete them or leave the arrays empty. Here is another example where a JSON body in an API call triggers 2 App Journeys to run: {"appJourneyIds":[22611,22610]} To find the IDs to fill these arrays, you can simply go to the audit or Journey you would like to have started and look at the URL. The ID is the first number you see: https://app.observepoint.com/audit/123456/reports/summary/run/789123 Trigger by Folder Note: This is an example of a script written in Javascript. It is likely that the teams that manage your CI/CD pipeline use a different programming language to trigger tests. This script is simple enough that they shouldn't have much difficulty translating it into the programming language they prefe You will need to provide your ObservePoint folder Id(s) and API Key. /* THE 3 TRIGGER FUNCTIONS BELOW INITIATE THE OBSERVEPOINT SCANS IN THE THE ASSOCIATED FOLDERS THE OTHER FUNCTIONS ASSIST IN THE OPERATION OF THE 3 TRIGGER FUNCTIONS AND MUST BE INCLUDED. */ let FolderId = 12345; triggerTestsByFolder(FolderId); //trigger staging tests function triggerTestsByFolder(folderId) { let apiKey = 'XXXXXXX'; //get all audits let auditsEndpoint = '/web-audits' let auditsResponse = apiRequestGET(auditsEndpoint,apiKey); //get all journeys let journeysEndpoint = '/web-journeys' let journeysResponse = apiRequestGETv3(journeysEndpoint,apiKey); //filter out all audits/journeys that don't have folderId let filteredAudits = auditsResponse.filter(audit => { return audit.folderId == folderId; }); let filteredJourneys = journeysResponse.filter(journey => { return journey.folderId == folderId; }); //map to just the auditId/journeyId let auditIds = filteredAudits.map(audit => audit.id); let journeyIds = filteredJourneys.map(journey => journey.id); //make the api call let triggerEndpoint = '/cards/run'; let triggerBody = {"auditIds": auditIds, "webJourneyIds": journeyIds}; let response = apiRequestPOST(triggerEndpoint,apiKey,triggerBody); Logger.log(response); } //The functions below are helper functions and are required to run any of the above functions. function apiRequestGET(endpoint,apiKey) { var url = 'https://api.observepoint.com/v2' + endpoint; var options = { 'method': 'GET', 'headers': { Authorization: 'api_key ' + apiKey }, 'contentType': 'application/json', 'muteHttpExceptions': true } var ret = UrlFetchApp.fetch(url, options); return JSON.parse(ret); } function apiRequestGETv3(endpoint,apiKey) { var url = 'https://api.observepoint.com/v3' + endpoint; var options = { 'method': 'GET', 'headers': { Authorization: 'api_key ' + apiKey }, 'contentType': 'application/json', 'muteHttpExceptions': true } var ret = UrlFetchApp.fetch(url, options); return JSON.parse(ret); } function apiRequestPOST(endpoint,apiKey, payload) { var url = 'https://api.observepoint.com/v3' + endpoint; var options = { 'method': 'POST', 'headers': { Authorization: 'api_key ' + apiKey }, 'payload': JSON.stringify(payload), 'contentType': 'application/json', 'muteHttpExceptions': true } var ret = UrlFetchApp.fetch(url, options); return JSON.parse(ret); } Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.
__label__pos
0.951415
2 D Projective Transform START   Lets take the Lena image to perform the transformation lena Input image • In this post I am going to discuss image projective transforms. • These transform are easy to understand and useful in many applications like object detection,  3 D view geometry and ADAS. • Suppose image I(x,y) as input image and our output (transform) image is O(u,v) •  So we can write a Transform matrix T such that :                                 O(u,v) = T [I(x,y)] • Suppose image is in homogeneous co-ordinate system we can add 1                              O(u,v,1) = T [I(x,y,1)] • Where T is 3 x 3 matrix, according to T matrix we can able to transform  the image many ways. Lets write a code which can take input image multiply it with transform matrix and produce transform image   %%%%%%%%%%%%%%%%%%%%%%%% Code Start%%%%%%%%%%%%%%%% function transform_img = trasform_2d(T, input_img) %function perform the 2 D projective transform  % input_image : gray input image % T is 3 x 3 trasnform matrix   %transform_image : output gray transform image [row,col] = size(input_img); transform_img = zeros(2*row,2*col); for i=-row:2*row for j=-col:2*col U = inv(T)*[i j 1]’;      % where ‘ is transpose if(U(3)>1)                       % in case of 8 dof projective transform U(1) = U(1)/U(3); %% taking care homogeneous co ordinate U(2) = U(2)/U(3); end if((U(1)>0)&&(U(1)<row-1)&&(U(2)>0)&&(U(2)<col-1)) %% consider only points                                                                                                                 %which lie inside of input image transform_img(round(i+row+1),round(j+col+1)) =                                         input_img(round(U(1)+1),round(U(2)+1)); end end end end %%%%%%%%%%%% Code End %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Following are the main 2 D project transform : 1.  Euclidean Transform 2. Similarity Transform 3. Affine Transform 4. Projective Transform   Euclidean Transform : Let define transformation matrix for Euclidean transform T = [ R11  R12  Tx  ;  R21  R22  Ty ; 0 0 1] Where R11 , R12, R21 and  R22 are rotation matrix and Tx and Ty are translation. So it have have 3 degree of freedom 1 in rotation and 2 in translation. lets take 30 degree rotation angle and -100 pixel translation in both direction Euclidean Result of Euclidean Transform Euclidean Transform dont have property to scale the images. Similarity Transform: Let define transformation matrix for Similarity transform T = [ s*R11  s*R12  Tx  ; s* R21  s*R22  Ty ; 0 0 1] It have 4 degree of freedom. if in Euclidean transform we added the feature of scale (s) its become similarity tranform lets take 40 degree rotation angle and -100 pixel translation in both direction and 1.5 scaling factor Similurity_transform.JPG Result of Similarity transform Affine Transform : Let define transformation matrix for Affine transform T = [ a11  a12  Tx  ; a21  a22  Ty ; 0 0 1] In Similarity transform if we can able to take different angle as well as different scale it will become affine transform. lets take 40 degree rotation angle in x direction and 30 degree rotation angle in y direction , -100 pixel translation in both direction, 0.7 scaling factor in x direction and 1.5  scaling factor in y direction. Affine Result of Affine transform Projective Transform :   Define the transformation full matrix which include the homogeneous  factor as well. T =  [h11  h12  h13 ; h21  h22  h23 ; h31  h32  h33] Projective transform have 8 degree of freedom because we added 2  coefficient h31  h32 in affine transform matrix which take care of image homogeneous co-ordinate geometry. (might be in furure calibration post i will discuss it about in detail) Projective_transform Result of projective Transform %%%%%%%%%%%%%%%%%%  Code Start  %%%%%%%%%%%%%%%%%%%%%%% clc % clear the screen clear all % clear all variables close all % close all MATLAB windows %% read Image % set path to read image from system ImagePath = ‘D:\DSUsers\uidp6927\image_processingCode\lena.jpg’; img_RGB = imread(ImagePath); % read image from path img_RGB = im2double(img_RGB); % Convert image to double precision img_gray = rgb2gray(img_RGB); % convert image to gray [row, col] = size(img_gray); figure,imshow(img_gray) %For a nonreflective similarity, %[u,v] = [x,y,1]T %% euclidean transformation. scale = 1; % scale factor angle = 30*pi/180; % rotation angle tx = -100; % x translation ty = -100; % y translation sc = scale*cos(angle); ss = scale*sin(angle); T = [ sc ss tx; -ss sc ty; 0 0 1]; % call the function transform_2d transform_img = trasform_2d(T, img_gray); figure, imshow(transform_img) title(‘Euclidean transform’)   %% Similarity transform scale = 1.5; % scale factor angle = 40*pi/180; % rotation angle tx = -100; % x translation ty = -50; % y translation sc = scale*cos(angle); ss = scale*sin(angle); T = [ sc ss tx; -ss sc ty; 0 0 1]; transform_img = trasform_2d(T, img_gray); figure, imshow(transform_img) title(‘Similarity transform’) %% Affine transform scale1 = .7; % scale factor scale2 = 1.7; angle1 = 40*pi/180; % rotation angle angle2 = 30*pi/180; % rotation angle tx = -100; % x translation ty = -50; % y translation sc1 = scale1*cos(angle1); ss1 = scale1*sin(angle2); sc2 = scale2*cos(angle1); ss2 = scale2*sin(angle2); T = [ sc1 ss1 tx; -ss2 sc2 ty; 0 0 1]; transform_img = trasform_2d(T, img_gray); figure, imshow(transform_img) title(‘Affine transform’) %% projective transform scale1 = .7; % scale factor scale2 = 1.7; angle1 = 40*pi/180; % rotation angle angle2 = 30*pi/180; % rotation angle tx = -100; % x translation ty = -50; % y translation sc1 = scale1*cos(angle1); ss1 = scale1*sin(angle2); sc2 = scale2*cos(angle1); ss2 = scale2*sin(angle2); T = [ sc1 ss1 tx; -ss2 sc2 ty; .01 .02 1]; transform_img = trasform_2d(T, img_gray); figure, imshow(transform_img) title(‘Projective transform’) %%%%%%%%%%%%%%%%%%%%%  Code End %%%%%%%%%%%%%%%%%%%%%%%   the_end1   happy_learning Happy Learning Cheers     Advertisements Leave a Reply Fill in your details below or click an icon to log in: WordPress.com Logo You are commenting using your WordPress.com account. Log Out / Change ) Twitter picture You are commenting using your Twitter account. Log Out / Change ) Facebook photo You are commenting using your Facebook account. Log Out / Change ) Google+ photo You are commenting using your Google+ account. Log Out / Change ) Connecting to %s
__label__pos
0.935418
How to create a new file with vim How do I create and edit a file via SSH using a text editor such as vim on a Linux or Unix-like system? There are many ways to create a new file in Linux or Unix-like system. One can use a text editor such as vi or vim to create and edit a file. This page explains how to use vim text editor to create a file via SSH. VIM text editor commands Vim is a text editor to create or edit a text file, config file and programs on a Linux, macOS, and Unix-like system. There are two modes in vim: 1. Command mode : In this mode you can move around the file, delete text, copy/paste/undo/redo and more. 2. Insert mode : In this mode you can insert text or edit text. How do I change mode from one to another when using vim? To switch from insert mode to command mode press or type escape key (Esc). If you are ever unsure about something you typed, just press ESC to place you in Normal mode. Then retype the command you wanted. To switch from command mode to insert mode type any one of the following characters: Vim text editor commands are case-sensitive. • a : Append text following the current cursor position • A : Append text to the end of the current line • i : Insert text at the current cursor position • I : Insert text at the beginning of the cursor line • o (small o letter): Begin a new line below the cursor to insert text • O (capital O letter) : Begin a new line above the cursor to add text How do I move the cursor around when working with vim? To move the cursor, press the h,j,k,l keys as indicated: ^ k < h l > j v 1. The h key is at the left and moves left. 2. The l key is at the right and moves right. 3. The j key looks like a down arrow and moved down. 4. The k key looks like a up arrow and moved up. 5. You can use up, down, left and right arrow keys too. But, with hjkl keys you will be able to move around much faster. Steps to create and edit a file using vim 1. Log into your server using SSH command: ssh user@cloud-vm-ip 2. Type vim command to create a file named demo.txt: vim demo.txt Vim started with a new blank file Vim started with a new blank file 3. To enter insert mode and to append text type the letter i (usually you do this by press Esc followed by i) Enter INSERT mode in vim Enter INSERT mode in vim 4. Start entering text 5. When done editing press the Esc key to go back to command mode 6. Once in command mode to save and exit the file type a colon (:) followed by x. Press the Enter key. To save the file and exit the vim To save the file and exit the vim Summing up You learned how to create a new file using vim or vi text editor. Getting help is easy too. Hence, I suggest you read vim command tutorial by simply typing the following command at the CLI: $ vimtutor 🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter. 🐧 2 comments so far... add one CategoryList of Unix and Linux commands Disk space analyzersncdu pydf File Managementcat FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04 Network UtilitiesNetHogs dig host ip nmap OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04 Package Managerapk apt Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time Searchinggrep whereis which User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04 2 comments… add one • Brandon Feb 24, 2021 @ 16:35 I decided to leave a comment since I usually recur to this page to create txt files with vim. Thank you! Leave a Reply Your email address will not be published. Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum
__label__pos
0.971232
Posted 12 years ago by Igor Velikorossov - Sydney, Australia Version: 4.0.0246 Avatar I'm trying to build some sort of class view based on DocumentOutlineTreeView in the original example. I want to display a member info similar to QuickInfo once a node is clicked in the tree. There seems to be no easy way to retrieve information I want (or perhaps I'm just missing it). I hacked it using reflection but I wonder if there is an easier way to do that. IDomMember type = e.Node.Tag as IDomMember; object[] param; object offset = null; // CSharpSyntaxLanguage: // protected override DotNetContext GetContext(SyntaxEditor, int, bool, bool) MethodInfo m = typeof(DotNetSyntaxLanguage).GetMethod("GetContext", BindingFlags.NonPublic | BindingFlags.Instance); if (m == null) return; param = new object[] { this.buddyCodeEditor.Editor, offset, false, false }; DotNetContext context = (DotNetContext)m.Invoke(this.buddyCodeEditor.Document.Language, param); // DotNetProjectResolver: // internal string a(DotNetLanguage, DotNetContext, IDomType, IDomMember, int, bool) m = typeof(DotNetProjectResolver).GetMethod("a", BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(DotNetLanguage), typeof(DotNetContext), typeof(IDomType), typeof(IDomMember), typeof(int), typeof(bool) }, null); if (m == null) return; param = new object[] { DotNetLanguage.CSharp, context, null, type, -1, true }; object o = m.Invoke(this.classViewUpdater.ProjectResolver, param); if (o != null && o is string) { string html = o as string; this.markupLabel.Text = html; } Comments (7) Posted 12 years ago by Actipro Software Support - Cleveland, OH, USA Avatar Would you like us to add a GetQuickInfo method that takes a DotNetContext and returns the formatted quick info markup? Actipro Software Support Posted 12 years ago by Igor Velikorossov - Sydney, Australia Avatar That would be great. While we are at it, how do I get hold of the context object without resorting to reflection? And is there way of getting DotNetLanguage from the SE.Document.Language? Posted 12 years ago by Igor Velikorossov - Sydney, Australia Avatar It also appears that the GetQuickInfo method (or whatever it is called at the moment) does not alway generate correct output. First problem is when any of parameters or return type is an array (ie contains []). This behaviour is present in the example: 1. Create a method: public int[] M(double[] x) { return null; } 2. In a body of any other method type "M(" and quick info is "int M(double x)" instead of "int[] TestClass.M(double[] x)" Second problem is that it seems to pick the base's method while generating the info, not the method from very top class in case of overriden methods. Whilst the return type and parameters do not change, summary may as well be different from the original, and the reference to base class (in the tooltip) may be somewhat misleading (to a user). This behaviour is present in the example: 1. Create a following objects: class A { /// <summary> /// summary for A.M /// </summary> /// <param name="x"></param> public virtual int M(int x) { } } class B : A { /// <summary> /// summary for B.M /// </summary> /// <param name="x"></param> public override int M(int x) { } } 2. When you request a quick info for B's method M you will get "int A.M(int)\nsummary for A.M" Posted 12 years ago by Actipro Software Support - Cleveland, OH, USA Avatar The CSharpContext and VBContext classes have some static methods for getting the context. However maybe we can add a DotNetSyntaxLanguage method that calls the appropriate one for you in the future. There isn't a way right now to get the DotNetLanguage for a DotNetSyntaxLanguage but I've added it for you last minute before a maintenance release today. For the quick info array issue, that is something we have on our TODO list but relates to the other array issues we still need to sort out. Thanks for the other quick info code, that is now fixed for the upcoming maintenance release. Actipro Software Support Posted 12 years ago by Igor Velikorossov - Sydney, Australia Avatar Sweet, looking forward to testing the update. Thank you. Posted 12 years ago by Igor Velikorossov - Sydney, Australia Avatar Thank you for the DotNetProjectResolver.GetQuickInfo method, but I'm afraid that it does not solve my problem. It always returns null. I suspect that the reason behind that you rely on the actual context object from which you determine of what type the token is and generate its quick info. In my case context is always None, because the member may not be present in the editor at all. The method I invoke through reflection as one of its parameters takes IDomMember, which what the treenode is. Your suggestion of using CSharpContext.GetContextAtOffset unfortunately neither worked. From what I could gather through the .Net Reflector - the context object is populated from Document.Tokens, which in my case may be empty (most of my code is in either HeaderText or FooterText, and it doesn't seem to be present in Document.Tokens collection). As a result the {context = None}. I have also tried CSharpContext.GetContextBeforeOffset but it yeilds {context = AnyCode}, which again causes GetQuickInfo fall through to returning null. Posted 12 years ago by Actipro Software Support - Cleveland, OH, USA Avatar Yes you are correct, the context determines how the quick info is populated. Since you are doing something a little different than most people, try doing this... Make a class that inherits DotNetContext (since it is abstract). For constructor params, give it a target offset of 0, DotNetContextType.NamespaceTypeOrMember, and an ArrayList of items. The two items should be a IDomType followed by an IDomMember. So to initialize the items, the TextRange can be anything, the Text should be the name of the type/member, the Type should be DotNetContextItemType.Type and DotNetContextItemType.Member, and the ResolvedInfo should be the reference to the IDomType and IDomMember. If you do that, I believe you will build up what the context needs for quick info. Actipro Software Support The latest build of this product (v2018.1 build 0341) was released 6 months ago, which was after the last post in this thread. Add Comment Please log in to a validated account to post comments.
__label__pos
0.877021
Crear gráficos de tornado en Excel usando Python La visualización de datos es una herramienta esencial, ya que facilita la comprensión de conjuntos de datos complejos y la toma de decisiones informadas. Los gráficos de tornado son útiles para el análisis de sensibilidad porque proporcionan una salida gráfica que permite evaluar la variación en las variables de entrada sobre un resultado específico. En esta publicación de blog, aprenderemos cómo crear gráficos de tornado en Excel usando Python. Este artículo cubre los siguientes temas: ¿Qué es un gráfico de tornado? Un gráfico de tornado es una forma de gráfico de barras particularmente útil para comparar la magnitud del cambio en un resultado derivado de varias entradas. Cuando se trata de elegir o evaluar el riesgo, facilita la determinación de qué variable tiene el mayor impacto en el resultado. El orden decreciente de las barras genera una forma que se asemeja a un tornado, de ahí el nombre. API de gráficos de tornado en Python para Excel Para crear gráficos de tornado en Excel, utilizaremos las características de gráficos de la API Aspose.Cells para Python. Es una herramienta eficaz que permite a los desarrolladores crear, manipular, convertir y realizar otras operaciones en archivos de Excel en sus aplicaciones. Antes de profundizar en la creación de gráficos de tornado, configuremos nuestro entorno e instalemos Aspose.Cells para Python. Para instalar Aspose.Cells para Python, por favor descargue el paquete o instale la API desde PyPI usando el siguiente comando pip en su terminal: pip install aspose-cells-python Crear un gráfico de tornado en Excel usando Python Después de configurar el entorno, podemos crear fácilmente un gráfico de tornado en una hoja de cálculo de Excel siguiendo los pasos a continuación: 1. Cargue el archivo de Excel con datos usando la clase Workbook. 2. Obtenga la hoja de cálculo deseada en un objeto de la clase Worksheet. 3. Agregue un gráfico de barras apiladas usando el método Charts.add(). 4. Acceda al gráfico por su índice en un objeto de la clase Chart. 5. Configure la fuente de datos para el gráfico usando el método set_chart_data_range(). 6. Configure las propiedades requeridas para el gráfico. 7. Finalmente, guarde el documento usando el método save(). El siguiente ejemplo de código muestra cómo crear un gráfico de tornado en Excel usando Python. Crear un gráfico de tornado en Excel usando Python Crear un gráfico de tornado en Excel usando Python Insertar datos y crear un gráfico de tornado en Excel Hasta ahora, hemos aprendido cómo crear un gráfico de tornado usando una hoja de cálculo con datos pre-poblados. Ahora, veremos cómo insertar datos en una hoja de cálculo de Excel usando el método put_value() de la clase Cells. El resto del proceso para crear un gráfico de tornado seguirá siendo el mismo. El siguiente ejemplo de código muestra cómo insertar datos y luego crear un gráfico de tornado en Excel usando Python. Insertar datos y crear un gráfico de tornado en Excel Insertar datos y crear un gráfico de tornado en Excel Obtener una licencia gratuita Desbloquee todo el potencial de crear gráficos de tornado en Excel con una licencia temporal gratuita. Simplemente visite nuestra página para obtener instrucciones rápidas y fáciles sobre cómo reclamar su licencia gratuita y disfrutar de acceso sin restricciones. Gráficos de tornado en Excel en Python – Recursos gratuitos Además de crear gráficos de tornado en Excel usando Python, explore otras técnicas de visualización de datos y mejore sus capacidades de análisis de datos usando Python y Aspose.Cells. Para más información y características avanzadas, consulte los siguientes recursos: Conclusión En este artículo, hemos aprendido cómo crear gráficos de tornado en Excel usando Python. Aspose.Cells para Python es una biblioteca poderosa que permite la manipulación programática de archivos de Excel, permitiendo la automatización de tareas de visualización de datos. Siguiendo los pasos descritos en este artículo, puede crear gráficos de tornado personalizados para visualizar efectivamente el impacto de varios factores en resultados específicos. En caso de cualquier duda, no dude en contactarnos en nuestro foro de soporte gratuito. Ver también
__label__pos
0.707412
User Experience Design I don’t think UX is a “buzz” word. It’s not even a word at all. It’s a collection of methods that are applied to the process of designing interactive experiences. It encourages the interactive designer to make the most of the users’ experience. There’s a broad range of skills-sets that any good UX designer must equip themselves with in order to be effective. You have to have a creative mindset as well as an analytical mind. There’s a tremendous amount of empathy and design thinking that is involved as well as a fair amount of project management in there too. Everything ab0ut UX is impacted by the golden triangle of time, budget and resources. And it is an iterative process. Something that is ongoing and is never finished. Digital products, just like the models of cars like the “Camry” or “Taurus,” keep changing ever so slightly from year to year. UX design revolves around the issues of usability, user experience, UI design and e-commerce. Design thinking plays a huge role in understanding what is not just the most pleasurable, but the most effective mode of interaction. What are some of your thoughts on UX? Originally published at HEINTZSIGHT. One clap, two clap, three clap, forty? By clapping more or less, you can signal to us which stories really stand out.
__label__pos
0.676539
Inner Classes An inner class is a "class within a class" in java. An instance of an inner class has a "special relationship" with an instance of the outer class. That "special relationship" gives code in the inner class access to members of the enclosing (outer) class as if the inner class were part of the outer class.  There are four types of inner class: • Regular inner class (or member inner class) • Method-local inner class • Anonymous inner class • Static nested class 1. Regular Inner Class • An inner class is defined within the curly braces of the outer class. • To create an instance of the inner class, an instance of the outer class should exist. • Inner and outer classes have the access to each other's members (even private). Example 1.1. Regular Inner Class The inner class Street is defined within outer class Town. class Town { private String postCode = "33333"; public void createStreet() { Street street = new Street(); street.printAddress(); } class Street { public void printAddress() { System.out.println("Town is " + Town.this); System.out.println("PostCode is " + postCode); System.out.println("Street is " + this); } } public static void main(String[] args) { Town town = new Town(); town.createStreet(); Street street1 = town.new Street(); Street street2 = new Town().new Street(); street1.printAddress(); street2.printAddress(); } } • Inside methods of the outer class, an inner class can be used as any other class: • Street street = new Street(); • From outside the outer class instance code (including static method code within the outer class), the inner class name must include the outer class's name: Town.Street • Use a reference to the outer class or an instance of the outer class, to instantiate an inner class: new Town().new Street(); or town.new Street(); • To reference the inner class instance itself, from within the inner class code, use "this". • To reference the outer class instance from within the inner class code, use "Town.this". • A regular inner class is a member of the outer class just as instance variables and methods are, so the following modifiers can be applied to an inner class: • final • abstract • public • private • protected • static - but static turns it into a static nested class, not an inner class • strictfp 2. Method-Local Inner Class Let's see what is method local inner class in java: • A method-local inner class is defined within a block, usually within a method. • An instance of a method-local inner class should be created within the same method but below the class definition. • This type of inner class shares a "special relationship" with the outer class object, and can access all its members (even private). • A method-local inner class can have only those modifiers, which are applied to local variable declarations. It cannot be marked as public, private, protected, static, transient. A method-local inner class can be abstract or final. Example 2.1. Method-Local Inner Class class Town { private String postCode = "33333"; public void createAddress() { final int houseNumber = 34; class Street { public void printAddress() { System.out.println("PostCode is " + postCode); System.out.println("House Number is " + houseNumber); } } Street street = new Street(); street.printAddress(); } public static void main(String[] args) { Town town = new Town(); town.createAddress(); } } A local class declared in a static method has access to only static members of the enclosing class. Example 2.2. Static Method-Local Inner Class class Town { private static String postCode = "33333"; public static void createAddress() { final int houseNumber = 34; class Street { public void printAddress() { System.out.println("PostCode is " + postCode); System.out.println("House Number is " + houseNumber); } } Street street = new Street(); street.printAddress(); } public static void main(String[] args) { Town.createAddress(); } } In Java SE 7 and earlier, the inner class object cannot use the local variables of the method of the inner class, unless the local variables are marked final. In Example 2.1, the variable "houseNumber" is marked as final. Starting from Java SE 8, a local class can access local variables and parameters of the enclosing block that are final or effectively final. A variable or parameter whose value is never changed after it is initialized is effectively final.  Example 2.3. Effectively final local Variable Let's update the code from Example 2.1, making the local variable "houseNumber" of the createAddress() method effectively final instead of final: // Java SE 8 - successfully compiles and runs; // Java SE 7 - compilation failure ... public void createAddress() { int houseNumber = 34; class Street { public void printAddress() { System.out.println("PostCode is " + postCode); System.out.println("House Number is " + houseNumber); } } Street street = new Street(); street.printAddress(); } ... Example 2.4. Change Local Variable In this example, we are trying to change the local variable "houseNumber". As a result, the variable "houseNumber" is not effectively final anymore, and the Java compiler generates an error message "Local variables referenced from an inner class must be final or effectively final": // Java SE 8 - compilation failure ... public void createAddress() { int houseNumber = 34; class Street { public void printAddress() { houseNumber = 78; System.out.println("PostCode is " + postCode); System.out.println("House Number is " + houseNumber); } } Street street = new Street(); street.printAddress(); } ... 3. Anonymous Inner Class Let's discuss what is an anonymous inner class in java: • Anonymous inner class is declared without any class name. • These classes can be defined not just within a method, but even within an argument to a method. • They are useful if the only thing it is required to do with the inner class is creating instances of it in one location. Example 3.1. Syntax of an anonymous inner class The example shows the syntax of a simple anonymous inner class, where AnyType is a class or an interface. AnyType a = new AnyType(){ //body of the class }; It is possible to call only those methods of an anonymous class reference, which are defined in the reference variable type. Example 3.2. Anonymous Inner Class defines a new Method A class Potato has only one method - peel(). An anonymous inner class, which extends Potato, defines its own method fry() - this is eligible. But when we are trying to invoke this method outside an anonymous inner class - in the method prepare(), the compiler generates an error. class Potato { public void peel() { System.out.println("peeling potato"); } } class Food { Potato p = new Potato() { public void fry() { System.out.println("frying potato anonymously "); } public void peel() { System.out.println("peeling potato anonymously"); } }; public void prepare() { p.peel(); p.fry(); //compilation failure } } An anonymous inner class can not only extend another class but implement an interface as well (but only one interface). Let's look at the next example: Example 3.3. Anonymous Inner Class implements an Interface interface Cookable { public void cook(); } class Food { Cookable c = new Cookable() { public void cook() { System.out.println("anonymous cookable implementer"); } }; } Example 3.4. Anonymous Inner Class, defined as a Method Argument  The example shows how to define an anonymous inner class as a method parameter: class Food { public void prepare(Cookable c) { c.cook(); } public static void main(String[] args) { Food food = new Food(); food.prepare(new Cookable() { public void cook() { System.out.println("Preparing something yummy."); } }); } } interface Cookable { void cook(); } 4. Static Nested Class A static nested class in java is often called a static inner class, but it isn't an inner class at all by the standard definition of an inner class. While any inner class has the "special relationship" with the outer class, a static nested class does not. A static nested class doesn't have access to non-static members of the outer class. Example 4.1. Syntax of Static Nested Class Let's look at the simple definition of the static nested class. The static modifier in this case means that the nested class is a static member of the outer class. class BigOuter { static class Nested { } } Example 4.2. Instantiation of the Static Nested Class The example demonstrates the difference between accessing a static nested class from its enclosing class and non-enclosing class. class Town { static class Street { void go() { System.out.println("Go to the Street"); } } } class City { static class District { void go() { System.out.println("Go to the District"); } } public static void main(String[] args) { Town.Street street = new Town.Street(); // both class names street.go(); District district = new District(); // access the enclosed class district.go(); } } Trustpilot Trustpilot Комментарии
__label__pos
0.9991
Welcome! Java IoT Authors: Elizabeth White, Liz McMillan, AppDynamics Blog, Pat Romanski, Cloud Best Practices Network Related Topics: Java IoT Java IoT: Article Next-Gen Concurrency in Java: The Actor Model Multiple concurrent processes can communicate with each other without needing to use shared state variables At a time where the clock speeds of processors have been stable over the past couple of years, and Moore's Law is instead being applied by increasing the number of processor cores, it is getting more important for applications to use concurrent processing to reduce run/response times, as the time slicing routine via increased clock speed will no longer be available to bail out slow running programs. Carl Hewitt proposed the Actor Model in 1973 as a way to implement unbounded nondeterminism in concurrent processing. In many ways this model was influenced by the packet switching mechanism, for example, no synchronous handshake between sender and receiver, inherently concurrent message passing, messages may not arrive in the order they were sent, addresses are stored in messages, etc. The main difference between this model and most other parallel processing systems is that it uses message passing instead of shared variables for communication between concurrent processes. Using shared memory to communicate between concurrent processes requires the application of some form of locking mechanism to coordinate between threads, which may give rise to live locks, deadlocks, race conditions and starvation. Actors are the location transparent primitives that form the basis of the actor model. Each actor is associated with a mailbox (which is a queue with multiple producers and a single consumer) where it receives and buffers messages, and a behavior that is executed as a reaction to a message received. The messages are immutable and may be passed between actors synchronously or asynchronously depending on the type of operation being invoked. In response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and designate how to respond to the next message received. Actors never share state and thus don't need to compete for locks for access to shared data. The actor model first rose to fame in the language Erlang, designed by Ericcson in 1986. It has since been implemented in many next-generation languages on the JVM such as Scala, Groovy and Fantom. It is the simplicity of usage provided via a higher level of abstraction that makes the actor model easier to implement and reason about. It's now possible to implement the actor model in Java, thanks to the growing number of third-party concurrency libraries advertising this feature. Akka is one such library, written in Scala, that uses the Actor model to simplify writing fault-tolerant, highly scalable applications in both Java and Scala. Implementation Using Akka, we shall attempt to create a concurrent processing system for loan request processing in a bank as can be seen in the Figure 1. Figure 1 The system consists of four actors: 1. The front desk - which shall receive loan requests from the customers and send them to the back office for processing. It shall also maintain the statistics of the number of loans accepted/rejected and print a report detailing the same on being asked to do so. 2. The back office - which shall sort the loan requests into personal loans and home loans, and send them to the corresponding accountant for approval/rejection. 3. The personal loan accountant - who shall process personal loan requests, including approving/rejecting the requests, carrying out credit history checks and calculating the rate of interest. 4. The home loan accountant - who shall process home loan requests, including approving/rejecting the requests, carrying out credit history checks and calculating the rate of interest. To get started, download the version 2.0 of Akka for Java from http://akka.io/downloads and add the jars present in ‘akka-2.0-RC4\lib' to the classpath. Next, create a new Java class "Bank.java" and add the following import statements : import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.routing.RoundRobinRouter; Now, create a few static nested classes under ‘Bank' that will act as messages (DTOs) and be passed to actors. 1. ‘LoanRequest' will contain the following elements and their corresponding getters/setters: int requestedLoan; int accountBalance; 2. ‘PersonalLoanRequest' will extend ‘LoanRequest' and contain the following element and its corresponding getter: final static String type="Personal"; 3. ‘HomeLoanRequest' will extend ‘LoanRequest' and contain the following element and its corresponding getter: final static String type="Home"; 4. ‘LoanReply' will contain the following elements and their corresponding getters/setters: String type; boolean approved; int rate; Next, create a static nested class ‘PersonalLoanAccountant' under ‘Bank'. public static class PersonalLoanAccountant extends UntypedActor { public int rateCaluclation(int requestedLoan, int accountBalance) { if (accountBalance/requestedLoan>=2) return 5; else return 6; } public void checkCreditHistory() { for (int i=0; i<1000; i++) { continue ; } } public void onReceive(Object message) { if (message instanceof PersonalLoanRequest) { PersonalLoanRequest request=PersonalLoanRequest.class.cast(message); LoanReply reply = new LoanReply(); reply.setType(request.getType()); if (request.getRequestedLoan()<request.getaccountBalance()) { reply.setApproved(true); reply.setRate(rateCaluclation(request.getRequestedLoan(), request.getaccountBalance())); checkCreditHistory(); } getSender().tell(reply); } else { unhandled(message); } } } The above class  serves as an actor in the system. It extends the ‘UntypedActor' base class provided by Akka and must define its ‘onReceive‘ method. This method acts as the mailbox and receives messages from other actors (or non-actors) in the system. If the message received is of type 'PersonalLoanRequest', then it can be processed by approving/rejecting the loan request, setting the rate of interest and checking the requestor's credit history. Once the processing is complete, the requestor uses the sender's reference (which is embedded in the message) to send the reply (LoanReply) to the requestor via the ‘getSender().tell()' method. Now, create a similar static nested class ‘HomeLoanAccountant' under ‘Bank' public static class HomeLoanAccountant extends UntypedActor { public int rateCaluclation(int requestedLoan, int accountBalance) { if (accountBalance/requestedLoan>=2) return 7; else return 8; } public void checkCreditHistory() { for (int i=0; i<2000; i++) { continue ; } } public void onReceive(Object message) { if (message instanceof HomeLoanRequest) { HomeLoanRequest request=HomeLoanRequest.class.cast(message); LoanReply reply = new LoanReply(); reply.setType(request.getType()); if (request.getRequestedLoan()<request.getaccountBalance()) { reply.setApproved(true); reply.setRate(rateCaluclation(request.getRequestedLoan(), request.getaccountBalance())); checkCreditHistory(); } getSender().tell(reply); } else { unhandled(message); } } } Now, create a static nested class ‘BackOffice' under ‘Bank': public static class BackOffice extends UntypedActor { ActorRef personalLoanAccountant=getContext().actorOf(new Props(PersonalLoanAccountant.class).withRouter(new RoundRobinRouter(2))); ActorRef homeLoanAccountant=getContext().actorOf(new Props(HomeLoanAccountant.class).withRouter(new RoundRobinRouter(2))); public void onReceive(Object message) { if (message instanceof PersonalLoanRequest) { personalLoanAccountant.forward(message, getContext()); } else if (message instanceof HomeLoanRequest) { homeLoanAccountant.forward(message, getContext()); } else { unhandled(message); } } } The above class serves as an actor in the system and is purely used to route the incoming messages to PersonalLoanAccountant or HomeLoanAccountant, based on the type of message received. It defines actor references ‘personalLoanAccountant' and ‘homeLoanAccountant' to ‘PersonalLoanAccountant.class' and ‘HomeLoanAccountant.class', respectively. Each of these references initiates two instances of the actor it refers to and attaches a round-robin router to cycle through the actor instances. The ‘onReceive' method checks the type of the message received and forwards the message to either ‘PersonalLoanAccountant' or ‘HomeLoanAccountant' based on the message type. The ‘forward()' method helps ensure that the reference of the original sender is maintained in the message, so the receiver of the message (‘PersonalLoanAccountant' or ‘HomeLoanAccountant') can directly reply back to the message's original sender. Now, create a static nested class ‘FrontDesk' under ‘Bank': public static class FrontDesk extends UntypedActor { int approvedPersonalLoans=0; int approvedHomeLoans=0; int rejectedPersonalLoans=0; int rejectedHomeLoans=0; ActorRef backOffice=getContext().actorOf( new Props(BackOffice.class), "backOffice"); public void maintainLoanApprovalStats(Object message) { LoanReply reply = LoanReply.class.cast(message); if (reply.isApproved()) { System.out.println(reply.getType()+" Loan Approved"+" at "+reply.getRate()+"% interest."); if (reply.getType().equals("Personal")) ++approvedPersonalLoans; else if(reply.getType().equals("Home")) ++approvedHomeLoans; } else { System.out.println(reply.getType()+" Loan Rejected"); if (reply.getType().equals("Personal")) ++rejectedPersonalLoans; else if(reply.getType().equals("Home")) ++rejectedHomeLoans; } } public void printLoanApprovalStats() { System.out.println("--- REPORT ---"); System.out.println("Personal Loans Approved : "+approvedPersonalLoans); System.out.println("Home Loans Approved : "+approvedHomeLoans); System.out.println("Personal Loans Rejected : "+rejectedPersonalLoans); System.out.println("Home Loans Rejected : "+rejectedHomeLoans); } public void onReceive(Object message) { if (message instanceof LoanRequest) { backOffice.tell(message, getSelf()); } else if (message instanceof LoanReply) { maintainLoanApprovalStats(message); } else if(message instanceof String && message.equals("printLoanApprovalStats")) { printLoanApprovalStats(); getContext().stop(getSelf()); } else { unhandled(message); } } } The above class serves as the final actor in the system. It creates a reference ‘backOffice' to the actor ‘BackOffice.class'. If the message received is of type ‘LoanRequest', it sends the message to ‘BackOffice' via the method ‘backOffice.tell()', which takes a message and the reference to the sender (acquired through the method ‘getSelf()') as arguments. If the message received is of type ‘LoanReply', it updates the counters to maintain the approved/rejected counts. If the message received is "printLoanApprovalStats", it prints the stats stored in the counters, and then proceeds to stop itself via the method ‘getContext().stop(getSelf())'. The actors follow a pattern of supervisor hierarchy, and thus this command trickles down the hierarchy chain and stops all four actors in the system. Finally, write a few methods under ‘Bank' to submit requests to the ‘FrontOffice': public static void main(String[] args) throws InterruptedException { ActorSystem system = ActorSystem.create("bankSystem"); ActorRef frontDesk = system.actorOf(new Props(FrontDesk.class), "frontDesk"); submitLoanRequests (frontDesk); Thread.sleep(1000); printLoanApprovalStats (frontDesk); system.shutdown(); } public static PersonalLoanRequest getPersonalLoanRequest() { int min=10000; int max=50000; int amount=min + (int)(Math.random() * ((max - min) + 1)); int balance=min + (int)(Math.random() * ((max - min) + 1)); return (new Bank()).new PersonalLoanRequest(amount, balance); } public static HomeLoanRequest getHomeLoanRequest() { int min=50000; int max=90000; int amount=min + (int)(Math.random() * ((max - min) + 1)); int balance=min + (int)(Math.random() * ((max - min) + 1)); return (new Bank()).new HomeLoanRequest(amount, balance); } public static void submitLoanRequests(ActorRef frontDesk) { for (int i=0;i<1000;i++) { frontDesk.tell(getPersonalLoanRequest()); frontDesk.tell(getHomeLoanRequest()); } } public static void printLoanApprovalStats(ActorRef frontDesk) { frontDesk.tell("printLoanApprovalStats"); } The method ‘main' creates an actor system ‘system' using the method ‘ActorSystem.create()'. It then creates a reference ‘frontDesk' to the actor ‘FrontDesk.class'. It uses this reference to send a 1000 requests each of types ‘PersonalLoanRequest' and ‘HomeLoanRequest' to ‘FrontDesk'. It then sleeps for a second, following which it sends the message "printLoanApprovalStats" to ‘FrontDesk'. Once done, it shuts down the actor system via the method ‘system.shutdown()'. Conclusion Running the above code will create a loan request processing system with concurrent processing capabilities, and all this without using a single synchronize/lock pattern. Moreover, the code doesn't need one to go into the low-level semantics of the JVM threading mechanism or use the complex ‘java.util.concurrent' package. This mechanism of concurrent processing using the Actor Model is truly more robust as multiple concurrent processes can communicate with each other without needing to use shared state variables. More Stories By Sanat Vij Sanat Vij is a professional software engineer currently working at CenturyLink. He has vast experience in developing high availability applications, configuring application servers, JVM profiling and memory management. He specializes in performance tuning of applications, reducing response times, and increasing stability. Comments (0) Share your thoughts on this story. Add your comment You must be signed in to add a comment. Sign-in | Register In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect. @ThingsExpo Stories Increasing IoT connectivity is forcing enterprises to find elegant solutions to organize and visualize all incoming data from these connected devices with re-configurable dashboard widgets to effectively allow rapid decision-making for everything from immediate actions in tactical situations to strategic analysis and reporting. In his session at 18th Cloud Expo, Shikhir Singh, Senior Developer Relations Manager at Sencha, will discuss how to create HTML5 dashboards that interact with IoT devic... The IoTs will challenge the status quo of how IT and development organizations operate. Or will it? Certainly the fog layer of IoT requires special insights about data ontology, security and transactional integrity. But the developmental challenges are the same: People, Process and Platform. In his session at @ThingsExpo, Craig Sproule, CEO of Metavine, will demonstrate how to move beyond today's coding paradigm and share the must-have mindsets for removing complexity from the development proc... We’ve worked with dozens of early adopters across numerous industries and will debunk common misperceptions, which starts with understanding that many of the connected products we’ll use over the next 5 years are already products, they’re just not yet connected. With an IoT product, time-in-market provides much more essential feedback than ever before. Innovation comes from what you do with the data that the connected product provides in order to enhance the customer experience and optimize busi... A critical component of any IoT project is the back-end systems that capture data from remote IoT devices and structure it in a way to answer useful questions. Traditional data warehouse and analytical systems are mature technologies that can be used to handle large data sets, but they are not well suited to many IoT-scale products and the need for real-time insights. At Fuze, we have developed a backend platform as part of our mobility-oriented cloud service that uses Big Data-based approache... trust and privacy in their ecosystem. Assurance and protection of device identity, secure data encryption and authentication are the key security challenges organizations are trying to address when integrating IoT devices. This holds true for IoT applications in a wide range of industries, for example, healthcare, consumer devices, and manufacturing. In his session at @ThingsExpo, Lancen LaChance, vice president of product management, IoT solutions at GlobalSign, will teach IoT developers how t... Digital payments using wearable devices such as smart watches, fitness trackers, and payment wristbands are an increasing area of focus for industry participants, and consumer acceptance from early trials and deployments has encouraged some of the biggest names in technology and banking to continue their push to drive growth in this nascent market. Wearable payment systems may utilize near field communication (NFC), radio frequency identification (RFID), or quick response (QR) codes and barcodes... SYS-CON Events announced today that Peak 10, Inc., a national IT infrastructure and cloud services provider, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Peak 10 provides reliable, tailored data center and network services, cloud and managed services. Its solutions are designed to scale and adapt to customers’ changing business needs, enabling them to lower costs, improve performance and focus inter... We're entering the post-smartphone era, where wearable gadgets from watches and fitness bands to glasses and health aids will power the next technological revolution. With mass adoption of wearable devices comes a new data ecosystem that must be protected. Wearables open new pathways that facilitate the tracking, sharing and storing of consumers’ personal health, location and daily activity data. Consumers have some idea of the data these devices capture, but most don’t realize how revealing and... The demand for organizations to expand their infrastructure to multiple IT environments like the cloud, on-premise, mobile, bring your own device (BYOD) and the Internet of Things (IoT) continues to grow. As this hybrid infrastructure increases, the challenge to monitor the security of these systems increases in volume and complexity. In his session at 18th Cloud Expo, Stephen Coty, Chief Security Evangelist at Alert Logic, will show how properly configured and managed security architecture can... There is an ever-growing explosion of new devices that are connected to the Internet using “cloud” solutions. This rapid growth is creating a massive new demand for efficient access to data. And it’s not just about connecting to that data anymore. This new demand is bringing new issues and challenges and it is important for companies to scale for the coming growth. And with that scaling comes the need for greater security, gathering and data analysis, storage, connectivity and, of course, the... The IETF draft standard for M2M certificates is a security solution specifically designed for the demanding needs of IoT/M2M applications. In his session at @ThingsExpo, Brian Romansky, VP of Strategic Technology at TrustPoint Innovation, will explain how M2M certificates can efficiently enable confidentiality, integrity, and authenticity on highly constrained devices. So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, will provide tips on how to be successful in large scale machine lear... Artificial Intelligence has the potential to massively disrupt IoT. In his session at 18th Cloud Expo, AJ Abdallat, CEO of Beyond AI, will discuss what the five main drivers are in Artificial Intelligence that could shape the future of the Internet of Things. AJ Abdallat is CEO of Beyond AI. He has over 20 years of management experience in the fields of artificial intelligence, sensors, instruments, devices and software for telecommunications, life sciences, environmental monitoring, process... You think you know what’s in your data. But do you? Most organizations are now aware of the business intelligence represented by their data. Data science stands to take this to a level you never thought of – literally. The techniques of data science, when used with the capabilities of Big Data technologies, can make connections you had not yet imagined, helping you discover new insights and ask new questions of your data. In his session at @ThingsExpo, Sarbjit Sarkaria, data science team lead ... SYS-CON Events announced today that Ericsson has been named “Gold Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. Ericsson is a world leader in the rapidly changing environment of communications technology – providing equipment, software and services to enable transformation through mobility. Some 40 percent of global mobile traffic runs through networks we have supplied. More than 1 billion subscribers around the world re... In his session at @ThingsExpo, Chris Klein, CEO and Co-founder of Rachio, will discuss next generation communities that are using IoT to create more sustainable, intelligent communities. One example is Sterling Ranch, a 10,000 home development that – with the help of Siemens – will integrate IoT technology into the community to provide residents with energy and water savings as well as intelligent security. Everything from stop lights to sprinkler systems to building infrastructures will run ef... Manufacturers are embracing the Industrial Internet the same way consumers are leveraging Fitbits – to improve overall health and wellness. Both can provide consistent measurement, visibility, and suggest performance improvements customized to help reach goals. Fitbit users can view real-time data and make adjustments to increase their activity. In his session at @ThingsExpo, Mark Bernardo Professional Services Leader, Americas, at GE Digital, will discuss how leveraging the Industrial Interne... The increasing popularity of the Internet of Things necessitates that our physical and cognitive relationship with wearable technology will change rapidly in the near future. This advent means logging has become a thing of the past. Before, it was on us to track our own data, but now that data is automatically available. What does this mean for mHealth and the "connected" body? In her session at @ThingsExpo, Lisa Calkins, CEO and co-founder of Amadeus Consulting, will discuss the impact of wea... Whether your IoT service is connecting cars, homes, appliances, wearable, cameras or other devices, one question hangs in the balance – how do you actually make money from this service? The ability to turn your IoT service into profit requires the ability to create a monetization strategy that is flexible, scalable and working for you in real-time. It must be a transparent, smoothly implemented strategy that all stakeholders – from customers to the board – will be able to understand and comprehe... You deployed your app with the Bluemix PaaS and it's gaining some serious traction, so it's time to make some tweaks. Did you design your application in a way that it can scale in the cloud? Were you even thinking about the cloud when you built the app? If not, chances are your app is going to break. Check out this webcast to learn various techniques for designing applications that will scale successfully in Bluemix, for the confidence you need to take your apps to the next level and beyond.  
__label__pos
0.74728
Namespaces Variants Actions Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions. Archived:Collision detection events with PySymbian From Wiki Jump to: navigation, search Archived.pngArchived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}. The article is believed to be still valid for the original topic scope. Article Metadata Code Example Source file: Media:CornRush.zip Article Created: marcelcaraciolo (26 Mar 2009) Last edited: hamishwillee (31 May 2013) PySymbian is a simple and powerful language. Despite not providing native API's for game development, as the existing one in PyGame , we can easily create some code to PySymbian support it. The example below serves just as a base to the development of the Sprite class existing in MIDP 2.0 of JavaME. To detect collision between two objects, it uses the method collidesWith(). As same as in Java ME, this method returns True when a collision has ocurred and accepts an image or another sprite to check collision. The creation of a simple framework for games would help simplifying the development of applications with PySymbian. The example of code is based on the article in portuguese hosted in the Wiki Nokia Developer Criando animações em PySymbian by Felipe Andrade . Contents First Steps If you're beginning in PySymbian, I'd recommend you to read some articles and tutorials for introduction of the platform. Example In case of this be your first time with PySymbian, download the PySymbian runtime and script shell. After the installation, create a directory named 'Python' at your memory card and copy the code below in a new file with .py termination. The image must be either copied to the recent created 'Python' folder at the memory card. Cornrush.png import appuifw import e32 from graphics import Image import graphics     ## Sprite #Similar to the Sprite class of the game package available at Java ME MIDP 2.0 #This piece of code was created in only 30 minutes, and it wasn't tested exhaustively, #so may have some bugs in your implementation. Any improvement is welcomed.   class Sprite:   ## Class Constructor # @param self The object pointer. def __init__(self,aImg,aFrWidth,aFrHeight): self._iImg = aImg self._iFrWidth = aFrWidth self._iFrHeight = aFrHeight self._iCurrentFrame = 1 self._iIndFrame = 0 self._iWidth, self._iHeight = self._iImg.size self._iMaxWidthFrames = self._iWidth / self._iFrWidth self._iMaxHeightFrames = self._iHeight / self._iFrHeight self._iFrameSequence = [0] self._iPosX = 0 self._iPosY = 0 self._iOrientation = None self._iFlipOrientation = None #end __init__   ##Set the frame Sequence # @param self The object pointer. # @param aSeq Frame sequence. def set_frame_sequence(self,aSeq): self._iIndFrame = 0 self._iFrameSequence = aSeq self.iCurrentFrame = self._iFrameSequence[self._iIndFrame] #end set_frame_sequence   ##Sets the position of the sprite in the screen # @param self The object pointer. # @param aPos The Layer position. def set_position(self,aPos): self._iPosX, self._iPosY = aPos #end set_position   ##Gets the current position # @param self The object pointer. # @return the current position def getPosition(self): return self._iPosX,self._iPosY #end getPosition   ##Gets the frame Size # @param self The object pointer. # @return the frame Size. def getFrameSize(self): return self._iFrWidth, self._iFrHeight #end getFrameSize   ###Gets the Sprite Size # @param self The object pointer. # @return the Sprite Size. def getSize(self): return self._iWidth, self._iHeight #end getSize   ##Sets the next frame. #@param self The object pointer. def next_frame(self): self._iIndFrame += 1 if self._iIndFrame == len(self._iFrameSequence): self._iIndFrame = 0 self._iCurrentFrame = self._iFrameSequence[self._iIndFrame] #end next_frame   ##Set the current frame # @param self The object pointer. # @param aFrame frame. def set_frame(self, aFrame): self._iCurrentFrame = self._iFrameSequence[aFrame] #end set_frame   ##Set the Sprite Orientation # @param self The object pointer. # @param aOrientation the sprite rotation orientation. # @param aFlipOrientation the sprite flip orientation. def set_transform(self,aOrientation,aFlipOrientation): self._iImg = self._iImg.transpose(aOrientation) self._iImg = self._iImg.transpose(aFlipOrientation) #end set_transform   ##Moves the sprite at the screen # @param self The object pointer. # @param aPosX X coord. # @param aPosY Y coord def move(self,aPosX,aPosY): self._iPosX, self._iPosY = (self._iPosX + aPosX, self._iPosY + aPosY) #end move   ##Checks for collision between itself and another object. # @param self The object pointer. # @param aObject the another object. def collidesWith(self,aObject): objectLeft,objectTop = aObject.getPosition() objectRight,objectBottom = (objectLeft + aObject.getFrameSize()[0], \ objectTop + aObject.getFrameSize()[1]) selfLeft,selfTop = (self._iPosX, self._iPosY) selfRight,selfBottom = (selfLeft + self._iFrWidth, selfTop + self._iFrHeight) if not ((selfLeft >= objectRight) or (selfTop >= objectBottom) \ or (selfRight <= objectLeft) or (selfBottom <= objectTop)): return True return False #end collidesWith   ##Draws the object at the screen in accordance with its current frame and current position. #@param self The object pointer. #@param aGraphics Canvas. def paint(self,aGraphics): aGraphics.blit(self._iImg,target=(self._iPosX,self._iPosY), \ source=((self._iCurrentFrame-1) * self._iFrWidth, 0, \ self._iCurrentFrame * self._iFrWidth, self._iCurrentFrame * self._iFrHeight)) # end paint   ##Sprite Animation #Responsable for creating the objects at the screen class SpriteAnimation: ##Class Constructor #@param self The object pointer. def __init__(self):   #Defines the body of application self._iCanvas = appuifw.Canvas() appuifw.app.body = self._iCanvas   #Defines the screen resolution appuifw.app.orientation = 'portrait' appuifw.app.screen = 'full'   #Sets the Height and Width of canvas self._cWidth, self._cHeight = self._iCanvas.size   #Sprite CornRush Up self._imgCornRush = Image.open("e:\\Python\\cornrush.png") self._spCornRushUp = Sprite(self._imgCornRush, 66, 56) self._spCornRushUp.set_position((self._cWidth/2 - self._spCornRushUp.getSize()[0]/2, \ self._spCornRushUp.getSize()[1])) self._spCornRushUp.set_frame_sequence([1,2]) self._spCornRushUp.set_transform(graphics.ROTATE_180, graphics.FLIP_LEFT_RIGHT)   #Sprite CornRush Down self._spCornRushDown = Sprite(self._imgCornRush,66,56) self._spCornRushDown.set_position((self._cWidth/2 - self._spCornRushDown.getSize()[0]/2, \ self._cHeight-self._spCornRushDown.getSize()[1])) self._spCornRushDown.set_frame_sequence([1,2])   #Defines the exit key handler appuifw.app.exit_key_handler = self.quit   #Sets the app status self._iRunning = True self._iCollision = 0   #defines a white background self._iCanvas.rectangle((0,0,240,320), outline = 0xFFFFFF, width=240)   #Creates the app main loop self.paint() # end __init__   #Redraws the objects at the screen. # @param self The object pointer. def paint(self): while self._iRunning:   self._iCanvas.clear() self._spCornRushUp.paint(self._iCanvas) self._spCornRushDown.paint(self._iCanvas)   self._spCornRushUp.next_frame() self._spCornRushDown.next_frame()   self._spCornRushDown.move(0,-1) self._spCornRushUp.move(0,1)   #A delay to show at the screen that the collision has ocurred. if self._iCollision == 2: self._iRunning = False   #Checks the collision detection self.detectionCollision()   #Process pendent events e32.ao_yield()   #update rate e32.ao_sleep(0.1) # end paint   ##Collision Checker def detectionCollision(self): if self._spCornRushUp.collidesWith(self._spCornRushDown): self._spCornRushUp.set_frame_sequence([3]) self._spCornRushDown.set_frame_sequence([3]); self._iCollision += 1 #end detectionCollision   ##Exit Handler # @param self The object pointer. def quit(self): self._iRunning = False #end quit     animation = SpriteAnimation() Screenshots CornRushNoCollision.jpg        CornRushCollision.jpg Source Code Donwload source code of this example: File:CornRush.zip Autor marcelcaraciolo -- 09:12, 26 March 2009 (EEST) --nirpsis 10:27, 1 September 2009 (UTC) This page was last modified on 31 May 2013, at 01:07. 60 page views in the last 30 days. ×
__label__pos
0.699334
Imported code looks different than actual https://goatplayzs-stellar-project.webflow.io/untitled this is how the imported code looks This is how it should look : https://imgur.com/ceSfTTu My share only link code under body{font-family:Montserrat,sans-serif;background:#f7edd5}.container{max-width:900px}a{display:inline-block;text-decoration:none}input{outline:0!important}h1{text-align:center;text-transform:uppercase;margin-bottom:40px;font-weight:700}section#formHolder{padding:50px 0}.brand{padding:20px;background:url(https://goo.gl/A0ynht);background-size:cover;background-position:center center;color:#fff;min-height:540px;position:relative;box-shadow:3px 3px 10px rgba(0,0,0,.3);transition:all .6s cubic-bezier(1,-.375,.285,.995);z-index:9999}.brand.active{width:100%}.brand::before{content:"";display:block;width:100%;height:100%;position:absolute;top:0;left:0;background:#000;z-index:-1}.brand a.logo{color:#f95959;font-size:20px;font-weight:700;text-decoration:none;line-height:1em}.brand a.logo span{font-size:30px;color:#fff;transform:translateX(-5px);display:inline-block}.brand .heading{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;transition:all .6s}.brand .heading.active{top:100px;left:100px;transform:translate(0)}.brand .heading h2{font-size:70px;font-weight:700;text-transform:uppercase;margin-bottom:0}.brand .heading p{font-size:15px;font-weight:300;text-transform:uppercase;letter-spacing:2px;white-space:4px;font-family:Raleway,sans-serif}.brand .success-msg{width:100%;text-align:center;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);margin-top:60px}.brand .success-msg p{font-size:25px;font-weight:400;font-family:Raleway,sans-serif}.brand .success-msg a{font-size:12px;text-transform:uppercase;padding:8px 30px;background:#f95959;text-decoration:none;color:#fff;border-radius:30px}.brand .success-msg a,.brand .success-msg p{transition:all .9s;transform:translateY(20px);opacity:0}.brand .success-msg a.active,.brand .success-msg p.active{transform:translateY(0);opacity:1}.form{position:relative}.form .form-peice{background:#fff;min-height:480px;margin-top:30px;box-shadow:3px 3px 10px rgba(0,0,0,.2);color:#bbb;padding:30px 0 60px;transition:all .9s cubic-bezier(1,-.375,.285,.995);position:absolute;top:0;left:-30%;width:130%;overflow:hidden}.form .form-peice.switched{transform:translateX(-100%);width:100%;left:0}.form form{padding:0 40px;margin:0;width:70%;position:absolute;top:50%;left:60%;transform:translate(-50%,-50%)}.form form .form-group{margin-bottom:5px;position:relative}.form form .form-group.hasError input{border-color:#f95959!important}.form form .form-group.hasError label{color:#f95959!important}.form form label{font-size:12px;font-weight:400;text-transform:uppercase;font-family:Montserrat,sans-serif;transform:translateY(40px);transition:all .4s;cursor:text;z-index:-1}.form form label.active{transform:translateY(10px);font-size:10px}.form form label.fontSwitch{font-family:Raleway,sans-serif!important;font-weight:600}.form form input:not([type=submit]){background:0 0;outline:0;border:none;display:block;padding:10px 0;width:100%;border-bottom:1px solid #eee;color:#444;font-size:15px;font-family:Montserrat,sans-serif;z-index:1}.form form input:not([type=submit]).hasError{border-color:#f95959}.form form span.error{color:#f95959;font-family:Montserrat,sans-serif;font-size:12px;position:absolute;bottom:-20px;right:0;display:none}.form form input[type=password]{color:#f95959}.form form .CTA{margin-top:30px}.form form .CTA input{font-size:12px;text-transform:uppercase;padding:5px 30px;background:#f95959;color:#fff;border-radius:30px;margin-right:20px;border:none;font-family:Montserrat,sans-serif}.form form .CTA a.switch{font-size:13px;font-weight:400;font-family:Montserrat,sans-serif;color:#bbb;text-decoration:underline;transition:all .3s}.form form .CTA a.switch:hover{color:#f95959}footer{text-align:center}footer p{color:#777}footer p a,footer p a:focus{color:#b8b09f;transition:all .3s;text-decoration:none!important}footer p a:focus:hover,footer p a:hover{color:#f95959}@media (max-width:768px){.container{overflow:hidden}section#formHolder{padding:0}section#formHolder div.brand{min-height:200px!important}section#formHolder div.brand.active{min-height:100vh!important}section#formHolder div.brand .heading.active{top:200px;left:50%;transform:translate(-50%,-50%)}section#formHolder div.brand .success-msg p{font-size:16px}section#formHolder div.brand .success-msg a{padding:5px 30px;font-size:10px}section#formHolder .form{width:80vw;min-height:500px;margin-left:10vw}section#formHolder .form .form-peice{margin:0;top:0;left:0;width:100%!important;transition:all .5s ease-in-out}section#formHolder .form .form-peice.switched{transform:translateY(-100%);width:100%;left:0}section#formHolder .form .form-peice>form{width:100%!important;padding:60px;left:50%}}@media (max-width:480px){section#formHolder .form{width:100vw;margin-left:0}h2{font-size:50px!important}} code before <div class="container"> <section id="formHolder"> <div class="row"> <!-- Brand Box --> <div class="col-sm-6 brand"> <div class="heading"> <h2>Morelli</h2> <p>Your Right Choice</p> </div> <div class="success-msg"> <p>Great! You are one of our members now</p> <a href="#" class="profile">Your Profile</a> </div> </div> <!-- Form Box --> <div class="col-sm-6 form"> <!-- Login Form --> <div class="login form-peice switched"> <form class="login-form" action="/login" method="post"> <div class="form-group"> <label for="loginemail">Email Adderss</label> <input type="email" name="username" id="loginemail" required> </div> <div class="form-group"> <label for="loginPassword">Password</label> <input type="password" name="password" id="loginPassword" required> </div> <div class="CTA"> <input type="submit" value="Login"> <a href="#" class="switch">I'm New</a> </div> </form> </div><!-- End Login Form --> <!-- Signup Form --> <div class="signup form-peice"> <form class="signup-form" action="#" method="post"> <div class="form-group"> <label for="name">Full Name</label> <input type="text" name="name" id="name" class="name"> <span class="error"></span> </div> <div class="form-group"> <label for="email">Email Adderss</label> <input type="email" name="username" id="email" class="email"> <span class="error"></span> </div> <div class="form-group"> <label for="phone">Phone Number - <small>Optional</small></label> <input type="text" name="phone" id="phone"> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" id="password" class="pass"> <span class="error"></span> </div> <div class="form-group"> <label for="passwordCon">Confirm Password</label> <input type="password" name="passwordCon" id="passwordCon" class="passConfirm"> <span class="error"></span> </div> <div class="CTA"> <input type="submit" value="Signup Now" id="submit"> <a href="#" class="switch">I have an account</a> </div> </form> </div><!-- End Signup Form --> </div> </div> </section> </div> my read only link : https://preview.webflow.com/preview/goatplayzs-stellar-project?utm_medium=preview_link&utm_source=designer&utm_content=goatplayzs-stellar-project&preview=9fc3df7bde93d3f04f608216572c3c79&pageId=5eac76eacd114674fa6c1695&mode=preview
__label__pos
0.814219
AWS IAM: Allowing a Role to Assume Another Role To allow an IAM Role to assume another Role, we need to modify the trust relationship of the role that is to be assumed. This process varies depending if the roles exist within the same account or if they’re in separate accounts. Roles in the Same Account Let’s say we have two roles, Role_A and Role_B. If we want to allow Role_A to assume Role_B, we need to modify the trust relationship of Role_B with the following: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::111111111111:role/Role_A" }, "Action": "sts:AssumeRole" } ] } This is all that’s needed to allow a role to assume another role within the same account. Note the Principal element where we specify the role that we want to give permissions to. In general, the Principal element is used in policies to give users/roles/services access to other AWS resources. However, the Principal element cannot be used in policies attached to Roles. It can only exist in the trust relationships of roles (you’ll get errors if you try to use the Principal element in an IAM Role policy). You can read more about this element in the AWS docs. Roles in Different Accounts Let’s say Role_A and Role_B are in different accounts. In this case, the process from above stays the same. Role_B needs to have its trust relationship modified to allow Role_A to assume it. The difference here is that Role_A will need an additional policy with sts:AssumeRole permissions. So the final result is as follows: The Role_B trust relationship stays the same: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::111111111111:role/Role_A" }, "Action": "sts:AssumeRole" } ] } And Role_A needs the following attached as a policy: { "Version": "2012-10-17", "Statement": { "Effect": "Allow", "Action": "sts:AssumeRole", "Resource": "arn:aws:iam::222222222222:role/Role_B" } } Now Role_A will be able to assume Role_B even if they’re in different accounts.
__label__pos
0.998046
Classes:PowerTargeter From ZDoom Wiki Jump to navigation Jump to search Note: Wait! Stop! Before you copy this actor's definition into your mod, remember the following things: 1. You do not need to copy that actor, since it is already defined. 2. In fact, it's not just useless, it's actually harmful as it can cause problems. 3. If you want to modify it, or use a modified version, using inheritance is the way to go. 4. The actor definitions here are put on the wiki for reference purpose only. Learn from them, don't copy them. 5. There is only one exception: if what you want is changing Ammo capacity, you need to create a new type from Ammo. Targeter power Actor type Power Game MiniZDoomLogoIcon.png DoomEd Number None Class Name PowerTargeter Classes: InventoryPowerupPowerTargeter This actor needs a description. DECORATE definition ACTOR PowerTargeter : Powerup native { Powerup.Duration -160 +INVENTORY.HUBPOWER States { Targeter: TRGT A -1 Stop TRGT B -1 Stop TRGT C -1 Stop } }
__label__pos
0.829267
alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix   Java example source code file (TestConverterManager.java) This example Java source code file (TestConverterManager.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM. Learn more about this Java project at its project page. Java - Java tags/keywords chronology, class, datetimeformatter, datetimezone, durationconverter, illegalargumentexception, instantconverter, intervalconverter, object, old_jdk, partialconverter, periodconverter, reflection, security, securityexception, securitymanager, util The TestConverterManager.java Java example source code /* * Copyright 2001-2006 Stephen Colebourne * * 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. */ package org.joda.time.convert; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.security.AllPermission; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import junit.framework.TestCase; import junit.framework.TestSuite; import org.joda.time.Chronology; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.Duration; import org.joda.time.ReadablePartial; import org.joda.time.ReadablePeriod; import org.joda.time.Period; import org.joda.time.PeriodType; import org.joda.time.Interval; import org.joda.time.JodaTimePermission; import org.joda.time.ReadWritablePeriod; import org.joda.time.ReadWritableInterval; import org.joda.time.ReadableDateTime; import org.joda.time.ReadableDuration; import org.joda.time.ReadableInstant; import org.joda.time.ReadableInterval; import org.joda.time.TimeOfDay; import org.joda.time.format.DateTimeFormatter; /** * This class is a JUnit test for ConverterManager. * * @author Stephen Colebourne */ public class TestConverterManager extends TestCase { private static final boolean OLD_JDK; static { String str = System.getProperty("java.version"); boolean old = true; if (str.length() > 3 && str.charAt(0) == '1' && str.charAt(1) == '.' && (str.charAt(2) == '4' || str.charAt(2) == '5' || str.charAt(2) == '6')) { old = false; } OLD_JDK = old; } private static final Policy RESTRICT; private static final Policy ALLOW; static { // don't call Policy.getPolicy() RESTRICT = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } public boolean implies(ProtectionDomain domain, Permission permission) { if (permission instanceof JodaTimePermission) { return false; } return true; // return super.implies(domain, permission); } }; ALLOW = new Policy() { public PermissionCollection getPermissions(CodeSource codesource) { Permissions p = new Permissions(); p.add(new AllPermission()); // enable everything return p; } public void refresh() { } }; } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestConverterManager.class); } public TestConverterManager(String name) { super(name); } //----------------------------------------------------------------------- public void testSingleton() throws Exception { Class cls = ConverterManager.class; assertEquals(true, Modifier.isPublic(cls.getModifiers())); Constructor con = cls.getDeclaredConstructor((Class[]) null); assertEquals(1, cls.getDeclaredConstructors().length); assertEquals(true, Modifier.isProtected(con.getModifiers())); Field fld = cls.getDeclaredField("INSTANCE"); assertEquals(true, Modifier.isPrivate(fld.getModifiers())); } //----------------------------------------------------------------------- public void testGetInstantConverter() { InstantConverter c = ConverterManager.getInstance().getInstantConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new DateTime()); assertEquals(ReadableInstant.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new Date()); assertEquals(Date.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new GregorianCalendar()); assertEquals(Calendar.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getInstantConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetInstantConverterRemovedNull() { try { ConverterManager.getInstance().removeInstantConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getInstantConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addInstantConverter(NullConverter.INSTANCE); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testGetInstantConverterOKMultipleMatches() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return ReadableDateTime.class;} }; try { ConverterManager.getInstance().addInstantConverter(c); InstantConverter ok = ConverterManager.getInstance().getInstantConverter(new DateTime()); // ReadableDateTime and ReadableInstant both match, but RI discarded as less specific assertEquals(ReadableDateTime.class, ok.getSupportedType()); } finally { ConverterManager.getInstance().removeInstantConverter(c); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testGetInstantConverterBadMultipleMatches() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Serializable.class;} }; try { ConverterManager.getInstance().addInstantConverter(c); try { ConverterManager.getInstance().getInstantConverter(new DateTime()); fail(); } catch (IllegalStateException ex) { // Serializable and ReadableInstant both match, so cannot pick } } finally { ConverterManager.getInstance().removeInstantConverter(c); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } //----------------------------------------------------------------------- public void testGetInstantConverters() { InstantConverter[] array = ConverterManager.getInstance().getInstantConverters(); assertEquals(6, array.length); } //----------------------------------------------------------------------- public void testAddInstantConverter1() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; try { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getInstantConverter(Boolean.TRUE).getSupportedType()); assertEquals(7, ConverterManager.getInstance().getInstantConverters().length); } finally { ConverterManager.getInstance().removeInstantConverter(c); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverter2() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return String.class;} }; try { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getInstantConverter("").getSupportedType()); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } finally { ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverter3() { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverter4() { InstantConverter removed = ConverterManager.getInstance().addInstantConverter(null); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testAddInstantConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } //----------------------------------------------------------------------- public void testRemoveInstantConverter1() { try { InstantConverter removed = ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(5, ConverterManager.getInstance().getInstantConverters().length); } finally { ConverterManager.getInstance().addInstantConverter(StringConverter.INSTANCE); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testRemoveInstantConverter2() { InstantConverter c = new InstantConverter() { public long getInstantMillis(Object object, Chronology chrono) {return 0;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; InstantConverter removed = ConverterManager.getInstance().removeInstantConverter(c); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testRemoveInstantConverter3() { InstantConverter removed = ConverterManager.getInstance().removeInstantConverter(null); assertEquals(null, removed); assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } public void testRemoveInstantConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(6, ConverterManager.getInstance().getInstantConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static final int PARTIAL_SIZE = 7; public void testGetPartialConverter() { PartialConverter c = ConverterManager.getInstance().getPartialConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new TimeOfDay()); assertEquals(ReadablePartial.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new DateTime()); assertEquals(ReadableInstant.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new Date()); assertEquals(Date.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(new GregorianCalendar()); assertEquals(Calendar.class, c.getSupportedType()); c = ConverterManager.getInstance().getPartialConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getPartialConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetPartialConverterRemovedNull() { try { ConverterManager.getInstance().removePartialConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getPartialConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addPartialConverter(NullConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testGetPartialConverterOKMultipleMatches() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return ReadableDateTime.class;} }; try { ConverterManager.getInstance().addPartialConverter(c); PartialConverter ok = ConverterManager.getInstance().getPartialConverter(new DateTime()); // ReadableDateTime and ReadablePartial both match, but RI discarded as less specific assertEquals(ReadableDateTime.class, ok.getSupportedType()); } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testGetPartialConverterBadMultipleMatches() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Serializable.class;} }; try { ConverterManager.getInstance().addPartialConverter(c); try { ConverterManager.getInstance().getPartialConverter(new DateTime()); fail(); } catch (IllegalStateException ex) { // Serializable and ReadablePartial both match, so cannot pick } } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } //----------------------------------------------------------------------- public void testGetPartialConverters() { PartialConverter[] array = ConverterManager.getInstance().getPartialConverters(); assertEquals(PARTIAL_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddPartialConverter1() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; try { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getPartialConverter(Boolean.TRUE).getSupportedType()); assertEquals(PARTIAL_SIZE + 1, ConverterManager.getInstance().getPartialConverters().length); } finally { ConverterManager.getInstance().removePartialConverter(c); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverter2() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return String.class;} }; try { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getPartialConverter("").getSupportedType()); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } finally { ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverter3() { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverter4() { PartialConverter removed = ConverterManager.getInstance().addPartialConverter(null); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testAddPartialConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } //----------------------------------------------------------------------- public void testRemovePartialConverter1() { try { PartialConverter removed = ConverterManager.getInstance().removePartialConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(PARTIAL_SIZE - 1, ConverterManager.getInstance().getPartialConverters().length); } finally { ConverterManager.getInstance().addPartialConverter(StringConverter.INSTANCE); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testRemovePartialConverter2() { PartialConverter c = new PartialConverter() { public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono) {return null;} public int[] getPartialValues(ReadablePartial partial, Object object, Chronology chrono, DateTimeFormatter parser) {return null;} public Chronology getChronology(Object object, DateTimeZone zone) {return null;} public Chronology getChronology(Object object, Chronology chrono) {return null;} public Class getSupportedType() {return Boolean.class;} }; PartialConverter removed = ConverterManager.getInstance().removePartialConverter(c); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testRemovePartialConverter3() { PartialConverter removed = ConverterManager.getInstance().removePartialConverter(null); assertEquals(null, removed); assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } public void testRemovePartialConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeInstantConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PARTIAL_SIZE, ConverterManager.getInstance().getPartialConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static int DURATION_SIZE = 5; public void testGetDurationConverter() { DurationConverter c = ConverterManager.getInstance().getDurationConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(new Duration(123L)); assertEquals(ReadableDuration.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getDurationConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getDurationConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetDurationConverterRemovedNull() { try { ConverterManager.getInstance().removeDurationConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getDurationConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addDurationConverter(NullConverter.INSTANCE); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } //----------------------------------------------------------------------- public void testGetDurationConverters() { DurationConverter[] array = ConverterManager.getInstance().getDurationConverters(); assertEquals(DURATION_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddDurationConverter1() { DurationConverter c = new DurationConverter() { public long getDurationMillis(Object object) {return 0;} public Class getSupportedType() {return Boolean.class;} }; try { DurationConverter removed = ConverterManager.getInstance().addDurationConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getDurationConverter(Boolean.TRUE).getSupportedType()); assertEquals(DURATION_SIZE + 1, ConverterManager.getInstance().getDurationConverters().length); } finally { ConverterManager.getInstance().removeDurationConverter(c); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testAddDurationConverter2() { DurationConverter c = new DurationConverter() { public long getDurationMillis(Object object) {return 0;} public Class getSupportedType() {return String.class;} }; try { DurationConverter removed = ConverterManager.getInstance().addDurationConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getDurationConverter("").getSupportedType()); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } finally { ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testAddDurationConverter3() { DurationConverter removed = ConverterManager.getInstance().addDurationConverter(null); assertEquals(null, removed); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testAddDurationConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } //----------------------------------------------------------------------- public void testRemoveDurationConverter1() { try { DurationConverter removed = ConverterManager.getInstance().removeDurationConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(DURATION_SIZE - 1, ConverterManager.getInstance().getDurationConverters().length); } finally { ConverterManager.getInstance().addDurationConverter(StringConverter.INSTANCE); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testRemoveDurationConverter2() { DurationConverter c = new DurationConverter() { public long getDurationMillis(Object object) {return 0;} public Class getSupportedType() {return Boolean.class;} }; DurationConverter removed = ConverterManager.getInstance().removeDurationConverter(c); assertEquals(null, removed); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testRemoveDurationConverter3() { DurationConverter removed = ConverterManager.getInstance().removeDurationConverter(null); assertEquals(null, removed); assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } public void testRemoveDurationConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeDurationConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(DURATION_SIZE, ConverterManager.getInstance().getDurationConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static int PERIOD_SIZE = 5; public void testGetPeriodConverter() { PeriodConverter c = ConverterManager.getInstance().getPeriodConverter(new Period(1, 2, 3, 4, 5, 6, 7, 8)); assertEquals(ReadablePeriod.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(new Duration(123L)); assertEquals(ReadableDuration.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getPeriodConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getPeriodConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} } public void testGetPeriodConverterRemovedNull() { try { ConverterManager.getInstance().removePeriodConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getPeriodConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addPeriodConverter(NullConverter.INSTANCE); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } //----------------------------------------------------------------------- public void testGetPeriodConverters() { PeriodConverter[] array = ConverterManager.getInstance().getPeriodConverters(); assertEquals(PERIOD_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddPeriodConverter1() { PeriodConverter c = new PeriodConverter() { public void setInto(ReadWritablePeriod duration, Object object, Chronology c) {} public PeriodType getPeriodType(Object object) {return null;} public Class getSupportedType() {return Boolean.class;} }; try { PeriodConverter removed = ConverterManager.getInstance().addPeriodConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getPeriodConverter(Boolean.TRUE).getSupportedType()); assertEquals(PERIOD_SIZE + 1, ConverterManager.getInstance().getPeriodConverters().length); } finally { ConverterManager.getInstance().removePeriodConverter(c); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testAddPeriodConverter2() { PeriodConverter c = new PeriodConverter() { public void setInto(ReadWritablePeriod duration, Object object, Chronology c) {} public PeriodType getPeriodType(Object object) {return null;} public Class getSupportedType() {return String.class;} }; try { PeriodConverter removed = ConverterManager.getInstance().addPeriodConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getPeriodConverter("").getSupportedType()); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } finally { ConverterManager.getInstance().addPeriodConverter(StringConverter.INSTANCE); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testAddPeriodConverter3() { PeriodConverter removed = ConverterManager.getInstance().addPeriodConverter(null); assertEquals(null, removed); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testAddPeriodConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addPeriodConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } //----------------------------------------------------------------------- public void testRemovePeriodConverter1() { try { PeriodConverter removed = ConverterManager.getInstance().removePeriodConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(PERIOD_SIZE - 1, ConverterManager.getInstance().getPeriodConverters().length); } finally { ConverterManager.getInstance().addPeriodConverter(StringConverter.INSTANCE); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testRemovePeriodConverter2() { PeriodConverter c = new PeriodConverter() { public void setInto(ReadWritablePeriod duration, Object object, Chronology c) {} public PeriodType getPeriodType(Object object) {return null;} public Class getSupportedType() {return Boolean.class;} }; PeriodConverter removed = ConverterManager.getInstance().removePeriodConverter(c); assertEquals(null, removed); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testRemovePeriodConverter3() { PeriodConverter removed = ConverterManager.getInstance().removePeriodConverter(null); assertEquals(null, removed); assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } public void testRemovePeriodConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removePeriodConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(PERIOD_SIZE, ConverterManager.getInstance().getPeriodConverters().length); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- private static int INTERVAL_SIZE = 3; public void testGetIntervalConverter() { IntervalConverter c = ConverterManager.getInstance().getIntervalConverter(new Interval(0L, 1000L)); assertEquals(ReadableInterval.class, c.getSupportedType()); c = ConverterManager.getInstance().getIntervalConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getIntervalConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getIntervalConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} try { ConverterManager.getInstance().getIntervalConverter(new Long(0)); fail(); } catch (IllegalArgumentException ex) {} } public void testGetIntervalConverterRemovedNull() { try { ConverterManager.getInstance().removeIntervalConverter(NullConverter.INSTANCE); try { ConverterManager.getInstance().getIntervalConverter(null); fail(); } catch (IllegalArgumentException ex) {} } finally { ConverterManager.getInstance().addIntervalConverter(NullConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } //----------------------------------------------------------------------- public void testGetIntervalConverters() { IntervalConverter[] array = ConverterManager.getInstance().getIntervalConverters(); assertEquals(INTERVAL_SIZE, array.length); } //----------------------------------------------------------------------- public void testAddIntervalConverter1() { IntervalConverter c = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) {return false;} public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) {} public Class getSupportedType() {return Boolean.class;} }; try { IntervalConverter removed = ConverterManager.getInstance().addIntervalConverter(c); assertEquals(null, removed); assertEquals(Boolean.class, ConverterManager.getInstance().getIntervalConverter(Boolean.TRUE).getSupportedType()); assertEquals(INTERVAL_SIZE + 1, ConverterManager.getInstance().getIntervalConverters().length); } finally { ConverterManager.getInstance().removeIntervalConverter(c); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testAddIntervalConverter2() { IntervalConverter c = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) {return false;} public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) {} public Class getSupportedType() {return String.class;} }; try { IntervalConverter removed = ConverterManager.getInstance().addIntervalConverter(c); assertEquals(StringConverter.INSTANCE, removed); assertEquals(String.class, ConverterManager.getInstance().getIntervalConverter("").getSupportedType()); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } finally { ConverterManager.getInstance().addIntervalConverter(StringConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testAddIntervalConverter3() { IntervalConverter removed = ConverterManager.getInstance().addIntervalConverter(null); assertEquals(null, removed); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testAddIntervalConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().addIntervalConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } //----------------------------------------------------------------------- public void testRemoveIntervalConverter1() { try { IntervalConverter removed = ConverterManager.getInstance().removeIntervalConverter(StringConverter.INSTANCE); assertEquals(StringConverter.INSTANCE, removed); assertEquals(INTERVAL_SIZE - 1, ConverterManager.getInstance().getIntervalConverters().length); } finally { ConverterManager.getInstance().addIntervalConverter(StringConverter.INSTANCE); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testRemoveIntervalConverter2() { IntervalConverter c = new IntervalConverter() { public boolean isReadableInterval(Object object, Chronology chrono) {return false;} public void setInto(ReadWritableInterval interval, Object object, Chronology chrono) {} public Class getSupportedType() {return Boolean.class;} }; IntervalConverter removed = ConverterManager.getInstance().removeIntervalConverter(c); assertEquals(null, removed); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testRemoveIntervalConverter3() { IntervalConverter removed = ConverterManager.getInstance().removeIntervalConverter(null); assertEquals(null, removed); assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } public void testRemoveIntervalConverterSecurity() { if (OLD_JDK) { return; } try { Policy.setPolicy(RESTRICT); System.setSecurityManager(new SecurityManager()); ConverterManager.getInstance().removeIntervalConverter(StringConverter.INSTANCE); fail(); } catch (SecurityException ex) { // ok } finally { System.setSecurityManager(null); Policy.setPolicy(ALLOW); } assertEquals(INTERVAL_SIZE, ConverterManager.getInstance().getIntervalConverters().length); } //----------------------------------------------------------------------- public void testToString() { assertEquals("ConverterManager[6 instant,7 partial,5 duration,5 period,3 interval]", ConverterManager.getInstance().toString()); } } Other Java examples (source code examples) Here is a short list of links related to this Java TestConverterManager.java source code file: ... this post is sponsored by my books ... #1 New Release! FP Best Seller   new blog posts   Copyright 1998-2021 Alvin Alexander, alvinalexander.com All Rights Reserved. A percentage of advertising revenue from pages under the /java/jwarehouse URI on this website is paid back to open source projects.  
__label__pos
0.979843
Backward compatibility обратная совместимость, полная совместимость с предыдущими версиями способность ПО и аппаратного обеспечения работать с предыдущими версиями ПО или на предыдущих версиях процессоров. Например, способность машины на новом процессоре выполнять старые программы без необходимости внесения в них изменений. При этом новый процессор может содержать дополнительные команды и иметь другие особенности, которые могут использоваться в разрабатываемом для него ПО Смотри также: downward compatibility, upward compatibility Англо-русский словарь компьютерных терминов Backward compatibility Able to share data or commands with older versions of itself, or sometimes other older systems, particularly systems it intends to supplant. Sometimes backward compatibility is limited to being able to read old data but does not extend to being able to write data in a format that can be read by old versions. For example, WordPerfect 6.0 can read WordPerfect 5.1 files, so it is backward compatible. It can be said that Perl is backward compatible with awk, because Perl was (among other things) intended to replace awk, and can, with a converter, run awk programs. See also: backward combatability. Compare: forward compatible. Онлайн словарь компьютерных терминов
__label__pos
0.645129
菜单开关 周梦康 发表于 2019-02-13 103 次浏览 标签 : Mysql 免费领取阿里云优惠券 我的直播 - 《PHP 进阶之路》 本篇文章关键字:优先队列排序算法、小顶堆、大顶堆 背景 接着 https://mengkang.net/1328.html 的案例,我们继续磕。 回顾下实验3中的例子 select `aid`,sum(`pv`) as num from article_rank force index(idx_aid_day_pv) where `day`>'20190115' group by aid order by num desc limit 10; optimizer_trace.join_execution.steps的结果如下 { "join_execution": { "select#": 1, "steps": [ { "creating_tmp_table": { "tmp_table_info": { "table": "intermediate_tmp_table", "row_length": 20, "key_length": 0, "unique_constraint": false, "location": "memory (heap)", "row_limit_estimate": 838860 } } }, { "filesort_information": [ { "direction": "desc", "table": "intermediate_tmp_table", "field": "num" } ], "filesort_priority_queue_optimization": { "limit": 10, "rows_estimate": 649101, "row_size": 24, "memory_available": 262144, "chosen": true }, "filesort_execution": [ ], "filesort_summary": { "rows": 11, "examined_rows": 649091, "number_of_tmp_files": 0, "sort_buffer_size": 352, "sort_mode": "<sort_key, rowid>" } } ] } } 关于这里的 filesort_priority_queue_optimization 算法可以参考 https://blog.csdn.net/qian520ao/article/details/80531150 在该案例中根据该结果可知,临时表使用的堆上的 memory 表。根据 https://mengkang.net/1336.html 实验中 gdb 调试打印可知道,临时表存的两个字段是aidnum 前面我们已经分析过对于 InnoDB 表来说 additional_fields 对比 rowid 来说,减少了回表,也就减少了磁盘访问,会被优先选择。但是要注意这是对于 InnoDB 来说的。而实验3是内存表,使用的是 memory 引擎。回表过程只是根据数据行的位置,直接访问内存得到数据,不会有磁盘访问(可以简单的理解为一个内存中的数组下标去找对应的元素),排序的列越少越好占的内存就越小,所以就选择了 rowid 排序。 还有一个原因就是我们这里使用了limit 10这样堆的成员个数比较小,所以占用的内存不会太大。不要忘了这里选择优先队列排序算法依然受到sort_buffer_size的限制。 优先队列排序执行步骤分析: 1. 在临时表(未排序)中取出前 10 行,把其中的num(来源于sum(pv))和rowid作为10个元素构成一个小顶堆,也就是最小的 num 在堆顶。 2. 取下一行,根据 num 的值和堆顶值作比较,如果该字大于堆顶的值,则替换掉。然后将新的堆做堆排序。 3. 重复步骤2直到第 649091 行比较完成。 4. 然后对最后的10行做一次回表查询其 aid,num。 rows_estimate 根据以上分析,先读取了 649091 行,然后回表又读取了 10 行,所以总共是 649101 行。 实验3的结果与之相吻合,但是其他的都是 1057 行,是怎么算出来的呢? row_size 存储在临时表里时,都是 aidnum 字段,占用宽度是4+15是19字节。 为什么是实验3是24字节,其他是 additional_fields 排序都是36字节。 源码分析 看下里面的Sort_param /** There are two record formats for sorting: |<key a><key b>...|<rowid>| / sort_length / ref_l / or with "addon fields" |<key a><key b>...|<null bits>|<field a><field b>...| / sort_length / addon_length / The packed format for "addon fields" |<key a><key b>...|<length>|<null bits>|<field a><field b>...| / sort_length / addon_length / <key> Fields are fixed-size, specially encoded with Field::make_sort_key() so we can do byte-by-byte compare. <length> Contains the *actual* packed length (after packing) of everything after the sort keys. The size of the length field is 2 bytes, which should cover most use cases: addon data <= 65535 bytes. This is the same as max record size in MySQL. <null bits> One bit for each nullable field, indicating whether the field is null or not. May have size zero if no fields are nullable. <field xx> Are stored with field->pack(), and retrieved with field->unpack(). Addon fields within a record are stored consecutively, with no "holes" or padding. They will have zero size for NULL values. */ class Sort_param { public: uint rec_length; // Length of sorted records. uint sort_length; // Length of sorted columns. uint ref_length; // Length of record ref. uint addon_length; // Length of added packed fields. uint res_length; // Length of records in final sorted file/buffer. uint max_keys_per_buffer; // Max keys / buffer. ha_rows max_rows; // Select limit, or HA_POS_ERROR if unlimited. ha_rows examined_rows; // Number of examined rows. TABLE *sort_form; // For quicker make_sortkey. bool use_hash; // Whether to use hash to distinguish cut JSON //... }; trace 日志是在这里记录的 GDB 调试 Mysql 实战(三)优先队列排序算法中的行记录长度统计是怎么来的(上) (gdb) b sortlength Breakpoint 7 at 0xf20d84: file /root/newdb/mysql-server/sql/filesort.cc, line 2332. 这样就推断出了 rowid 排序时,优先队列排序里面的 row_size 为什么是 24 了。 小结 当是 rowid 排序时,参考上面的注释可知 row_size (也就是 param->rec_length)格式如下 |<key a><key b>...|<rowid>| / sort_length / ref_l / sort_length 就是 num 的长度 + 1字节(标识是可以为空)。所以源码里注释有问题,没有标识出每个排序字段可以为空的长度 rowid 的长度就是 table->file->ref_length 也就是 handler->ref_length class handler :public Sql_alloc { public: uchar *ref; /* Pointer to current row */ public: /** Length of ref (1-8 or the clustered key length) */ uint ref_length; } 可以看到ref_length表示该行的指针长度。因为是64位服务器,所以长度是8字节,因此最后就是24字节啦。验证完毕。 嗨,老铁,欢迎来到我的博客! 如果觉得我的内容还不错的话,可以关注下我在 segmentfault.com 上的直播。我主要从事 PHP 和 Java 方面的开发,《深入 PHP 内核》作者之一。 [视频直播] PHP 进阶之路 - 亿级 pv 网站架构的技术细节与套路 直播中我将毫无保留的分享我这六年的全部工作经验和踩坑的故事,以及会穿插着一些面试中的 考点难点加分点 评论列表
__label__pos
0.921056
Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona more useful options   PerlMonks   Re^3: 15 billion row text file and row deletes - Best Practice? by BrowserUk (Pope) on Dec 01, 2006 at 23:20 UTC ( #587334=note: print w/ replies, xml ) Need Help?? in reply to Re^2: 15 billion row text file and row deletes - Best Practice? in thread 15 billion row text file and row deletes - Best Practice? Would it be faster to do relative seeks? It would, but I think almost all modern implementations of seek would automatically translate an absolute seek into a relative seek anyway. I don't know for sure, but I find it hard to believe that an absolute seek would ever cause the OS to 'go back to the beginning of the file'. In reality, seeking simply adjusts a number somwhere and it's not until the next read or write that it has any affect at all. The third parameter to seek is simply a throwback to when files stored on tape were commonplace. With regard to the possibility that the file has fixed length records, you're right it would be much easier and faster if that were the case. But from the (scant) information provided by the OP, it seems unlikely. Whilst he shows the serial number padded with leading zeros, he also shows a name field, which is empty in the given example, but names vary in length, so unless they are all empty, it probably indicates that these are variable length records. Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error. Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal? "Science is about questioning the status quo. Questioning authority". In the absence of evidence, opinion is indistinguishable from prejudice. Comment on Re^3: 15 billion row text file and row deletes - Best Practice? Log In? Username: Password: What's my password? Create A New User Node Status? node history Node Type: note [id://587334] help Chatterbox? and the web crawler heard nothing... How do I use this? | Other CB clients Other Users? Others musing on the Monastery: (8) As of 2013-12-09 21:56 GMT Sections? Information? Find Nodes? Leftovers? Voting Booth? How do you parse XML? Results (230 votes), past polls
__label__pos
0.937121
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long. 128 lines 3.5KB 1. #!/usr/bin/env python 2. # -*- coding: utf-8 -*- 3. # 4. # Copyright 2010 Maurizio Porrato <[email protected]> 5. # See LICENSE.txt for copyright info 6. import subprocess 7. from frn.protocol.client import FRNClient, FRNClientFactory 8. from frn.user import FRNUser 9. from twisted.internet import reactor, task 10. from twisted.internet.defer import DeferredList 11. from twisted.python import log 12. import os, string 13. from Queue import Queue 14. from twisted.internet.task import LoopingCall 15. import fcntl 16. from twisted.internet.protocol import ProcessProtocol 17. class StreamingProtocol(ProcessProtocol): 18. _silenceFrame = open("sounds/silence-gsm.gsm", "rb").read() 19. def __init__(self): 20. self._frames = Queue() 21. self._streamTimer = LoopingCall.withCount(self.sendStreamFrame) 22. def connectionMade(self): 23. log.msg("Streaming process started") 24. self._streamTimer.start(0.20) 25. def inConnectionLost(self): 26. log.msg("connection lost") 27. self._streamTimer.stop() 28. def processExited(self, status): 29. log.msg("Streaming process exited (%s)" % str(status)) 30. def sendStreamFrame(self, count): 31. for i in range(count): 32. if self._frames.empty(): 33. frames = self._silenceFrame 34. else: 35. frames = self._frames.get_nowait() 36. self.transport.write(frames) 37. def feed(self, frame): 38. self._frames.put_nowait(frame) 39. def eof(self): 40. self.transport.closeStdin() 41. STREAM_CMD="""tools/gsmstream.sh""" 42. class FRNStream(FRNClient): 43. def __init__(self): 44. self._stream = StreamingProtocol() 45. def connectionMade(self): 46. FRNClient.connectionMade(self) 47. reactor.spawnProcess(self._stream, "bash", ["bash", "-c", STREAM_CMD], os.environ) 48. def connectionLost(self, reason): 49. FRNClient.connectionLost(self, reason) 50. self._stream.eof() 51. def getClientName(self, client_id): 52. if self.clientsById.has_key(client_id): 53. return self.clientsById[client_id]['ON'] 54. else: 55. return client_id 56. def audioFrameReceived(self, from_id, frames): 57. self._stream.feed(frames) 58. self.pong() 59. def loginResponse(self, info): 60. log.msg("Login: %s" % info['AL']) 61. def clientsListUpdated(self, clients): 62. self.clients = clients 63. self.clientsById = dict([(i['ID'], i) for i in clients]) 64. class FRNStreamFactory(FRNClientFactory): 65. protocol = FRNStream 66. reactor = reactor 67. if __name__ == '__main__': 68. import sys 69. from os.path import dirname, join as pjoin 70. from ConfigParser import ConfigParser 71. log.startLogging(sys.stderr) 72. basedir = dirname(__file__) 73. acfg = ConfigParser() 74. acfg.read(['/etc/grn/accounts.conf', 75. pjoin(basedir,'accounts.conf'), 'accounts.conf']) 76. scfg = ConfigParser() 77. scfg.read(['/etc/grn/servers.conf', 78. pjoin(basedir,'servers.conf'), 'servers.conf']) 79. argc = len(sys.argv) 80. if argc >= 3: 81. server_name, network_name = sys.argv[2].split(':',1) 82. account_cfg = acfg.items(sys.argv[1])+[('network', network_name)] 83. server_cfg = scfg.items(server_name) 84. server = scfg.get(server_name, 'server') 85. port = scfg.getint(server_name, 'port') 86. d = dict(account_cfg) 87. user = FRNUser( 88. EA=d['email'], 89. PW=d['password'], ON=d['operator'], 90. BC=d['transmission'], DS=d['description'], 91. NN=d['country'], CT=d['city'], NT=d['network']) 92. reactor.connectTCP(server, port, FRNStreamFactory(user)) 93. reactor.run() 94. # vim: set et ai sw=4 ts=4 sts=4:
__label__pos
0.997049
blob: 480072139b7aa00db3d27d9381c0e6eace04835e [file] [log] [blame] /* * edac_mc kernel module * (C) 2005, 2006 Linux Networx (http://lnxi.com) * This file may be distributed under the terms of the * GNU General Public License. * * Written by Thayne Harbaugh * Based on work by Dan Hollis <goemon at anime dot net> and others. * http://www.anime.net/~goemon/linux-ecc/ * * Modified by Dave Peterson and Doug Thompson * */ #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/smp.h> #include <linux/init.h> #include <linux/sysctl.h> #include <linux/highmem.h> #include <linux/timer.h> #include <linux/slab.h> #include <linux/jiffies.h> #include <linux/spinlock.h> #include <linux/list.h> #include <linux/ctype.h> #include <linux/edac.h> #include <linux/bitops.h> #include <linux/uaccess.h> #include <asm/page.h> #include "edac_mc.h" #include "edac_module.h" #include <ras/ras_event.h> #ifdef CONFIG_EDAC_ATOMIC_SCRUB #include <asm/edac.h> #else #define edac_atomic_scrub(va, size) do { } while (0) #endif int edac_op_state = EDAC_OPSTATE_INVAL; EXPORT_SYMBOL_GPL(edac_op_state); static int edac_report = EDAC_REPORTING_ENABLED; /* lock to memory controller's control array */ static DEFINE_MUTEX(mem_ctls_mutex); static LIST_HEAD(mc_devices); /* * Used to lock EDAC MC to just one module, avoiding two drivers e. g. * apei/ghes and i7core_edac to be used at the same time. */ static void const *edac_mc_owner; static struct bus_type mc_bus[EDAC_MAX_MCS]; int edac_get_report_status(void) { return edac_report; } EXPORT_SYMBOL_GPL(edac_get_report_status); void edac_set_report_status(int new) { if (new == EDAC_REPORTING_ENABLED || new == EDAC_REPORTING_DISABLED || new == EDAC_REPORTING_FORCE) edac_report = new; } EXPORT_SYMBOL_GPL(edac_set_report_status); static int edac_report_set(const char *str, const struct kernel_param *kp) { if (!str) return -EINVAL; if (!strncmp(str, "on", 2)) edac_report = EDAC_REPORTING_ENABLED; else if (!strncmp(str, "off", 3)) edac_report = EDAC_REPORTING_DISABLED; else if (!strncmp(str, "force", 5)) edac_report = EDAC_REPORTING_FORCE; return 0; } static int edac_report_get(char *buffer, const struct kernel_param *kp) { int ret = 0; switch (edac_report) { case EDAC_REPORTING_ENABLED: ret = sprintf(buffer, "on"); break; case EDAC_REPORTING_DISABLED: ret = sprintf(buffer, "off"); break; case EDAC_REPORTING_FORCE: ret = sprintf(buffer, "force"); break; default: ret = -EINVAL; break; } return ret; } static const struct kernel_param_ops edac_report_ops = { .set = edac_report_set, .get = edac_report_get, }; module_param_cb(edac_report, &edac_report_ops, &edac_report, 0644); unsigned edac_dimm_info_location(struct dimm_info *dimm, char *buf, unsigned len) { struct mem_ctl_info *mci = dimm->mci; int i, n, count = 0; char *p = buf; for (i = 0; i < mci->n_layers; i++) { n = snprintf(p, len, "%s %d ", edac_layer_name[mci->layers[i].type], dimm->location[i]); p += n; len -= n; count += n; if (!len) break; } return count; } #ifdef CONFIG_EDAC_DEBUG static void edac_mc_dump_channel(struct rank_info *chan) { edac_dbg(4, " channel->chan_idx = %d\n", chan->chan_idx); edac_dbg(4, " channel = %p\n", chan); edac_dbg(4, " channel->csrow = %p\n", chan->csrow); edac_dbg(4, " channel->dimm = %p\n", chan->dimm); } static void edac_mc_dump_dimm(struct dimm_info *dimm, int number) { char location[80]; edac_dimm_info_location(dimm, location, sizeof(location)); edac_dbg(4, "%s%i: %smapped as virtual row %d, chan %d\n", dimm->mci->csbased ? "rank" : "dimm", number, location, dimm->csrow, dimm->cschannel); edac_dbg(4, " dimm = %p\n", dimm); edac_dbg(4, " dimm->label = '%s'\n", dimm->label); edac_dbg(4, " dimm->nr_pages = 0x%x\n", dimm->nr_pages); edac_dbg(4, " dimm->grain = %d\n", dimm->grain); edac_dbg(4, " dimm->nr_pages = 0x%x\n", dimm->nr_pages); } static void edac_mc_dump_csrow(struct csrow_info *csrow) { edac_dbg(4, "csrow->csrow_idx = %d\n", csrow->csrow_idx); edac_dbg(4, " csrow = %p\n", csrow); edac_dbg(4, " csrow->first_page = 0x%lx\n", csrow->first_page); edac_dbg(4, " csrow->last_page = 0x%lx\n", csrow->last_page); edac_dbg(4, " csrow->page_mask = 0x%lx\n", csrow->page_mask); edac_dbg(4, " csrow->nr_channels = %d\n", csrow->nr_channels); edac_dbg(4, " csrow->channels = %p\n", csrow->channels); edac_dbg(4, " csrow->mci = %p\n", csrow->mci); } static void edac_mc_dump_mci(struct mem_ctl_info *mci) { edac_dbg(3, "\tmci = %p\n", mci); edac_dbg(3, "\tmci->mtype_cap = %lx\n", mci->mtype_cap); edac_dbg(3, "\tmci->edac_ctl_cap = %lx\n", mci->edac_ctl_cap); edac_dbg(3, "\tmci->edac_cap = %lx\n", mci->edac_cap); edac_dbg(4, "\tmci->edac_check = %p\n", mci->edac_check); edac_dbg(3, "\tmci->nr_csrows = %d, csrows = %p\n", mci->nr_csrows, mci->csrows); edac_dbg(3, "\tmci->nr_dimms = %d, dimms = %p\n", mci->tot_dimms, mci->dimms); edac_dbg(3, "\tdev = %p\n", mci->pdev); edac_dbg(3, "\tmod_name:ctl_name = %s:%s\n", mci->mod_name, mci->ctl_name); edac_dbg(3, "\tpvt_info = %p\n\n", mci->pvt_info); } #endif /* CONFIG_EDAC_DEBUG */ const char * const edac_mem_types[] = { [MEM_EMPTY] = "Empty csrow", [MEM_RESERVED] = "Reserved csrow type", [MEM_UNKNOWN] = "Unknown csrow type", [MEM_FPM] = "Fast page mode RAM", [MEM_EDO] = "Extended data out RAM", [MEM_BEDO] = "Burst Extended data out RAM", [MEM_SDR] = "Single data rate SDRAM", [MEM_RDR] = "Registered single data rate SDRAM", [MEM_DDR] = "Double data rate SDRAM", [MEM_RDDR] = "Registered Double data rate SDRAM", [MEM_RMBS] = "Rambus DRAM", [MEM_DDR2] = "Unbuffered DDR2 RAM", [MEM_FB_DDR2] = "Fully buffered DDR2", [MEM_RDDR2] = "Registered DDR2 RAM", [MEM_XDR] = "Rambus XDR", [MEM_DDR3] = "Unbuffered DDR3 RAM", [MEM_RDDR3] = "Registered DDR3 RAM", [MEM_LRDDR3] = "Load-Reduced DDR3 RAM", [MEM_DDR4] = "Unbuffered DDR4 RAM", [MEM_RDDR4] = "Registered DDR4 RAM", }; EXPORT_SYMBOL_GPL(edac_mem_types); /** * edac_align_ptr - Prepares the pointer offsets for a single-shot allocation * @p: pointer to a pointer with the memory offset to be used. At * return, this will be incremented to point to the next offset * @size: Size of the data structure to be reserved * @n_elems: Number of elements that should be reserved * * If 'size' is a constant, the compiler will optimize this whole function * down to either a no-op or the addition of a constant to the value of '*p'. * * The 'p' pointer is absolutely needed to keep the proper advancing * further in memory to the proper offsets when allocating the struct along * with its embedded structs, as edac_device_alloc_ctl_info() does it * above, for example. * * At return, the pointer 'p' will be incremented to be used on a next call * to this function. */ void *edac_align_ptr(void **p, unsigned size, int n_elems) { unsigned align, r; void *ptr = *p; *p += size * n_elems; /* * 'p' can possibly be an unaligned item X such that sizeof(X) is * 'size'. Adjust 'p' so that its alignment is at least as * stringent as what the compiler would provide for X and return * the aligned result. * Here we assume that the alignment of a "long long" is the most * stringent alignment that the compiler will ever provide by default. * As far as I know, this is a reasonable assumption. */ if (size > sizeof(long)) align = sizeof(long long); else if (size > sizeof(int)) align = sizeof(long); else if (size > sizeof(short)) align = sizeof(int); else if (size > sizeof(char)) align = sizeof(short); else return (char *)ptr; r = (unsigned long)p % align; if (r == 0) return (char *)ptr; *p += align - r; return (void *)(((unsigned long)ptr) + align - r); } static void _edac_mc_free(struct mem_ctl_info *mci) { int i, chn, row; struct csrow_info *csr; const unsigned int tot_dimms = mci->tot_dimms; const unsigned int tot_channels = mci->num_cschannel; const unsigned int tot_csrows = mci->nr_csrows; if (mci->dimms) { for (i = 0; i < tot_dimms; i++) kfree(mci->dimms[i]); kfree(mci->dimms); } if (mci->csrows) { for (row = 0; row < tot_csrows; row++) { csr = mci->csrows[row]; if (csr) { if (csr->channels) { for (chn = 0; chn < tot_channels; chn++) kfree(csr->channels[chn]); kfree(csr->channels); } kfree(csr); } } kfree(mci->csrows); } kfree(mci); } struct mem_ctl_info *edac_mc_alloc(unsigned mc_num, unsigned n_layers, struct edac_mc_layer *layers, unsigned sz_pvt) { struct mem_ctl_info *mci; struct edac_mc_layer *layer; struct csrow_info *csr; struct rank_info *chan; struct dimm_info *dimm; u32 *ce_per_layer[EDAC_MAX_LAYERS], *ue_per_layer[EDAC_MAX_LAYERS]; unsigned pos[EDAC_MAX_LAYERS]; unsigned size, tot_dimms = 1, count = 1; unsigned tot_csrows = 1, tot_channels = 1, tot_errcount = 0; void *pvt, *p, *ptr = NULL; int i, j, row, chn, n, len, off; bool per_rank = false; BUG_ON(n_layers > EDAC_MAX_LAYERS || n_layers == 0); /* * Calculate the total amount of dimms and csrows/cschannels while * in the old API emulation mode */ for (i = 0; i < n_layers; i++) { tot_dimms *= layers[i].size; if (layers[i].is_virt_csrow) tot_csrows *= layers[i].size; else tot_channels *= layers[i].size; if (layers[i].type == EDAC_MC_LAYER_CHIP_SELECT) per_rank = true; } /* Figure out the offsets of the various items from the start of an mc * structure. We want the alignment of each item to be at least as * stringent as what the compiler would provide if we could simply * hardcode everything into a single struct. */ mci = edac_align_ptr(&ptr, sizeof(*mci), 1); layer = edac_align_ptr(&ptr, sizeof(*layer), n_layers); for (i = 0; i < n_layers; i++) { count *= layers[i].size; edac_dbg(4, "errcount layer %d size %d\n", i, count); ce_per_layer[i] = edac_align_ptr(&ptr, sizeof(u32), count); ue_per_layer[i] = edac_align_ptr(&ptr, sizeof(u32), count); tot_errcount += 2 * count; } edac_dbg(4, "allocating %d error counters\n", tot_errcount); pvt = edac_align_ptr(&ptr, sz_pvt, 1); size = ((unsigned long)pvt) + sz_pvt; edac_dbg(1, "allocating %u bytes for mci data (%d %s, %d csrows/channels)\n", size, tot_dimms, per_rank ? "ranks" : "dimms", tot_csrows * tot_channels); mci = kzalloc(size, GFP_KERNEL); if (mci == NULL) return NULL; /* Adjust pointers so they point within the memory we just allocated * rather than an imaginary chunk of memory located at address 0. */ layer = (struct edac_mc_layer *)(((char *)mci) + ((unsigned long)layer)); for (i = 0; i < n_layers; i++) { mci->ce_per_layer[i] = (u32 *)((char *)mci + ((unsigned long)ce_per_layer[i])); mci->ue_per_layer[i] = (u32 *)((char *)mci + ((unsigned long)ue_per_layer[i])); } pvt = sz_pvt ? (((char *)mci) + ((unsigned long)pvt)) : NULL; /* setup index and various internal pointers */ mci->mc_idx = mc_num; mci->tot_dimms = tot_dimms; mci->pvt_info = pvt; mci->n_layers = n_layers; mci->layers = layer; memcpy(mci->layers, layers, sizeof(*layer) * n_layers); mci->nr_csrows = tot_csrows; mci->num_cschannel = tot_channels; mci->csbased = per_rank; /* * Alocate and fill the csrow/channels structs */ mci->csrows = kcalloc(tot_csrows, sizeof(*mci->csrows), GFP_KERNEL); if (!mci->csrows) goto error; for (row = 0; row < tot_csrows; row++) { csr = kzalloc(sizeof(**mci->csrows), GFP_KERNEL); if (!csr) goto error; mci->csrows[row] = csr; csr->csrow_idx = row; csr->mci = mci; csr->nr_channels = tot_channels; csr->channels = kcalloc(tot_channels, sizeof(*csr->channels), GFP_KERNEL); if (!csr->channels) goto error; for (chn = 0; chn < tot_channels; chn++) { chan = kzalloc(sizeof(**csr->channels), GFP_KERNEL); if (!chan) goto error; csr->channels[chn] = chan; chan->chan_idx = chn; chan->csrow = csr; } } /* * Allocate and fill the dimm structs */ mci->dimms = kcalloc(tot_dimms, sizeof(*mci->dimms), GFP_KERNEL); if (!mci->dimms) goto error; memset(&pos, 0, sizeof(pos)); row = 0; chn = 0; for (i = 0; i < tot_dimms; i++) { chan = mci->csrows[row]->channels[chn]; off = EDAC_DIMM_OFF(layer, n_layers, pos[0], pos[1], pos[2]); if (off < 0 || off >= tot_dimms) { edac_mc_printk(mci, KERN_ERR, "EDAC core bug: EDAC_DIMM_OFF is trying to do an illegal data access\n"); goto error; } dimm = kzalloc(sizeof(**mci->dimms), GFP_KERNEL); if (!dimm) goto error; mci->dimms[off] = dimm; dimm->mci = mci; /* * Copy DIMM location and initialize it. */ len = sizeof(dimm->label); p = dimm->label; n = snprintf(p, len, "mc#%u", mc_num); p += n; len -= n; for (j = 0; j < n_layers; j++) { n = snprintf(p, len, "%s#%u", edac_layer_name[layers[j].type], pos[j]); p += n; len -= n; dimm->location[j] = pos[j]; if (len <= 0) break; } /* Link it to the csrows old API data */ chan->dimm = dimm; dimm->csrow = row; dimm->cschannel = chn; /* Increment csrow location */ if (layers[0].is_virt_csrow) { chn++; if (chn == tot_channels) { chn = 0; row++; } } else { row++; if (row == tot_csrows) { row = 0; chn++; } } /* Increment dimm location */ for (j = n_layers - 1; j >= 0; j--) { pos[j]++; if (pos[j] < layers[j].size) break; pos[j] = 0; } } mci->op_state = OP_ALLOC; return mci; error: _edac_mc_free(mci); return NULL; } EXPORT_SYMBOL_GPL(edac_mc_alloc); void edac_mc_free(struct mem_ctl_info *mci) { edac_dbg(1, "\n"); /* If we're not yet registered with sysfs free only what was allocated * in edac_mc_alloc(). */ if (!device_is_registered(&mci->dev)) { _edac_mc_free(mci); return; } /* the mci instance is freed here, when the sysfs object is dropped */ edac_unregister_sysfs(mci); } EXPORT_SYMBOL_GPL(edac_mc_free); bool edac_has_mcs(void) { bool ret; mutex_lock(&mem_ctls_mutex); ret = list_empty(&mc_devices); mutex_unlock(&mem_ctls_mutex); return !ret; } EXPORT_SYMBOL_GPL(edac_has_mcs); /* Caller must hold mem_ctls_mutex */ static struct mem_ctl_info *__find_mci_by_dev(struct device *dev) { struct mem_ctl_info *mci; struct list_head *item; edac_dbg(3, "\n"); list_for_each(item, &mc_devices) { mci = list_entry(item, struct mem_ctl_info, link); if (mci->pdev == dev) return mci; } return NULL; } /** * find_mci_by_dev * * scan list of controllers looking for the one that manages * the 'dev' device * @dev: pointer to a struct device related with the MCI */ struct mem_ctl_info *find_mci_by_dev(struct device *dev) { struct mem_ctl_info *ret; mutex_lock(&mem_ctls_mutex); ret = __find_mci_by_dev(dev); mutex_unlock(&mem_ctls_mutex); return ret; } EXPORT_SYMBOL_GPL(find_mci_by_dev); /* * edac_mc_workq_function * performs the operation scheduled by a workq request */ static void edac_mc_workq_function(struct work_struct *work_req) { struct delayed_work *d_work = to_delayed_work(work_req); struct mem_ctl_info *mci = to_edac_mem_ctl_work(d_work); mutex_lock(&mem_ctls_mutex); if (mci->op_state != OP_RUNNING_POLL) { mutex_unlock(&mem_ctls_mutex); return; } if (edac_op_state == EDAC_OPSTATE_POLL) mci->edac_check(mci); mutex_unlock(&mem_ctls_mutex); /* Queue ourselves again. */ edac_queue_work(&mci->work, msecs_to_jiffies(edac_mc_get_poll_msec())); } /* * edac_mc_reset_delay_period(unsigned long value) * * user space has updated our poll period value, need to * reset our workq delays */ void edac_mc_reset_delay_period(unsigned long value) { struct mem_ctl_info *mci; struct list_head *item; mutex_lock(&mem_ctls_mutex); list_for_each(item, &mc_devices) { mci = list_entry(item, struct mem_ctl_info, link); if (mci->op_state == OP_RUNNING_POLL) edac_mod_work(&mci->work, value); } mutex_unlock(&mem_ctls_mutex); } /* Return 0 on success, 1 on failure. * Before calling this function, caller must * assign a unique value to mci->mc_idx. * * locking model: * * called with the mem_ctls_mutex lock held */ static int add_mc_to_global_list(struct mem_ctl_info *mci) { struct list_head *item, *insert_before; struct mem_ctl_info *p; insert_before = &mc_devices; p = __find_mci_by_dev(mci->pdev); if (unlikely(p != NULL)) goto fail0; list_for_each(item, &mc_devices) { p = list_entry(item, struct mem_ctl_info, link); if (p->mc_idx >= mci->mc_idx) { if (unlikely(p->mc_idx == mci->mc_idx)) goto fail1; insert_before = item; break; } } list_add_tail_rcu(&mci->link, insert_before); return 0; fail0: edac_printk(KERN_WARNING, EDAC_MC, "%s (%s) %s %s already assigned %d\n", dev_name(p->pdev), edac_dev_name(mci), p->mod_name, p->ctl_name, p->mc_idx); return 1; fail1: edac_printk(KERN_WARNING, EDAC_MC, "bug in low-level driver: attempt to assign\n" " duplicate mc_idx %d in %s()\n", p->mc_idx, __func__); return 1; } static int del_mc_from_global_list(struct mem_ctl_info *mci) { list_del_rcu(&mci->link); /* these are for safe removal of devices from global list while * NMI handlers may be traversing list */ synchronize_rcu(); INIT_LIST_HEAD(&mci->link); return list_empty(&mc_devices); } struct mem_ctl_info *edac_mc_find(int idx) { struct mem_ctl_info *mci = NULL; struct list_head *item; mutex_lock(&mem_ctls_mutex); list_for_each(item, &mc_devices) { mci = list_entry(item, struct mem_ctl_info, link); if (mci->mc_idx >= idx) { if (mci->mc_idx == idx) { goto unlock; } break; } } unlock: mutex_unlock(&mem_ctls_mutex); return mci; } EXPORT_SYMBOL(edac_mc_find); /* FIXME - should a warning be printed if no error detection? correction? */ int edac_mc_add_mc_with_groups(struct mem_ctl_info *mci, const struct attribute_group **groups) { int ret = -EINVAL; edac_dbg(0, "\n"); if (mci->mc_idx >= EDAC_MAX_MCS) { pr_warn_once("Too many memory controllers: %d\n", mci->mc_idx); return -ENODEV; } #ifdef CONFIG_EDAC_DEBUG if (edac_debug_level >= 3) edac_mc_dump_mci(mci); if (edac_debug_level >= 4) { int i; for (i = 0; i < mci->nr_csrows; i++) { struct csrow_info *csrow = mci->csrows[i]; u32 nr_pages = 0; int j; for (j = 0; j < csrow->nr_channels; j++) nr_pages += csrow->channels[j]->dimm->nr_pages; if (!nr_pages) continue; edac_mc_dump_csrow(csrow); for (j = 0; j < csrow->nr_channels; j++) if (csrow->channels[j]->dimm->nr_pages) edac_mc_dump_channel(csrow->channels[j]); } for (i = 0; i < mci->tot_dimms; i++) if (mci->dimms[i]->nr_pages) edac_mc_dump_dimm(mci->dimms[i], i); } #endif mutex_lock(&mem_ctls_mutex); if (edac_mc_owner && edac_mc_owner != mci->mod_name) { ret = -EPERM; goto fail0; } if (add_mc_to_global_list(mci)) goto fail0; /* set load time so that error rate can be tracked */ mci->start_time = jiffies; mci->bus = &mc_bus[mci->mc_idx]; if (edac_create_sysfs_mci_device(mci, groups)) { edac_mc_printk(mci, KERN_WARNING, "failed to create sysfs device\n"); goto fail1; } if (mci->edac_check) { mci->op_state = OP_RUNNING_POLL; INIT_DELAYED_WORK(&mci->work, edac_mc_workq_function); edac_queue_work(&mci->work, msecs_to_jiffies(edac_mc_get_poll_msec())); } else { mci->op_state = OP_RUNNING_INTERRUPT; } /* Report action taken */ edac_mc_printk(mci, KERN_INFO, "Giving out device to module %s controller %s: DEV %s (%s)\n", mci->mod_name, mci->ctl_name, mci->dev_name, edac_op_state_to_string(mci->op_state)); edac_mc_owner = mci->mod_name; mutex_unlock(&mem_ctls_mutex); return 0; fail1: del_mc_from_global_list(mci); fail0: mutex_unlock(&mem_ctls_mutex); return ret; } EXPORT_SYMBOL_GPL(edac_mc_add_mc_with_groups); struct mem_ctl_info *edac_mc_del_mc(struct device *dev) { struct mem_ctl_info *mci; edac_dbg(0, "\n"); mutex_lock(&mem_ctls_mutex); /* find the requested mci struct in the global list */ mci = __find_mci_by_dev(dev); if (mci == NULL) { mutex_unlock(&mem_ctls_mutex); return NULL; } /* mark MCI offline: */ mci->op_state = OP_OFFLINE; if (del_mc_from_global_list(mci)) edac_mc_owner = NULL; mutex_unlock(&mem_ctls_mutex); if (mci->edac_check) edac_stop_work(&mci->work); /* remove from sysfs */ edac_remove_sysfs_mci_device(mci); edac_printk(KERN_INFO, EDAC_MC, "Removed device %d for %s %s: DEV %s\n", mci->mc_idx, mci->mod_name, mci->ctl_name, edac_dev_name(mci)); return mci; } EXPORT_SYMBOL_GPL(edac_mc_del_mc); static void edac_mc_scrub_block(unsigned long page, unsigned long offset, u32 size) { struct page *pg; void *virt_addr; unsigned long flags = 0; edac_dbg(3, "\n"); /* ECC error page was not in our memory. Ignore it. */ if (!pfn_valid(page)) return; /* Find the actual page structure then map it and fix */ pg = pfn_to_page(page); if (PageHighMem(pg)) local_irq_save(flags); virt_addr = kmap_atomic(pg); /* Perform architecture specific atomic scrub operation */ edac_atomic_scrub(virt_addr + offset, size); /* Unmap and complete */ kunmap_atomic(virt_addr); if (PageHighMem(pg)) local_irq_restore(flags); } /* FIXME - should return -1 */ int edac_mc_find_csrow_by_page(struct mem_ctl_info *mci, unsigned long page) { struct csrow_info **csrows = mci->csrows; int row, i, j, n; edac_dbg(1, "MC%d: 0x%lx\n", mci->mc_idx, page); row = -1; for (i = 0; i < mci->nr_csrows; i++) { struct csrow_info *csrow = csrows[i]; n = 0; for (j = 0; j < csrow->nr_channels; j++) { struct dimm_info *dimm = csrow->channels[j]->dimm; n += dimm->nr_pages; } if (n == 0) continue; edac_dbg(3, "MC%d: first(0x%lx) page(0x%lx) last(0x%lx) mask(0x%lx)\n", mci->mc_idx, csrow->first_page, page, csrow->last_page, csrow->page_mask); if ((page >= csrow->first_page) && (page <= csrow->last_page) && ((page & csrow->page_mask) == (csrow->first_page & csrow->page_mask))) { row = i; break; } } if (row == -1) edac_mc_printk(mci, KERN_ERR, "could not look up page error address %lx\n", (unsigned long)page); return row; } EXPORT_SYMBOL_GPL(edac_mc_find_csrow_by_page); const char *edac_layer_name[] = { [EDAC_MC_LAYER_BRANCH] = "branch", [EDAC_MC_LAYER_CHANNEL] = "channel", [EDAC_MC_LAYER_SLOT] = "slot", [EDAC_MC_LAYER_CHIP_SELECT] = "csrow", [EDAC_MC_LAYER_ALL_MEM] = "memory", }; EXPORT_SYMBOL_GPL(edac_layer_name); static void edac_inc_ce_error(struct mem_ctl_info *mci, bool enable_per_layer_report, const int pos[EDAC_MAX_LAYERS], const u16 count) { int i, index = 0; mci->ce_mc += count; if (!enable_per_layer_report) { mci->ce_noinfo_count += count; return; } for (i = 0; i < mci->n_layers; i++) { if (pos[i] < 0) break; index += pos[i]; mci->ce_per_layer[i][index] += count; if (i < mci->n_layers - 1) index *= mci->layers[i + 1].size; } } static void edac_inc_ue_error(struct mem_ctl_info *mci, bool enable_per_layer_report, const int pos[EDAC_MAX_LAYERS], const u16 count) { int i, index = 0; mci->ue_mc += count; if (!enable_per_layer_report) { mci->ue_noinfo_count += count; return; } for (i = 0; i < mci->n_layers; i++) { if (pos[i] < 0) break; index += pos[i]; mci->ue_per_layer[i][index] += count; if (i < mci->n_layers - 1) index *= mci->layers[i + 1].size; } } static void edac_ce_error(struct mem_ctl_info *mci, const u16 error_count, const int pos[EDAC_MAX_LAYERS], const char *msg, const char *location, const char *label, const char *detail, const char *other_detail, const bool enable_per_layer_report, const unsigned long page_frame_number, const unsigned long offset_in_page, long grain) { unsigned long remapped_page; char *msg_aux = ""; if (*msg) msg_aux = " "; if (edac_mc_get_log_ce()) { if (other_detail && *other_detail) edac_mc_printk(mci, KERN_WARNING, "%d CE %s%son %s (%s %s - %s)\n", error_count, msg, msg_aux, label, location, detail, other_detail); else edac_mc_printk(mci, KERN_WARNING, "%d CE %s%son %s (%s %s)\n", error_count, msg, msg_aux, label, location, detail); } edac_inc_ce_error(mci, enable_per_layer_report, pos, error_count); if (mci->scrub_mode == SCRUB_SW_SRC) { /* * Some memory controllers (called MCs below) can remap * memory so that it is still available at a different * address when PCI devices map into memory. * MC's that can't do this, lose the memory where PCI * devices are mapped. This mapping is MC-dependent * and so we call back into the MC driver for it to * map the MC page to a physical (CPU) page which can * then be mapped to a virtual page - which can then * be scrubbed. */ remapped_page = mci->ctl_page_to_phys ? mci->ctl_page_to_phys(mci, page_frame_number) : page_frame_number; edac_mc_scrub_block(remapped_page, offset_in_page, grain); } } static void edac_ue_error(struct mem_ctl_info *mci, const u16 error_count, const int pos[EDAC_MAX_LAYERS], const char *msg, const char *location, const char *label, const char *detail, const char *other_detail, const bool enable_per_layer_report) { char *msg_aux = ""; if (*msg) msg_aux = " "; if (edac_mc_get_log_ue()) { if (other_detail && *other_detail) edac_mc_printk(mci, KERN_WARNING, "%d UE %s%son %s (%s %s - %s)\n", error_count, msg, msg_aux, label, location, detail, other_detail); else edac_mc_printk(mci, KERN_WARNING, "%d UE %s%son %s (%s %s)\n", error_count, msg, msg_aux, label, location, detail); } if (edac_mc_get_panic_on_ue()) { if (other_detail && *other_detail) panic("UE %s%son %s (%s%s - %s)\n", msg, msg_aux, label, location, detail, other_detail); else panic("UE %s%son %s (%s%s)\n", msg, msg_aux, label, location, detail); } edac_inc_ue_error(mci, enable_per_layer_report, pos, error_count); } void edac_raw_mc_handle_error(const enum hw_event_mc_err_type type, struct mem_ctl_info *mci, struct edac_raw_error_desc *e) { char detail[80]; int pos[EDAC_MAX_LAYERS] = { e->top_layer, e->mid_layer, e->low_layer }; /* Memory type dependent details about the error */ if (type == HW_EVENT_ERR_CORRECTED) { snprintf(detail, sizeof(detail), "page:0x%lx offset:0x%lx grain:%ld syndrome:0x%lx", e->page_frame_number, e->offset_in_page, e->grain, e->syndrome); edac_ce_error(mci, e->error_count, pos, e->msg, e->location, e->label, detail, e->other_detail, e->enable_per_layer_report, e->page_frame_number, e->offset_in_page, e->grain); } else { snprintf(detail, sizeof(detail), "page:0x%lx offset:0x%lx grain:%ld", e->page_frame_number, e->offset_in_page, e->grain); edac_ue_error(mci, e->error_count, pos, e->msg, e->location, e->label, detail, e->other_detail, e->enable_per_layer_report); } } EXPORT_SYMBOL_GPL(edac_raw_mc_handle_error); void edac_mc_handle_error(const enum hw_event_mc_err_type type, struct mem_ctl_info *mci, const u16 error_count, const unsigned long page_frame_number, const unsigned long offset_in_page, const unsigned long syndrome, const int top_layer, const int mid_layer, const int low_layer, const char *msg, const char *other_detail) { char *p; int row = -1, chan = -1; int pos[EDAC_MAX_LAYERS] = { top_layer, mid_layer, low_layer }; int i, n_labels = 0; u8 grain_bits; struct edac_raw_error_desc *e = &mci->error_desc; edac_dbg(3, "MC%d\n", mci->mc_idx); /* Fills the error report buffer */ memset(e, 0, sizeof (*e)); e->error_count = error_count; e->top_layer = top_layer; e->mid_layer = mid_layer; e->low_layer = low_layer; e->page_frame_number = page_frame_number; e->offset_in_page = offset_in_page; e->syndrome = syndrome; e->msg = msg; e->other_detail = other_detail; /* * Check if the event report is consistent and if the memory * location is known. If it is known, enable_per_layer_report will be * true, the DIMM(s) label info will be filled and the per-layer * error counters will be incremented. */ for (i = 0; i < mci->n_layers; i++) { if (pos[i] >= (int)mci->layers[i].size) { edac_mc_printk(mci, KERN_ERR, "INTERNAL ERROR: %s value is out of range (%d >= %d)\n", edac_layer_name[mci->layers[i].type], pos[i], mci->layers[i].size); /* * Instead of just returning it, let's use what's * known about the error. The increment routines and * the DIMM filter logic will do the right thing by * pointing the likely damaged DIMMs. */ pos[i] = -1; } if (pos[i] >= 0) e->enable_per_layer_report = true; } /* * Get the dimm label/grain that applies to the match criteria. * As the error algorithm may not be able to point to just one memory * stick, the logic here will get all possible labels that could * pottentially be affected by the error. * On FB-DIMM memory controllers, for uncorrected errors, it is common * to have only the MC channel and the MC dimm (also called "branch") * but the channel is not known, as the memory is arranged in pairs, * where each memory belongs to a separate channel within the same * branch. */ p = e->label; *p = '\0'; for (i = 0; i < mci->tot_dimms; i++) { struct dimm_info *dimm = mci->dimms[i]; if (top_layer >= 0 && top_layer != dimm->location[0]) continue; if (mid_layer >= 0 && mid_layer != dimm->location[1]) continue; if (low_layer >= 0 && low_layer != dimm->location[2]) continue; /* get the max grain, over the error match range */ if (dimm->grain > e->grain) e->grain = dimm->grain; /* * If the error is memory-controller wide, there's no need to * seek for the affected DIMMs because the whole * channel/memory controller/... may be affected. * Also, don't show errors for empty DIMM slots. */ if (e->enable_per_layer_report && dimm->nr_pages) { if (n_labels >= EDAC_MAX_LABELS) { e->enable_per_layer_report = false; break; } n_labels++; if (p != e->label) { strcpy(p, OTHER_LABEL); p += strlen(OTHER_LABEL); } strcpy(p, dimm->label); p += strlen(p); *p = '\0'; /* * get csrow/channel of the DIMM, in order to allow * incrementing the compat API counters */ edac_dbg(4, "%s csrows map: (%d,%d)\n", mci->csbased ? "rank" : "dimm", dimm->csrow, dimm->cschannel); if (row == -1) row = dimm->csrow; else if (row >= 0 && row != dimm->csrow) row = -2; if (chan == -1) chan = dimm->cschannel; else if (chan >= 0 && chan != dimm->cschannel) chan = -2; } } if (!e->enable_per_layer_report) { strcpy(e->label, "any memory"); } else { edac_dbg(4, "csrow/channel to increment: (%d,%d)\n", row, chan); if (p == e->label) strcpy(e->label, "unknown memory"); if (type == HW_EVENT_ERR_CORRECTED) { if (row >= 0) { mci->csrows[row]->ce_count += error_count; if (chan >= 0) mci->csrows[row]->channels[chan]->ce_count += error_count; } } else if (row >= 0) mci->csrows[row]->ue_count += error_count; } /* Fill the RAM location data */ p = e->location; for (i = 0; i < mci->n_layers; i++) { if (pos[i] < 0) continue; p += sprintf(p, "%s:%d ", edac_layer_name[mci->layers[i].type], pos[i]); } if (p > e->location) *(p - 1) = '\0'; /* Report the error via the trace interface */ grain_bits = fls_long(e->grain) + 1; if (IS_ENABLED(CONFIG_RAS)) trace_mc_event(type, e->msg, e->label, e->error_count, mci->mc_idx, e->top_layer, e->mid_layer, e->low_layer, (e->page_frame_number << PAGE_SHIFT) | e->offset_in_page, grain_bits, e->syndrome, e->other_detail); edac_raw_mc_handle_error(type, mci, e); } EXPORT_SYMBOL_GPL(edac_mc_handle_error);
__label__pos
0.999377
Hi, after the previouses answers about not sleeping tasks ( mailing list thread "task scheduling e priority"* *) i ask you how to reschedule a not sleeping task. I explain better: if my xenomai primary task work for example for 7 seconds without sleep the other task and linux don't work. How can i run the task for a estabilished time ( for example 10 ms ) and start schedule for other task without insert in the task sleep or other instruction ? thanks a lot Roberto Bielli _______________________________________________ Xenomai-core mailing list [email protected] https://mail.gna.org/listinfo/xenomai-core Reply via email to
__label__pos
0.953137
Define different types of Input and Output arguments for custom workflow activity As a MS Dynamics CRM Developer there are certain situations where you need to pass some of the entity field values as Input arguments to a Custom Workflow activity and some cases you may require to get some of the code execution results as Output arguments from a custom workflow activity. In order to accomplish this you definitely need to have an idea on the Syntax of the Input and Output arguments for different types of fields. Here i considered an entity called Patient which is having different types of fields and those are given below 1. Patient Name : String 2. Date Of Birth : Date and Time 3. Hospital : Lookup (to an entity called Hospital) 4. Patient Status : Option Set 5. Hospitalization Required : Two Option Set 6. Patient Age : Whole Number 7. Consultation Fee : Decimal Number 8. Estimated Amount : Floating Point Number 9. Treatment Cost : Currency 10. Patient Id : String Types of arguments 1. Input : Entity field value can be passed to Custom workflow activity 2. Output : Execution result (if any) can be passed as output from Custom workflow activity 3. Input/Output : It can be used as both Input and Output The following Custom Workflow Activity code will explains how to declare Input and Output arguments. using System; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Workflow; using System.Activities; namespace InputOutputParameters { public class InputOutputParameters : CodeActivity { //Data Type : String [Input("patientname")] [RequiredArgument] public InArgument<string> PatientName { get; set; } //Data Type : Date and Time [Input("dateofbirth")] [RequiredArgument] public InArgument DateOfBirth { get; set; } //Data Type : Lookup [Input("hospital")] [ReferenceTarget("new_hospital")] [RequiredArgument] public InArgument Hospital { get; set; } //Data Type : Option Set [Input("patientstatus")] [RequiredArgument] [AttributeTarget("new_patient", "statuscode")] public InArgument PatientStatus { get; set; } //Data Type : Two Option Set [Input("hospitalizationrequired")] [RequiredArgument] public InArgument<bool> HospitalizationRequired { get; set; } //Data Type : Whole Number [Input("patientage")] [RequiredArgument] public InArgument<int> PatientAge { get; set; } //Data Type : Decimal Number [Input("consultationfee")] [RequiredArgument] public InArgument<decimal> ConsultationFee { get; set; } //Data Type : Floating Point Number [Input("estimatedamount")] [RequiredArgument] public InArgument<decimal> EstimatedAmount { get; set; } //Data Type : Currency [Input("treatmentcost")] [RequiredArgument] public InArgument TreatmentCost { get; set; } //Data Type : String [Output("showpatientdetails")] public OutArgument<string> ShowPatientDetails { get; set; } //Data Type : String (Can be used as Input/Output) [Input("patientinput")] [Output("patientoutput")] [RequiredArgument] public InOutArgument<string> PatientInOut { get; set; } protected override void Execute(CodeActivityContext context) { try { IWorkflowContext workflowContext = context.GetExtension(); IOrganizationServiceFactory serviceFactory = context.GetExtension(); IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId); ITracingService tracingService = context.GetExtension(); tracingService.Trace("Patient Details using input and output parameters Workflow Started."); var patientName = PatientName.Get(context); var dateOfBirth = DateOfBirth.Get(context); var hospital = Hospital.Get(context)?.Name; var patientStatus = PatientStatus.Get(context).Value; var hospitalizationRequired = HospitalizationRequired.Get(context); var patientAge = PatientAge.Get(context); var consultationFee = ConsultationFee.Get(context); var estimatedAmount = EstimatedAmount.Get(context); var treatmentCost = TreatmentCost.Get(context).Value; var patientId = PatientInOut.Get(context); tracingService.Trace($"Patient Name : {patientName}, Date Of Birth : {dateOfBirth}, Hospital : {hospital}, Patient Status : {patientStatus}, Hospitalization Required: {hospitalizationRequired}, Patient Age: {patientAge}, Consultation Fee : {consultationFee}, Estimated Amount : {estimatedAmount}, Treatment Cost : {treatmentCost}, Patient ID : {patientId}"); var patientDetails = $"Patient Name : {patientName}, Date Of Birth : {dateOfBirth}, Hospital : {hospital}, Patient Status : {patientStatus}, Hospitalization Required: {hospitalizationRequired}, Patient Age: {patientAge}, Consultation Fee : {consultationFee}, Estimated Amount : {estimatedAmount}, Treatment Cost : {treatmentCost}, Patient ID : {patientId}"; PatientInOut.Set(context, PatientInOut.ToString()); ShowPatientDetails.Set(context, patientDetails); tracingService.Trace("Patient Details using input and output parameters Workflow Ended."); } catch(Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } } }   The below screen shot will show you the representation of the Input arguments once after you successfully build and deploy the above custom workflow code activity. Input_Output_Parameters Download Dynamics CRM Tools for v9.x Steps to be followed: 1. Go to Windows, Search for “Windows Power Shell” and Open it. (Shown below) Windows PowerShell 2. Navigate to the folder where you want to download the tools, for example if you want to download in a D365Tools folder in  C drive, Type  cd D365Tools\ (Shown Below) Windows PowerShell 3. Copy  and paste  the following Power Shell script in to the Power Shell window and Press Enter. (Shown Below) $sourceNugetExe = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" $targetNugetExe = ".\nuget.exe" Remove-Item .\Tools -Force -Recurse -ErrorAction Ignore Invoke-WebRequest $sourceNugetExe -OutFile $targetNugetExe Set-Alias nuget $targetNugetExe -Scope Global -Verbose ## ##Download Plugin Registration Tool ## ./nuget install Microsoft.CrmSdk.XrmTooling.PluginRegistrationTool -O .\Tools md .\Tools\PluginRegistration $prtFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.PluginRegistrationTool.'} move .\Tools\$prtFolder\tools\*.* .\Tools\PluginRegistration Remove-Item .\Tools\$prtFolder -Force -Recurse ## ##Download CoreTools ## ./nuget install Microsoft.CrmSdk.CoreTools -O .\Tools md .\Tools\CoreTools $coreToolsFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.CoreTools.'} move .\Tools\$coreToolsFolder\content\bin\coretools\*.* .\Tools\CoreTools Remove-Item .\Tools\$coreToolsFolder -Force -Recurse ## ##Download Configuration Migration ## ./nuget install Microsoft.CrmSdk.XrmTooling.ConfigurationMigration.Wpf -O .\Tools md .\Tools\ConfigurationMigration $configMigFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.ConfigurationMigration.Wpf.'} move .\Tools\$configMigFolder\tools\*.* .\Tools\ConfigurationMigration Remove-Item .\Tools\$configMigFolder -Force -Recurse ## ##Download Package Deployer ## ./nuget install Microsoft.CrmSdk.XrmTooling.PackageDeployment.WPF -O .\Tools md .\Tools\PackageDeployment $pdFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.PackageDeployment.Wpf.'} move .\Tools\$pdFolder\tools\*.* .\Tools\PackageDeployment Remove-Item .\Tools\$pdFolder -Force -Recurse ## ##Download Package Deployer PowerShell module ## ./nuget install Microsoft.CrmSdk.XrmTooling.PackageDeployment.PowerShell -O .\Tools $pdPoshFolder = Get-ChildItem ./Tools | Where-Object {$_.Name -match 'Microsoft.CrmSdk.XrmTooling.PackageDeployment.PowerShell.'} move .\Tools\$pdPoshFolder\tools\*.* .\Tools\PackageDeployment.PowerShell Remove-Item .\Tools\$pdPoshFolder -Force -Recurse ## ##Remove NuGet.exe ## Remove-Item nuget.exe Windows PowerShell 4. You will find the Tools in the folder C:\D365Tools\Tools (The folder you mentioned before) 5. To get the latest version of the tools, Repeat the same steps. The most used code snippets in Dynamics365
__label__pos
0.999254
Build a search engine in 20 minutes or less [This article was first published on Anything but R-bitrary, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here) Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. …or your money back. The author = "Ben Ogorek" Twitter = "@baogorek" email = paste0(sub("@", "", Twitter), "@gmail.com") Setup Pretend this is Big Data: doc1 <- "Stray cats are running all over the place. I see 10 a day!" doc2 <- "Cats are killers. They kill billions of animals a year." doc3 <- "The best food in Columbus, OH is the North Market." doc4 <- "Brand A is the best tasting cat food around. Your cat will love it." doc5 <- "Buy Brand C cat food for your cat. Brand C makes healthy and happy cats." doc6 <- "The Arnold Classic came to town this weekend. It reminds us to be healthy." doc7 <- "I have nothing to say. In summary, I have told you nothing." and this is the Big File System: doc.list <- list(doc1, doc2, doc3, doc4, doc5, doc6, doc7) N.docs <- length(doc.list) names(doc.list) <- paste0("doc", c(1:N.docs)) You have an information need that is expressed via the following text query: query <- "Healthy cat food" How will you meet your information need amidst all this unstructured text? Jokes aside, we're going to use an old method, one that's tried and true, one that goes way back to the 1960's. We're going to implement the vector space model of information retrieval in R. In the process, you'll hopefully learn something about the tm package and about the analysis of unstructured data before it was Big. Text mining in R Fundamentals of the tm package If you have not installed the tm [1][2] and Snowball [3] packages, please do so now. install.packages("tm") install.packages("Snowball") Load the tm package into memory. library(tm) In text mining and related fields, a corpus is a collection of texts, often with extensive manual annotation. Not surprisingly, the Corpus class is a fundamental data structure in tm. my.docs <- VectorSource(c(doc.list, query)) my.docs$Names <- c(names(doc.list), "query") my.corpus <- Corpus(my.docs) my.corpus ## A corpus with 8 text documents Above we treated the query like any other document. It is, after all, just another string of text. Queries are not typically known a priori, but in the processing steps that follow, we will pretend like we knew ours in advance to avoid repeating steps. Standardizing One of the nice things about the Corpus class is the tm_map function, which cleans and standardizes documents within a Corpus object. Below are some of the transformations. getTransformations() ## [1] "as.PlainTextDocument" "removeNumbers" "removePunctuation" ## [4] "removeWords" "stemDocument" "stripWhitespace" First, let's get rid of punctuation. my.corpus <- tm_map(my.corpus, removePunctuation) my.corpus$doc1 ## Stray cats are running all over the place I see 10 a day Suppose we don't want to count “cats” and “cat” as two separate words. Then we will use the stemDocument transformation to implement the famous Porter Stemmer algorithm. To use this particular transformation, first load the Snowball package. library(Snowball) my.corpus <- tm_map(my.corpus, stemDocument) my.corpus$doc1 ## Stray cat are run all over the place I see 10 a day Finally, remove numbers and any extra white space. my.corpus <- tm_map(my.corpus, removeNumbers) my.corpus <- tm_map(my.corpus, tolower) my.corpus <- tm_map(my.corpus, stripWhitespace) my.corpus$doc1 ## stray cat are run all over the place i see a day We applied all these standardization techniques without much thought. For instance, we sacrificed inflection in favor of fewer words. But at least the transformations make sense on a heuristic level, much like the similarity concepts to follow. The vector space model Document similarity Here's a trick that's been around for a while: represent each document as a vector in \( \mathcal{R}^N \) (with \( N \) as the number of words) and use the angle \( \theta \) between the vectors as a similarity measure. Rank by the similarity of each document to the query and you have a search engine. One of the simplest things we can do is to count words within documents. This naturally forms a two dimensional structure, the term document matrix, with rows corresponding to the words and the columns corresponding to the documents. As with any matrix, we may think of a term document matrix as a collection of column vectors existing in a space defined by the rows. The query lives in this space as well, though in practice we wouldn't know it beforehand. term.doc.matrix.stm <- TermDocumentMatrix(my.corpus) inspect(term.doc.matrix.stm[0:14, ]) ## A term-document matrix (14 terms, 8 documents) ## ## Non-/sparse entries: 21/91 ## Sparsity : 81% ## Maximal term length: 8 ## Weighting : term frequency (tf) ## ## Docs ## Terms doc1 doc2 doc3 doc4 doc5 doc6 doc7 query ## all 1 0 0 0 0 0 0 0 ## and 0 0 0 0 1 0 0 0 ## anim 0 1 0 0 0 0 0 0 ## are 1 1 0 0 0 0 0 0 ## arnold 0 0 0 0 0 1 0 0 ## around 0 0 0 1 0 0 0 0 ## best 0 0 1 1 0 0 0 0 ## billion 0 1 0 0 0 0 0 0 ## brand 0 0 0 1 2 0 0 0 ## buy 0 0 0 0 1 0 0 0 ## came 0 0 0 0 0 1 0 0 ## cat 1 1 0 2 3 0 0 1 ## classic 0 0 0 0 0 1 0 0 ## columbus 0 0 1 0 0 0 0 0 Sparsity and storage of the term document matrix The matrices in tm are of type Simple Triplet Matrix where only the triples \( (i, j, value) \) are stored for non-zero values. To work directly with these objects, you may use install the slam [4] package. We bear some extra cost by making the matrix “dense” (i.e., storing all the zeros) below. term.doc.matrix <- as.matrix(term.doc.matrix.stm) cat("Dense matrix representation costs", object.size(term.doc.matrix), "bytes.\n", "Simple triplet matrix representation costs", object.size(term.doc.matrix.stm), "bytes.") ## Dense matrix representation costs 6688 bytes. ## Simple triplet matrix representation costs 5808 bytes. Variations on a theme In term.doc.matrix, the dimensions of the document space are simple term frequencies. This is fine, but other heuristics are available. For instance, rather than a linear increase in the term frequency \( tf \), perhaps \( \sqrt(tf) \) or \( \log(tf) \) would provide a more reasonable diminishing returns on word counts within documents. Rare words can also get a boost. The word “healthy” appears in only one document, whereas “cat” appears in four. A word's document frequency \( df \) is the number of documents that contain it, and a natural choice is to weight words inversely proportional to their \( df \)s. As with term frequency, we may use logarithms or other transformations to achieve the desired effect. The tm function weightTfIdf offers one variety of tfidf weighting, but below we build our own. Visit the Wikipedia page for the SMART Information Retrieval System for a brief history and a list of popular weighting choices. Different weighting choices are often made for the query and the documents. For instance, Manning et al.'s worked example [5] uses \( idf \) weighting only for the query. Choice and implementation For both the document and query, we choose tfidf weights of \( (1 + \log_2(tf)) \times \log_2(N/df) \), which are defined to be \( 0 \) if \( tf = 0 \). Note that whenever a term does not occur in a specific document, or when it appears in every document, its weight is zero. We implement this weighting function across entire rows of the term document matrix, and therefore our tfidf function must take a term frequency vector and a document frequency scalar as inputs. get.tf.idf.weights <- function(tf.vec, df) { # Computes tfidf weights from a term frequency vector and a document # frequency scalar weight = rep(0, length(tf.vec)) weight[tf.vec > 0] = (1 + log2(tf.vec[tf.vec > 0])) * log2(N.docs/df) weight } cat("A word appearing in 4 of 6 documents, occuring 1, 2, 3, and 6 times, respectively: \n", get.tf.idf.weights(c(1, 2, 3, 0, 0, 6), 4)) ## A word appearing in 4 of 6 documents, occuring 1, 2, 3, and 6 times, respectively: ## 0.8074 1.615 2.087 0 0 2.894 Using apply, we run the tfidf weighting function on every row of the term document matrix. The document frequency is easily derived from each row by the counting the non-zero entries (not including the query). get.weights.per.term.vec <- function(tfidf.row) { term.df <- sum(tfidf.row[1:N.docs] > 0) tf.idf.vec <- get.tf.idf.weights(tfidf.row, term.df) return(tf.idf.vec) } tfidf.matrix <- t(apply(term.doc.matrix, c(1), FUN = get.weights.per.term.vec)) colnames(tfidf.matrix) <- colnames(term.doc.matrix) tfidf.matrix[0:3, ] ## ## Terms doc1 doc2 doc3 doc4 doc5 doc6 doc7 query ## all 2.807 0.000 0 0 0.000 0 0 0 ## and 0.000 0.000 0 0 2.807 0 0 0 ## anim 0.000 2.807 0 0 0.000 0 0 0 Dot product geometry A benefit of being in the vector space \( \mathcal{R}^N \) is the use of its dot product. For vectors \( a \) and \( b \), the geometric definition of the dot product is \( a \cdot b = \vert\vert a\vert\vert \, \vert\vert b \vert \vert \cos \theta \), where \( \vert\vert \cdot \vert \vert \) is the euclidean norm (the root sum of squares) and \( \theta \) is the angle between \( a \) and \( b \). In fact, we can work directly with the cosine of \( \theta \). For \( \theta \) in the interval \( [-\pi, -\pi] \), the endpoints are orthogonality (totally unrelated documents) and the center, zero, is complete collinearity (maximally similar documents). We can see that the cosine decreases from its maximum value of \( 1.0 \) as the angle departs from zero in either direction. angle <- seq(-pi, pi, by = pi/16) plot(cos(angle) ~ angle, type = "b", xlab = "angle in radians", main = "Cosine similarity by angle") plot of chunk unnamed-chunk-16 We may furthermore normalize each column vector in our tfidf matrix so that its norm is one. Now the dot product is \( \cos \theta \). tfidf.matrix <- scale(tfidf.matrix, center = FALSE, scale = sqrt(colSums(tfidf.matrix^2))) tfidf.matrix[0:3, ] ## ## Terms doc1 doc2 doc3 doc4 doc5 doc6 doc7 query ## all 0.3632 0.0000 0 0 0.0000 0 0 0 ## and 0.0000 0.0000 0 0 0.3486 0 0 0 ## anim 0.0000 0.3923 0 0 0.0000 0 0 0 Matrix multiplication: a dot product machine Keeping the query alongside the other documents let us avoid repeating the same steps. But now it's time to pretend it was never there. query.vector <- tfidf.matrix[, (N.docs + 1)] tfidf.matrix <- tfidf.matrix[, 1:N.docs] With the query vector and the set of document vectors in hand, it is time to go after the cosine similarities. These are simple dot products as our vectors have been normalized to unit length. Recall that matrix multiplication is really just a sequence of vector dot products. The matrix operation below returns values of \( \cos \theta \) for each document vector and the query vector. doc.scores <- t(query.vector) %*% tfidf.matrix With scores in hand, rank the documents by their cosine similarities with the query vector. results.df <- data.frame(doc = names(doc.list), score = t(doc.scores), text = unlist(doc.list)) results.df <- results.df[order(results.df$score, decreasing = TRUE), ] The results How did our search engine do? options(width = 2000) print(results.df, row.names = FALSE, right = FALSE, digits = 2) ## doc score text ## doc5 0.344 Buy Brand C cat food for your cat. Brand C makes healthy and happy cats. ## doc6 0.183 The Arnold Classic came to town this weekend. It reminds us to be healthy. ## doc4 0.177 Brand A is the best tasting cat food around. Your cat will love it. ## doc3 0.115 The best food in Columbus, OH is the North Market. ## doc2 0.039 Cats are killers. They kill billions of animals a year. ## doc1 0.036 Stray cats are running all over the place. I see 10 a day! ## doc7 0.000 I have nothing to say. In summary, I have told you nothing. Our “best” document, at least in an intuitive sense, comes out ahead with a score nearly twice as high as its nearest competitor. Notice however that this next competitor has nothing to do with cats. This is due to the relative rareness of the word “healthy” in the documents and our choice to incorporate the inverse document frequency weighting for both documents and query. Fortunately, the profoundly uninformative document 7 has been ranked dead last. Discussion I joked at the beginning that our seven documents were “Big Data.” This is silly but not off the wall. Hadoop is the technology most synonymous with Big Data. What is Hadoop's most common example and use case? Wait… Wait for it… It's counting words in text! Sorry if that disappoints you. To be fair, the programming paradigm used by Hadoop can be made to do many things, and even something as simple as counting words becomes troublesome with enough text and a pressing deadline (i.e., not 20 minutes). But sans deadline and gigabytes of text, we were counting words. Though tfidf weighting and the vector space model may now be old school, its core concepts are still used in industrial search solutions built using Lucene. In more modern (and statistical) approaches based on probabilistic language modeling, documents are ranked by the probability that their underlying language model produced the query [6]. While there's nothing inherently statistical about the vector space model, a link to probabilistic language modeling has been demonstrated [7]. I hope you've enjoyed exploring the tm package and some of the clever ideas introduced by the information retrieval community. Whatever happens with “Big Data,” keep experimenting with text analysis in R! Acknowledgements The markdown [8] and knitr [9] packages, in conjunction with RStudio's IDE [10], were used to create this document. Thanks to Chris Nicholas and Shannon Terry for their comments and feedback. I first learned about information retrieval in Coursera's Stanford Natural Language Processing course taught by Dan Jurafsky and Christopher Manning. Keep up with ours and other great articles on R-Bloggers . References 1. Ingo Feinerer and Kurt Hornik (2013). tm: Text Mining Package. R package version 0.5-8.3. http://CRAN.R-project.org/package=tm 2. Ingo Feinerer, Kurt Hornik, and David Meyer (2008). Text Mining Infrastructure in R. Journal of Statistical Software 25(5): 1-54. URL: http://www.jstatsoft.org/v25/i05/. 3. Kurt Hornik (2013). Snowball: Snowball Stemmers. R package version 0.0-8. http://CRAN.R-project.org/package=Snowball 4. Kurt Hornik, David Meyer and Christian Buchta (2013). slam: Sparse Lightweight Arrays and Matrices. R package version 0.1-28. http://CRAN.R-project.org/package=slam 5. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schutze, Introduction to Information Retrieval, Cambridge University Press. 2008. URL: http://www-nlp.stanford.edu/IR-book/ 6. Hugo Zaragoza, Djoerd Hiemstra, and Michael Tipping. “Bayesian extension to the language model for ad hoc information retrieval.” Proceedings of the 26th annual international ACM SIGIR conference on Research and development in information retrieval. ACM, 2003. URL 7. Thorsten Joachims. A Probabilistic Analysis of the Rocchio Algorithm with TFIDF for Text Categorization. No. CMU-CS-96-118. Carnegie-Mellon University of Pittsburgh, PA. Department of Computer Science, 1996. 8. JJ Allaire, Jeffrey Horner, Vicent Marti and Natacha Porte (2012). markdown: Markdown rendering for R. R package version 0.5.3. http://CRAN.R-project.org/package=markdown 9. Yihui Xie (2012). knitr: A general-purpose package for dynamic report generation in R. R package version 0.6. http://CRAN.R-project.org/package=knitr 10. RStudio IDE for Windows. URL http://www.rstudio.com/ide/ 11. R Core Team (2013). R: A language and environment for statistical computing. R Foundation for Statistical Computing, Vienna, Austria. ISBN 3-900051-07-0, URL: http://www.R-project.org/. To leave a comment for the author, please follow the link and comment on their blog: Anything but R-bitrary. R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job. Want to share your content on R-bloggers? click here if you have a blog, or here if you don't. Never miss an update! Subscribe to R-bloggers to receive e-mails with the latest R posts. (You will not see this message again.) Click here to close (This popup will not appear again)
__label__pos
0.621496
Help Center How can we help? 👋 How can I integrate my HouseCall Pro account with Ply? Step 1: Navigating to Integrations within Ply 1. Go to the settings in the lower left of your Ply account 1. Look for the "Integrations" tab within your settings 1. Then, click on Connect Field Service Management (FSM) to begin integrations 1. Connect your FSM by clicking on the ‘Connect Now’ button 1. Choose HouseCall Pro to begin the integration process. Step 2: Navigating to Integrations within Ply 1. Obtain the HouseCall Pro password by following the steps below:   Did this answer your question? 😞 😐 🤩
__label__pos
1
Erlang Central Difference between revisions of "How to use ei to marshal binary terms in port programs" From ErlangCentral Wiki (Introduction) (Erlang side) Line 19: Line 19:      ==Erlang side==   ==Erlang side== Let's start with writing an Erlang module responsible for marshaling data to and from the C port program.  The module will use erlang:port_command/2 + First, we need to define the data marshaling contract between Erlang and C that will request from C to execute functions and receive the result back. function for asynchronously sending data to the port.  Note that the data is encoded to the external binary term format using erlang:term_to_binary/1. +      The objective of the port program is to be able to implement the following API:   The objective of the port program is to be able to implement the following API:      <pre>   <pre> Erlang -> C                                 C -> Erlang + Erlang -> C           C -> Erlang ===========                                 =========== + ===========           ===========    {add,      X::integer(), Y::integer()}  ->  {ok, Result::integer()} | {error, Reason::atom()} + {add,      X, Y}  ->  {ok, Result::integer()} | {error, Reason::atom()} {multiply, X::integer(), Y::integer()}  ->  {ok, Result::integer()} | {error, Reason::atom()} + {multiply, X, Y}  ->  {ok, Result::integer()} | {error, Reason::atom()} {divide,  A,           B}             ->  {ok, Result::float()}  | {error, Reason::atom()} + {divide,  A, B} ->  {ok, Result::float()}  | {error, Reason::atom()}  +   X = integer()  +   Y = integer()      A = integer() | float()      A = integer() | float()      B = integer() | float()      B = integer() | float() Line 36: Line 37:      Where the add, multiply, and divide instructions perform the corresponding action on the C-side given two arguments.   Where the add, multiply, and divide instructions perform the corresponding action on the C-side given two arguments.  +  + Let's start with writing an Erlang module responsible for marshaling data to and from the C port program.  The module will use <tt>erlang:port_command/2</tt> function for asynchronously sending data to the port.  Note that the data is encoded to the external binary term format using <tt>erlang:term_to_binary/1</tt>.      {{CodeSnippet|Erlang module listing|<pre>   {{CodeSnippet|Erlang module listing|<pre> Revision as of 02:47, 21 March 2008 Contents Author Serge Aleynikov <saleyn at gmail.com> Overview The purpose of this tutorial is to illustrate how to use ei interface library (C API) for dealing with the Erlang binary term format used in marshaling data between an Erlang node and external port programs. The reader is also encouraged to read another how to guide by Pete Kazmer that focuses on using OTP framework for building Erlang systems that interface with external programs. ei offers a simple and convenient interface that makes it possible to communicate with Erlang from virtually any language that can call native C functions. Introduction The earlier releases of Erlang/OTP came with erl_interface library that later evolved into ei (Erlang Interface). The difference between ei and erl_interface is that in the contrast to erl_interface ei uses the binary format directly when sending and receiving terms in communications with an Erlang node, and it can use a given memory buffer without involving dynamic memory. While ei seems to be the preferred method of encoding/decoding terms, most of the help documents provided with Erlang describing how to build port programs still use erl_interface function calls or raw byte-coding methods as examples. This tutorial demonstrates the use of ei's encoding and decoding functions for marshaling data between an Erlang process and a C program. In order to focus this tutorial on ei rather than on details of OTP, we'll use only basic Erlang functionality in building the interface process communicating with the C program. The example described in this tutorial will show how to implement functions add(X, Y), multiply(X, Y) and divide(X, Y) that can be called from Erlang and executed in C. Erlang side First, we need to define the data marshaling contract between Erlang and C that will request from C to execute functions and receive the result back. The objective of the port program is to be able to implement the following API: Erlang -> C C -> Erlang =========== =========== {add, X, Y} -> {ok, Result::integer()} | {error, Reason::atom()} {multiply, X, Y} -> {ok, Result::integer()} | {error, Reason::atom()} {divide, A, B} -> {ok, Result::float()} | {error, Reason::atom()} X = integer() Y = integer() A = integer() | float() B = integer() | float() Where the add, multiply, and divide instructions perform the corresponding action on the C-side given two arguments. Let's start with writing an Erlang module responsible for marshaling data to and from the C port program. The module will use erlang:port_command/2 function for asynchronously sending data to the port. Note that the data is encoded to the external binary term format using erlang:term_to_binary/1. Erlang module listing -module(port). % API -export([start/0, start/1, stop/0, add/2, multiply/2, divide/2]). % Internal exports -export([init/1]). start() -> start("./cport"). start(ExtPrg) -> spawn_link(?MODULE, init, [ExtPrg]). stop() ->  ?MODULE ! stop. add(X, Y) -> call_port({add, X, Y}). multiply(X, Y) -> call_port({multiply, X, Y}). divide(X, Y) -> call_port({divide, X, Y}). call_port(Msg) ->  ?MODULE ! {call, self(), Msg}, receive Result -> Result end. init(ExtPrg) -> register(?MODULE, self()), process_flag(trap_exit, true), Port = open_port({spawn, ExtPrg}, [{packet, 2}, binary, exit_status]), loop(Port). loop(Port) -> receive {call, Caller, Msg} -> io:format("Calling port with ~p~n", [Msg]), erlang:port_command(Port, term_to_binary(Msg)), receive {Port, {data, Data}} -> Caller ! binary_to_term(Data); {Port, {exit_status, Status}} when Status > 128 -> io:format("Port terminated with signal: ~p~n", [Status-128]), exit({port_terminated, Status}); {Port, {exit_status, Status}} -> io:format("Port terminated with status: ~p~n", [Status]), exit({port_terminated, Status}); {'EXIT', Port, Reason} -> exit(Reason) end, loop(Port); stop -> erlang:port_close(Port), exit(normal) end. C side The port program that implements the API functions consists of two parts. Part I is the actual loop that decodes data from Erlang, calls the API functions, and encodes the result back to be sent to Erlang. This part uses ei interface library, and is the main focus of this turorial. Part II implements the data marshaling procedures to read and write data from standard input and to standard output. ei library implements a number of "ei_decode*()" functions. They can be used on the data received from Erlang that is encoded using erlang:term_to_binary/1 function call. The ei_decode_version() function is used to make sure that the incoming term is an external binary representation, and that the version magic number for the erlang binary term format is decoded. The rest of the ei_decode_* functions are used to decode tuple, integer, and double representation of data passed to the C port program. The result to be sent back to Erlang is encoded using a dynamic buffer of ei_x_buff type. We could've used a static buffer and handled memory management ourselves, but for the sake of this tutorial it's worth showing how the buffer can be managed automatically by using ei_x_* function calls. The output stored in external binary term representation is being initialized using ei_x_new_with_version() call, and ei_x_encode_tuple_header() is used to create a placeholder for the {ok, Result} or {error, Reason} tuple. C Program listing #include <ei.h> #include <unistd.h> #include <sys/io.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define BUF_SIZE 128 typedef char byte; int read_cmd(byte *buf, int *size); int write_cmd(ei_x_buff* x); int read_exact(byte *buf, int len); int write_exact(byte *buf, int len); /*----------------------------------------------------------------- * API functions *----------------------------------------------------------------*/ long add(long a, long b) { return a + b; } long multiply(long a, long b) { return a * b; } double divide(double a, double b) { return a / b; } /*----------------------------------------------------------------- * MAIN *----------------------------------------------------------------*/ int main() { byte* buf; int size = BUF_SIZE; char command[MAXATOMLEN]; int index, version, arity; long a, b, c; double x, y, z; ei_x_buff result; if ((buf = (byte *) malloc(size)) == NULL) return -1; while (read_cmd(buf, &size) > 0) { /* Reset the index, so that ei functions can decode terms from the * beginning of the buffer */ index = 0; /* Ensure that we are receiving the binary term by reading and * stripping the version byte */ if (ei_decode_version(buf, &index, &version)) return 1; /* Our marshalling spec is that we are expecting a tuple {Command, Arg1, Arg2} */ if (ei_decode_tuple_header(buf, &index, &arity)) return 2; if (arity != 3) return 3; if (ei_decode_atom(buf, &index, command)) return 4; /* Prepare the output buffer that will hold {ok, Result} or {error, Reason} */ if (ei_x_new_with_version(&result) || ei_x_encode_tuple_header(&result, 2)) return 5; if (!strcmp("add", command) || !strcmp("multiply", command)) { if (ei_decode_long(buf, &index, &a)) return 6; if (ei_decode_long(buf, &index, &b)) return 7; if (!strcmp("add", command)) c = add(a, b); else c = multiply(a, b); if (ei_x_encode_atom(&result, "ok") || ei_x_encode_long(&result, c)) return 8; } else if (!strcmp("divide", command)) { /* Allow incoming parameters to be integers or floats */ if (!ei_decode_long(buf, &index, &a)) x = a; else if (ei_decode_double(buf, &index, &x)) return 6; if (!ei_decode_long(buf, &index, &b)) y = b; else if (ei_decode_double(buf, &index, &y)) return 7; if (y == 0.0) { if (ei_x_encode_atom(&result, "error") || ei_x_encode_atom(&result, "division_by_zero")) return 8; } else { z = divide(x, y); if (ei_x_encode_atom(&result, "ok") || ei_x_encode_double(&result, z)) return 8; } } else { if (ei_x_encode_atom(&result, "error") || ei_x_encode_atom(&result, "unsupported_command")) return 99; } write_cmd(&result); ei_x_free(&result); } return 0; } /*----------------------------------------------------------------- * Data marshalling functions *----------------------------------------------------------------*/ int read_cmd(byte *buf, int *size) { int len; if (read_exact(buf, 2) != 2) return(-1); len = (buf[0] << 8) | buf[1]; if (len > *size) { buf = (byte *) realloc(buf, len); if (buf == NULL) return -1; *size = len; } return read_exact(buf, len); } int write_cmd(ei_x_buff *buff) { byte li; li = (buff->index >> 8) & 0xff; write_exact(&li, 1); li = buff->index & 0xff; write_exact(&li, 1); return write_exact(buff->buff, buff->index); } int read_exact(byte *buf, int len) { int i, got=0; do { if ((i = read(0, buf+got, len-got)) <= 0) return i; got += i; } while (got<len); return len; } int write_exact(byte *buf, int len) { int i, wrote = 0; do { if ((i = write(1, buf+wrote, len-wrote)) <= 0) return i; wrote += i; } while (wrote<len); return len; } Data Types Though in this example we didn't use ei_get_type() function, this function is quite useful when there's a need to determine the type of the next encoded term in the buffer. A question that gets frequently asked is which include file erl_interface.h or ei.h lists the macros that can be used to represent types returned by the ei_get_type() call? These macros are defined in the ei.h header: #define ERL_SMALL_INTEGER_EXT 'a' #define ERL_INTEGER_EXT 'b' #define ERL_FLOAT_EXT 'c' #define ERL_ATOM_EXT 'd' #define ERL_REFERENCE_EXT 'e' #define ERL_NEW_REFERENCE_EXT 'r' #define ERL_PORT_EXT 'f' #define ERL_PID_EXT 'g' #define ERL_SMALL_TUPLE_EXT 'h' #define ERL_LARGE_TUPLE_EXT 'i' #define ERL_NIL_EXT 'j' #define ERL_STRING_EXT 'k' #define ERL_LIST_EXT 'l' #define ERL_BINARY_EXT 'm' #define ERL_SMALL_BIG_EXT 'n' #define ERL_LARGE_BIG_EXT 'o' #define ERL_NEW_FUN_EXT 'p' #define ERL_FUN_EXT 'u' Makefile The following makefile can be used to build the sample port program and the corresponding Erlang module: Makefile listing $ cat Makefile ERL_LIB=/usr/local/lib/erlang/lib/erl_interface-3.5.5 CFLAGS=-Wall -I/usr/local/include -I$(ERL_LIB)/include LDFLAGS=-L. -L$(ERL_LIB)/lib all: cport port.beam cport: cport.o gcc $(LDFLAGS) $< -lerl_interface -lei -lpthread -o $@ %.o: %.c gcc -g $(CFLAGS) -o $@ -c $< %.beam: %.erl erlc $< clean: rm port.beam cport cport.o Running example Running make with the Makefile above will create two files: cport port.beam Now, let's start the emulator, and verify that everything works: Running the port program $ erl Erlang (BEAM) emulator version 5.5 [source] [async-threads:0] [hipe] [kernel-poll:false] Eshell V5.5 (abort with ^G) 1> port:start(). <0.35.0> 2> port:add(10,5). Calling port with {add,10,5} {ok,15} 3> port:multiply(3,6). Calling port with {multiply,3,6} {ok,18} 4> port:divide(10,5). Calling port with {divide,10,5} {ok,2.00000} 5> port:divide(10,0). Calling port with {divide,10,0} {error,division_by_zero} 6> port:stop(). stop 7> Conclusion As was illustrated in this tutorial ei provides a set of functions for convenient encoding and decoding of the erlang binary term format that can be used in other languages for interfacing with Erlang.
__label__pos
0.982161
Which would you rather have: a rich design or a fast user experience? Users want both, but sometimes the interplay between design and performance feels like a fixed sum game: one side's gain is the other side's loss. Design and performance are indeed connected, but it's more like the yin and yang. They aren't opposing forces, but instead complement each other. Users want an experience that is rich and fast. The trick for designers and developers is figuring out how to do that. The answer is to adopt an approach that considers both design and performance from the outset. With this approach, designs are conceived by teams of designers and developers working together. Developers benefit by participating in the product definition process. Designers benefit from understanding more about how designs are implemented. There's an emphasis on early prototyping and tracking performance from the get go. With new metrics that focus on what a user actually sees as the page loads, we can now bridge the technical and language gaps that have hindered the seamless creation of great user experiences. In this presentation, Steve Souders, former Chief Performance Yahoo! and Google Head Performance Engineer, explains how promoting a process that brings design and performance together at the beginning of a project helps deliver a web experience that is both fast and rich.
__label__pos
0.693531
Hacker News new | past | comments | ask | show | jobs | submit login Clever, as usual. But, this could have been done in far less code in a language that already supports term rewriting, such as Mathematica. Funny story--I am also a (recovering) Mathematica programmer! I'm not sure it's quite as good of a fit, for a few reasons. One is that Mathematica's syntax is, in a lot of ways, already pretty C-like. It uses mutable assignment `x = y`, function-arglist syntax `Fun[arg1, arg2]` instead of a Lisp-style `(f arg1 arg2)`, commas for list separators (in Clojure, they're whitespace), braces `{a, b, c}` are a sequential construct, rather than a map, and semicolons `first ; second ; third` denote sequential expressions (in Clojure, ; is an end-of-line comment). The second reason is that Mathematica, in my understanding, doesn't treat parentheses as first-class syntactic elements: they're used to control interpretation of the parse tree, but they transparently collapse, instead of being accessible as a reified type. (Are they? I know Mathematica is sort of an endless coal-mine of a language, and it's entirely possible I'm just not experienced enough to know about this!) If this constraint is true, I'm not sure how you would parse `func(arg1, arg2)` vs `func((arg1, arg2))`. Maybe it's inferrable from any symbol followed by a list, since `(arg1, arg2)` gives you a bounded context for the arglist, even if the parens disappear--and we can give up on having `(a,b)` for tuples or `()` as a unit syntax. It might also be inferrable from context, depending on what types of infix operators you allow, and how ; works as a separator. My license is long-since expired, so I can't test right now--perhaps you can give it a shot and show it off here! I wound up cutting this from the post, but... the full version of this rewriter provides a Java-style OO syntax with property accessors and chainable method calls. A tricky thing in Mathematica might be disambiguating `obj.property` from `obj.method()`, if the `()` isn't reified. For that matter, what do you do about `fun` vs `fun()`... One possible workaround might be to exploit (as I've done to hack around Clojure's insistence that "map keys be unique" and "maps have even numbers of elements") lesser-used Unicode codepoints, only this time, using alternatives for `(` and `)`, and to roll your own stack parser for arglist parsing... ideas, ideas. :) Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact Search:
__label__pos
0.767082
back to article High-powered luvvies given new radio home: 'But DON'T disturb the neighbours' Production companies will be allowed to operate 10-watt radio links in Channel 38, now that Ofcom has established it won't annoy the radio telescopes operated by nearby countries. Having shuffled the rest of the Programme Makers and Special Effects (PMSE) out of their existing home in Channel 69, in preparation for flogging … COMMENTS This topic is closed for new posts. Silver badge "one example being the Golf Open when commentators needed to be near the action, but get quality audio back to the club house for transmission - but when they are used there's generally no alternative." Not a good example - this is a voice commentary, so it doesn't exactly need to be super-duper highest possible quality, all they need is for the words to be intelligible. A mobile phone or walkie-talkie should work fine! And given that the news channels seem to think that a bad skype link is okay for interviewing people, then surely similar quality is fine for some sports commentary? 2 3 Silver badge I don't think the problem is the bandwidth quality: It's the transmitter power. 0 0 I agree it seems like not the greatest example. Exactly how much latency does going digital and would this significantly impact such a fast paced sport like golf? I have no horse in this race, just interested as it struck me as odd. Especially as you could add a slight delay to the pictures as well to bring them closer to sync (I assume we are talking a sub second lag). I could understand the bar flies in the clubhouse perhaps noticing a half second gap between commentary and video feed, but surely the video feed also experiences some delay in transmission \ conversion? 0 0 Anonymous Coward Golf balls You don't think the viewers (and those paying the BBC for syndication rights?) would get a bit upset if they saw the stick hitting the ball, and picture shows the ball going in the hole, whilst the sound of the stick hitting the ball then going in the hole and the crowd applause followed on half a second or more behind the picture ? 1 0 Plenty of other applications use digital transmission, with timecoding and a small buffer they can be synced. The article actually mentioned relaying commentary to the clubhouse for transmission but the cameras filming the action use digital transmission so it smells a bit funny that the audio cannot as the video will have significantly more information. Also calling the quality of the audio into question is a little odd. Even losslessly encoded digital would allow for more information and a greater sampling rate, in theory increasing the quality. It just sounds odd thats all :-) 0 0 Anonymous Coward I might be showing my ignorance here, but what if the production company wants to work on location in one of these countries that still use Channel 38 for their telescopes? Is it easy to flip to new more appropriate channels? 0 0 Silver badge Wireless gear that isn't complete crap usually has a setting to change it to a different frequency. That and production companies are required by law to use equipment that has been certified by the proper authorities of the nation where they want to use said equipment. 0 0 Silver badge The weakest link > High power users ... can't go digital because of the same quality and latency issues that prevent the entire PMSE industry adopting digital radio Yet all our domestic TV manages quite well with digital transmission to the viewer. So I can't see the point in having higher quality "upstream" than the user is capable of receiving. If the signal was digitised as soon as possible, there shouldn't be any further loss in quality all the way through the chain, from O/B to the viewer, provided that the signal wasn't reconverted to analog at any point. Has this premise about quality and latency ever been tested, or is it just the doom-mongers putting up roadblocks as an excuse for not wanting to make changes? 1 2 Silver badge Re: The weakest link You seem to have missed the point, it is not latency for "live" broadcast on TV - that is bollocks, it is latency for things like concerts and theatre where you can't tolerate 0.1s delay between actors & instruments, etc, and those involved are experiencing it all in human real time. All of the bandwidth/power gains you see with digital radio come at the expense of delay - you need to have a significant block of data (10s of milliseconds or more) before you can strip out 'insignificant' information for audio compression, and similar case to allow the addition of worthwhile forward error correction (ARQ is largely a lost cause when real-time matters, and most radio mics, etc, won't have a back channel). 3 0 Re: The weakest link Um. Broadcast digital TV is compressed with lossy compression (MPEG2/MPEG4) and the quality isn't really that great (it's compressed to the point that it is "just good enough"). You don't want any lossy compression on the production side because every bit of processing would result in recompressing and maybe even resampling with further loss and this degrades quality. Try ripping an MP3, burning it to CD, ripping it back again with slightly different parameters, and repeat the process a couple of times. The quality will drop drastically even though every stage of the process was a digital recording... 4 0 Silver badge @Paul > like concerts and theatre where you can't tolerate 0.1s delay between actors & instruments It's a long time since I dabbled in TV (university course, back in the analog days), but I do seem to recall being told that to make the audio sound "right", there's an artificial delay of some 100's of mSec introduced specifically so that actors lips move at the same time that the sound reaches the viewers ears. So long as the right amount of delay between sound and vision is introduced, and kept constant the absolute time delay between recording the "live" event and the time it makes it through to the TV is immaterial. I often notice that in our house a TV tuned to a terrestrial channel leads another TV tuned to the same channel on satellite (not surprisingly) by a second or two. 0 0 Silver badge Re: @Paul "specifically so that actors lips move at the same time that the sound reaches the viewers ears" I expect that delay is the opposite way - you delay the video to account for the audio's slower path. The real problem is for the actors & musicians who need to play in time with each other, and if you remember the joys of significant delay on a phone, it can be very disconcerting (pun?) to hear yourself with a modest delay. What Ofcom has finally been forced to recognise it seems is you can't magically replace a high power FM link and get the same near-zero delay and hi-fi sound in a GSM channel, and so live events need to have much more bandwidth (and protection for it) than a similar number of phone users. The issue behind the shift is simply money - they wanted to combine and flog the analogue TV spectrum for money. Ah yes, analogue TV, I remember when it was near real-time for the New Year bells and where you did not get blocky compression artefacts on anything fast moving. Just needed a decent SNR... 4 0 If there's any danger of interfering with radio astronomy Then astronomy has to take precedent. Science > performing arts 4 2 Meh The alternative view.. Radio Astronomy? How much advertising does THAT bring in? 1 1 Silver badge Happy Re: The alternative view.. Have a look tomorrow night when live radar pictures of approaching doom are broadcast from Jodrell Bank... 2 1 Go Re: The alternative view.. But better make it cash-in-advance, and spend it all on nifty funerary goods for a happy afterlife. Wiki sez that the Mayans favoured "mushroom figures" among other things so something like this but made of platinum: http://4.bp.blogspot.com/_lGw8sYiLP5U/SqVkG9eNqTI/AAAAAAAAAEw/4YF-C7h8_Dw/s1600-h/pilzSmall.jpg 0 1 This topic is closed for new posts. Forums Biting the hand that feeds IT © 1998–2017
__label__pos
0.686872
30 Excel Functions in 30 Days: 27 – SUBSTITUTE Icon30DayYesterday, in the 30XL30D challenge, we used the OFFSET function to return a reference, and saw that it is similar to the non-volatile INDEX function. NOTE: You can have all of the 30 Functions content in an easy-to-use single reference file -- the 30 Excel Functions in 30 Days eBook Kit ($10). For day 27 in the challenge, we'll examine the SUBSTITUTE function. Like the REPLACE function, it replaces old text with new text, in a text string, but can replace multiple instances of the same text. In some situations though, it's quicker and easier to use the Find/Replace command on the Excel Ribbon, with Match Case option turned on, for case sensitive replacement. So, let's take a look at the SUBSTITUTE information and examples, and if you have other tips or examples, please share them in the comments. Function 27: SUBSTITUTE The SUBSTITUTE function replaces old text with new text, in a text string. It will replace all instances of the old text, unless a specific occurrence is selected, and SUBSTITUTE is case sensitive. Substitute00 How Could You Use SUBSTITUTE? The SUBSTITUTE function replaces old text with new text, in a text string, so you could use it to: • Change region name in report title • Remove non-printing characters • Replace last space character SUBSTITUTE Syntax The SUBSTITUTE function has the following syntax: • SUBSTITUTE(text,old_text,new_text,instance_num) • text is the text string or cell reference, where text will be replaced. • old_text is the text that will be removed • new_text is the text that will be added • instance_number is the specific occurrence of old text that you want replaced SUBSTITUTE Traps • The SUBSTITUTE function can replace all instances of the old text, so use the instance_num argument if you want only a specific occurrence of old text replaced. • For replacements that are not case sensitive, you can use the REPLACE function. Example 1: Change region name in report title With the SUBSTITUTE function, you can create a report title that changes automatically, based on the region name that is selected. In this example, the report title is entered in cell C11, which is named RptTitle. The "yyy" in the title text will be replaced with the region name, selected in cell D13. =SUBSTITUTE(RptTitle,"yyy",D13) Substitute01 Example 2: Remove non-printing characters When you copy data from a website, there might be hidden, non-printing space characters in the text. If you try to remove space characters from the text in Excel, the TRIM function can't remove them. The characters aren't normal space characters (character 32); they are non-breaking space characters (character 160). Instead, you can use the SUBSTITUTE function to replace each of the non-printing spaces with a normal space character. Then, use TRIM to remove all the extra spaces. =TRIM(SUBSTITUTE(B3,CHAR(160)," ")) Substitute02 Example 3: Replace last space character Instead of replacing all instances of a text string, you can use the SUBSTITUTE function's instance_number argument to select a specific instance. In this list of recipe ingredients, we want to replace the last space character only. In cell C3, the LEN function calculates the number of characters in cell B3. The SUBSTITUTE function replaces all the space characters with empty strings, and the second LEN function finds the length of the revised string. The length is 2 characters shorter, so there are two spaces. =LEN(B3)-LEN(SUBSTITUTE(B3," ","")) Substitute03a In cell D3, the SUBSTITUTE function replaces only the 2nd space character with the new text –  " | " =SUBSTITUTE(B3," "," | ",C3) Instead of using two columns for this formula, you could combine them into one long formula. =SUBSTITUTE(B3," "," | ",LEN(B3)-LEN(SUBSTITUTE(B3," ",""))) Substitute03b Download the SUBSTITUTE Function File To see the formulas used in today's examples, you can download the SUBSTITUTE function sample workbook. The file is zipped, and is in Excel 2007 file format. Watch the SUBSTITUTE Video To see a demonstration of the examples in the SUBSTITUTE function sample workbook, you can watch this short Excel video tutorial. YouTube link: Change Text with Excel SUBSTITUTE Function _____________ 5 comments to 30 Excel Functions in 30 Days: 27 – SUBSTITUTE Leave a Reply          You can use these HTML tags <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
__label__pos
0.90628
... View Full Version : Javascript/API help - Driving Directions with Clusterer Troubadourbluue 06-20-2008, 06:18 PM Hello all! I'm trying to get my driving directions to show up in my info windows using google API... Now, I am aware of the current way to add them, and can make them work just fine - // arrays to hold variants of the info window html with get direction forms open var to_htmls = []; var from_htmls = []; // A function to create the marker and set up the event window function createMarker(point,name,html,icontype) { // === create a marker with the requested icon === var marker = new GMarker(point, gicons[icontype]); // The info window version with the "to here" form open to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' + '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' + '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' + '<INPUT value="Get Directions" TYPE="SUBMIT">' + '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + // "(" + name + ")" + '"/>'; // The info window version with the "to here" form open from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' + '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' + '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' + '<INPUT value="Get Directions" TYPE="SUBMIT">' + '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() + // "(" + name + ")" + '"/>'; // The inactive version of the direction info html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>'; GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); However, I am actually using a clusterer inside the javascript code, and this coding isn't working. My current code is as follows: </head> <body onunload="GUnload()"> <!-- you can use tables or divs for the overall layout --> <table border=1> <tr> <td> <div id="map" style="width: 800px; height: 600px"></div> <center><div id="message"><h3>Please wait while data loads</h3></div></center> </td> </td> </tr> </table> <input type="button" value="A" onclick='readMap("test.xml")'> <input type="button" value="B" onclick='readMap("example.xml")'> <input type="button" value="C" onclick='readMap("map11c.xml")'><br> <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> However, it seems JavaScript is either disabled or not supported by your browser. To view Google Maps, enable JavaScript by changing your browser options, and then try again. </noscript> <script type="text/javascript"> //<![CDATA[ if (GBrowserIsCompatible()) { var side_bar_html = ""; var gmarkers = []; var htmls = []; var i = 0; var Icon = new GIcon(); Icon.image = "icon_beer.gif"; Icon.shadow = "http://www.google.com/mapfiles/shadow50.png"; Icon.iconSize = new GSize(20, 34); Icon.shadowSize = new GSize(37, 34); Icon.iconAnchor = new GPoint(9, 34); Icon.infoWindowAnchor = new GPoint(9, 2); Icon.infoShadowAnchor = new GPoint(18, 25); var clusterIcon = new GIcon(); clusterIcon.image = 'icon_beer.gif'; clusterIcon.shadow = 'shadow_large.png'; clusterIcon.iconSize = new GSize( 30, 51 ); clusterIcon.shadowSize = new GSize( 56, 51 ); clusterIcon.iconAnchor = new GPoint( 13, 34 ); clusterIcon.infoWindowAnchor = new GPoint( 13, 3 ); clusterIcon.infoShadowAnchor = new GPoint( 27, 37 ); // A function to create the marker and set up the event window function createMarker(point,name,html) { var marker = new GMarker(point,Icon); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); // add a line to the side_bar html side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>'; i++; return marker; } // This function picks up the click and opens the corresponding info window function myclick(i) { gmarkers[i].openInfoWindowHtml(htmls[i]); } // create the map var map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(31.844024,-99.418373), 6); // create the clusterer var clusterer = new Clusterer(map); // set the clusterer parameters if you dont like the defaults clusterer.icon = clusterIcon; clusterer.maxVisibleMarkers = 200; clusterer.gridSize = 5; clusterer.minMarkersPerClusterer = 5; clusterer.maxLinesPerInfoBox = 4; // Read the data var request = GXmlHttp.create(); request.open("GET", "test.xml", true); request.onreadystatechange = function() { if (request.readyState == 4) { var xmlDoc = GXml.parse(request.responseText); // obtain the array of markers and loop through it var markers = xmlDoc.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("lat")); var lng = parseFloat(markers[i].getAttribute("lng")); var point = new GPoint(lng,lat); var town = markers[i].getAttribute("html"); var pop = markers[i].getAttribute("pop"); var marker = createMarker(point,town,town+" "); // create clusterer object clusterer.AddMarker(marker,town); } } } request.send(null); } else { alert("Sorry, the Google Maps API is not compatible with this browser"); } //]]> </script> </body> I have been messing with this thing for about 3 days now, and cannot get the driving directions to populate inside the info window. Any help would be greatly appreciated! Thanks for your time! Mike EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum
__label__pos
0.571831
A Deep Dive into Technology Operating Behind Online Casino Software Photo by Raka Miftah from Pexels Online casinos are more complex and interesting than we give them credit for being. It’s easy to get accustomed to playing the odd slots game or a round of poker without overthinking it. However, there is some awe-inspiring technology behind it all, keeping online gaming fair for all. How Do Online Slot Games Work? As you may assume, keeping online casino games running means keeping things genuinely random. For casinos to meet regulations from bodies such as the UK Gambling Commission, there always need to be winning opportunities. Therefore, most casinos will run on a random number generator or an RNG. This is a simple but effective component that ensures players get fair access to prizes. The winnings may be a small line win on a slots game here and there, but it is a win, nonetheless. So, let’s use the casino games at Boss Casino, for example. The popular slots games at Boss will run a random number sequence every time you spin the reels. This randomisation ensures you get chances to win a genuinely random prize, with each bet you make.  What About General Programming? Anyone who has played a few slots games before will know that every title is slightly different. There are some with slight variations, and some games are similar due to programming and templates used. On the whole, you can expect simple slots games to use C++. The same can also apply to casino table emulations such as online blackjack and roulette. Those familiar with indie games of the past decade or so may also find it surprising that Java, and JavaScript, are also popular. However, there has been a swift move away from older programming standards in line with how the web evolves. The shift to mobile play means that HTML5 is now the casino programming standard. What’s more, Flash left our screens completely as of January 2021. Therefore, older games using this classic standard fade away or get upgrades. You also have to consider that live streaming tech plays a big part in modern online gaming. Many casinos, and games developers, produce ‘live’ casino experiences. Such events are a streaming of real dealers and presenters, who spin roulette wheels and deal cards in real-time. At the same time, you are betting from the comfort of your home.  What’s to Expect in the Future? Right now, live casinos are looking very popular. However, there is growing interest in VR or virtual reality casinos. The technology behind this, as you may imagine, is going to be incredibly advanced. Right now, VR casinos aren’t exactly mainstream. However, modern casinos will likely continue to surprise us for time to come. There are scores of developers and studios out there, all working on their original titles. It takes a little more work than you think to bring a slot game or online casino table to life. Next time you play slots, think about the fascinating technology behind them! Was it worth reading? Let us know.
__label__pos
0.551587
Home / Help / Documentation / DJ-Catalog2 / Import configuration In DJ-Catalog2 ver. 3.5.6 we have added new option that allows administrators to better configure import procedure when it comes to importing Products. The new feature can be found in the back-end area under the page named "Import configuration":  import configuration Keep in mind that the options described in here refer to importing Products only. Neither Categories nor Producers are affected. There are two main benefits of using Import configuration feature: 1. You no longer have to adjust the column layout of each CSV file before importing it, so you can set up a list of dependencies between your own CSV format and DJ-Catalog2 product structure just once. 2. The import process becomes more flexible and powerful as you can for example merge three columns into one or look up the attribute in the database and replace it with returned value. In order to create a dependency you have to click "New" button and the "Import dependency" form will be displayed. import dependency A dependency consists of following attributes: • Name - it's a friendly name of your depency. • Published - only published depency will be used. • CSV column - the exact name of the column inside CSV file that should be paired with target attribute. • Target column - e.g. "name", "description", "images", "_custom_field_1". The exact name of target column inside #__djc2_items table. See the guidelines for more information and the article describing how to import data to custom attributes. • Database lookup* - enabled this option if you want to look up the source value (from CSV column) in the database and be replaced by retured value. See the example below. • Lookup table - name of the table, e.g. #__djc2_producers. • Lookup column - e.g. "name" • Lookup value - e.g. "id" • Comparison operator - the operator which should be used when comparing the source value against values inside "lookup column". • Optional "WHERE" - additional condition that should used in the SQL query, e.g. published=1 • Merging - the merging will occur when there are more than one dependencies which refer to the same target column. In such case you can replace the previous value with new one or concatenate it BEFORE or AFTER. The perfect example is merging values from "first name" and "last name" columns into one "name" column. • HTML wrap - you may surround the value with HTML tags such as <p>, <div>, <span> *) Database lookup usage example. Dependency displayed below will take the string value (assuming it's name of the producer) from "manufacturer" column, insert it into SQL query which looks for producer ID from #__djc2_producers table based on "name" column and finally replace the old value with returned ID. In other words, following SQL query will be performed: SELECT `id` FROM `#__djc2_producers` WHERE `name` LIKE "?" LIMIT 1 db lookup depedency Found this article interesting? Subscribe for more. Or share this article with your friends. Subscribe to the Telegram bot / Subscribe to the Messenger Bot  
__label__pos
0.521076
CPP (C plus plus) Tokens CPP (C plus plus) Tokens What is Tokens? A token is the smallest identifiable and individual unit in any program.  or another definition is that a token is the smallest element of a C++ program that is meaningful to the compiler. Main Types of Token in C++ There are five types of tokens in C++ language: 1. Keywords 2. Variables/Identifiers 3. Constants/Literals 4. Punctuators 5. Operators 1. Keywords Keywords is reserved words which have fixed meaning. The meaning and working of these keywords are already known to the compiler. These words should be written in lowercase letters. Example of the keyword used in C++ are int, float, char, double, long, void, for, while, do, if, else etc.  2. Variables/Identifiers Identifiers or variables are names given to different variables, structures, and functions. It is a name used to represent a variable constant, array name, function name, class, object name etc.  Variables are identifier whose value can be changed is known as a variable.  Example of a variable can be declared as shown below.       int price;       float tax; 3. Constants/Literals Constants are like a variable but its value never changes during execution. The constant values used in C++ are known as literals, there are four type of literals in C++ Programming.  1.          i) Integer constant:-          A value written without fraction part is called an integer constant.          Example: 425, -7322, 10 etc.           ii) Floating constant:-  A value written with fraction part is floating value. Value of this type can also exponent form. Example: 9.54, -3.343, 2.11E10 iii) A character constant:-  A single character written within single quotation marks is called character constant. Example: ‘k’, ‘3’, ‘@’ etc. 1. iv) String constant:- It is an array of characters enclosed in double quotation marks called string. Example: “welcome”, “12-Sep-16” 4. Punctuators mostly used for formatting statements and expressions in C++ language. Examples are   { }   [ ]    , *:  = etc. 5. Operators C++ operator is a symbol that is used to perform mathematical or logical manipulations like Arithmetical operators, Relational operators etc.  Prof.Fazal Rehman Shamil (Available for Professional Discussions) 1. Message on Facebook page for discussions, 2. Video lectures on Youtube 3. Email is only for Advertisement/business enquiries.
__label__pos
0.99971
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free. I`m trying to send HTTP response to browser char *reply = "HTTP/1.1 200 OK\n" "Date: Thu, 19 Feb 2009 12:27:04 GMT\n" "Server: Apache/2.2.3\n" "Last-Modified: Wed, 18 Jun 2003 16:05:58 GMT\n" "ETag: \"56d-9989200-1132c580\"\n" "Content-Type: text/html\n" "Content-Length: 15\n" "Accept-Ranges: bytes\n" "Connection: close\n" "\n" "sdfkjsdnbfkjbsf"; int sd = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in addr; bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(8081); addr.sin_addr.s_addr = INADDR_ANY; if(bind(sd,&addr,sizeof(addr))!=0) { printf("bind error\n"); } if (listen(sd, 16)!=0) { printf("listen error\n"); } for(;;) { int size = sizeof(addr); int client = accept(sd, &addr, &size); if (client > 0) { printf("client connected\n"); send(client, reply, sizeof(reply), 0); } } but my browser cant understand this, waits for a long time and then print smth strange. I guess my response is wrong, but I dont know how to fix. Any ideas? share|improve this question 1 Answer 1 up vote 5 down vote accepted sizeof(reply) evaluates to the size of a char *, aka size of a pointer. Use strlen. send(client, reply, strlen(reply), 0); share|improve this answer      Damn! Stupid mistake. Thanks! –  spe Mar 30 '11 at 14:01 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.795004
Introduction to SharePoint 2019 (55298) Quiz Questions and Answers A college plans to enable personal sites for all users. All personal sites will be created in a dedicated web application. All staff, faculty members, and students have access to the same SharePoint environment. What do you need to ensure college staff should do? Answer : • Manage user permissions for the User Profile service application. When you create custom user profile properties which of the following data type you can include? Answer : • A) Integers B) URLs C) HTML Content All of the above When would you need to configure trusted host locations? Answer : • When you have multiple farms, each with a User Profile Service Application, and want to ensure that users have only one My Site. Which of the following is the individual value or entry that you want to provide to users so that they can use it as metadata? Answer : • Term Which of the following service should be used to share term sets or content types across different farms? Answer : • Managed metadata service Which SharePoint 2016 service application is responsible for resolving the identity of the user when SharePoint 2016 receives an OAuth-based server-to-server request? Answer : • The User Profile Service Application which cmdlet can be used to create Managed Metadata Service? Answer : • New-SPMetadataServiceApplication Why would you want to use SQL Alias? Answer : • Both A&B What are the advantages of having a separate farm for content publishing? Answer : • A) You can configure the servers and services in the publishing farm for browsing performance rather than for editing and collaboration performance. B) You can place the servers in the publishing farm in a security-enhanced perimeter network for Internet-based access. C) Publishing content in a separate farm increases security when anonymous access is granted. All of the above Which one of the following should not include in Functional Planning? Answer : • Security
__label__pos
1
vuZs Virtual University: Study Resource Bank You are here: Home MCQs MTH302: Business Mathematics &amp; Statistics MCQs MTH302 online Quiz 6 (23 to 45) Virtual University MCQs BANK - MCQs Collection from Online Quizzes MTH302 online Quiz 6 (23 to 45) Chapter No 6 Multiple Choice Quiz 1 A random variable is a function or rule that assigns a numerical value to each outcome in the sample space of a stochastic experiment. A)        True B)        False 2) The birth weight of a newborn baby is an example of a discrete random variable. A)        True B)        False 3To describe the possible outcomes and their probabilities when you roll one fair die, we would use a discrete binomial distribution. A)        True B)        False 4For the Poisson distribution to apply, the events must occur randomly and independently over a continuum of time or space. A)        True B)        False 5When π = 0.70 the binomial distribution is positively skewed. A)        True B)        False 6A discrete probability distribution A)        assigns a probability to each value of the random variable. B)        can assume any value between -1 and +1. C)        is appropriate when the probability of success is an integer. 7Which statement is incorrect? A)        The Poisson distribution is always skewed right. B)        The binomial distribution may be skewed left or right. C)        The uniform distribution is never skewed. D)        The Bernoulli distribution has two equally likely outcomes. 8Historically, 2% of the stray dogs in the city of Southfield are unlicensed. On a randomly-chosen day, the Southfield city animal control officer picks up 7 stray dogs. What is the probability that at least one will be unlicensed? A)        .8681 B)        .1319 C)        .3670 D)        .1240 9In a randomly-chosen week, which probability model would you use to describe the number of accidents at the intersection of two streets? A)        Uniform. B)        Binomial. C)        Poisson. D)        Geometric. 10Which probability model would you use to describe the number of damaged printers in a random sample of 12 printers taken from a shipment of 70 printers that contains 6 damaged printers? A)        Poisson. B)        Hypergeometric. C)        Binomial. D)        Geometric. 11Consider the following probability distribution of the random variable X: X  P (X) 100 .10 150 .20 200 .30 250 .30 300 .10  1.00 The expected value of X is: A)        175 B)        150 C)        200 D)        205 12A carnival has a game of chance: a fair coin is tossed. If it lands heads you win $1.00 and if it lands tails you lose $0.50. How much should a ticket to play this game cost if the carnival wants to break even? A)        $.25 B)        $.50 C)        $.75 D)        $1.00 13A random variable X is distributed binomially with n = 8 and π = 0.70. The standard deviation of the variable X is approximately A)        0.458 B)        2.828 C)        1.680 D)        1.296 14In Quebec, 90 percent of the population subscribes to the Roman Catholic religion. In a random sample of 8 Quebecois find the probability that the sample contains at least five Roman Catholics. A)        .0050 B)        .0331 C)        .9950 D)        .9619 15On average, a major earthquake (Richter scale 6.0 or above) occurs 3 times a decade in a certain California county. Find the probability that at least one major earthquake will occur within the next decade. A)        .9810 B)        .0498 C)        .1994 D)        .9502 16If the probability of success is .25, what is the probability of obtaining the first success within the first 3 trials? A)        .4218 B)        .5781 C)        .1406 Add comment Security code Refresh You are here: Home MCQs MTH302: Business Mathematics & Statistics MCQs MTH302 online Quiz 6 (23 to 45)
__label__pos
0.694624
home | career | drupal | java | mac | mysql | perl | scala | uml | unix   Java example source code file (LaguerreSolver.java) This example Java source code file (LaguerreSolver.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM. Learn more about this Java project at its project page. Java - Java tags/keywords abstractpolynomialsolver, complex, complexsolver, default_absolute_accuracy, deprecated, laguerresolver, nobracketingexception, nodataexception, nullargumentexception, numberistoolargeexception, polynomialfunction, toomanyevaluationsexception The LaguerreSolver.java Java example source code /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.commons.math3.analysis.solvers; import org.apache.commons.math3.analysis.polynomials.PolynomialFunction; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.complex.ComplexUtils; import org.apache.commons.math3.exception.NoBracketingException; import org.apache.commons.math3.exception.NoDataException; import org.apache.commons.math3.exception.NullArgumentException; import org.apache.commons.math3.exception.NumberIsTooLargeException; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.exception.util.LocalizedFormats; import org.apache.commons.math3.util.FastMath; /** * Implements the <a href="http://mathworld.wolfram.com/LaguerresMethod.html"> * Laguerre's Method</a> for root finding of real coefficient polynomials. * For reference, see * <blockquote> * <b>A First Course in Numerical Analysis, * ISBN 048641454X, chapter 8. * </blockquote> * Laguerre's method is global in the sense that it can start with any initial * approximation and be able to solve all roots from that point. * The algorithm requires a bracketing condition. * * @since 1.2 */ public class LaguerreSolver extends AbstractPolynomialSolver { /** Default absolute accuracy. */ private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; /** Complex solver. */ private final ComplexSolver complexSolver = new ComplexSolver(); /** * Construct a solver with default accuracy (1e-6). */ public LaguerreSolver() { this(DEFAULT_ABSOLUTE_ACCURACY); } /** * Construct a solver. * * @param absoluteAccuracy Absolute accuracy. */ public LaguerreSolver(double absoluteAccuracy) { super(absoluteAccuracy); } /** * Construct a solver. * * @param relativeAccuracy Relative accuracy. * @param absoluteAccuracy Absolute accuracy. */ public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy) { super(relativeAccuracy, absoluteAccuracy); } /** * Construct a solver. * * @param relativeAccuracy Relative accuracy. * @param absoluteAccuracy Absolute accuracy. * @param functionValueAccuracy Function value accuracy. */ public LaguerreSolver(double relativeAccuracy, double absoluteAccuracy, double functionValueAccuracy) { super(relativeAccuracy, absoluteAccuracy, functionValueAccuracy); } /** * {@inheritDoc} */ @Override public double doSolve() throws TooManyEvaluationsException, NumberIsTooLargeException, NoBracketingException { final double min = getMin(); final double max = getMax(); final double initial = getStartValue(); final double functionValueAccuracy = getFunctionValueAccuracy(); verifySequence(min, initial, max); // Return the initial guess if it is good enough. final double yInitial = computeObjectiveValue(initial); if (FastMath.abs(yInitial) <= functionValueAccuracy) { return initial; } // Return the first endpoint if it is good enough. final double yMin = computeObjectiveValue(min); if (FastMath.abs(yMin) <= functionValueAccuracy) { return min; } // Reduce interval if min and initial bracket the root. if (yInitial * yMin < 0) { return laguerre(min, initial, yMin, yInitial); } // Return the second endpoint if it is good enough. final double yMax = computeObjectiveValue(max); if (FastMath.abs(yMax) <= functionValueAccuracy) { return max; } // Reduce interval if initial and max bracket the root. if (yInitial * yMax < 0) { return laguerre(initial, max, yInitial, yMax); } throw new NoBracketingException(min, max, yMin, yMax); } /** * Find a real root in the given interval. * * Despite the bracketing condition, the root returned by * {@link LaguerreSolver.ComplexSolver#solve(Complex[],Complex)} may * not be a real zero inside {@code [min, max]}. * For example, <code> p(x) = x3 + 1, * with {@code min = -2}, {@code max = 2}, {@code initial = 0}. * When it occurs, this code calls * {@link LaguerreSolver.ComplexSolver#solveAll(Complex[],Complex)} * in order to obtain all roots and picks up one real root. * * @param lo Lower bound of the search interval. * @param hi Higher bound of the search interval. * @param fLo Function value at the lower bound of the search interval. * @param fHi Function value at the higher bound of the search interval. * @return the point at which the function value is zero. * @deprecated This method should not be part of the public API: It will * be made private in version 4.0. */ @Deprecated public double laguerre(double lo, double hi, double fLo, double fHi) { final Complex c[] = ComplexUtils.convertToComplex(getCoefficients()); final Complex initial = new Complex(0.5 * (lo + hi), 0); final Complex z = complexSolver.solve(c, initial); if (complexSolver.isRoot(lo, hi, z)) { return z.getReal(); } else { double r = Double.NaN; // Solve all roots and select the one we are seeking. Complex[] root = complexSolver.solveAll(c, initial); for (int i = 0; i < root.length; i++) { if (complexSolver.isRoot(lo, hi, root[i])) { r = root[i].getReal(); break; } } return r; } } /** * Find all complex roots for the polynomial with the given * coefficients, starting from the given initial value. * <p> * Note: This method is not part of the API of {@link BaseUnivariateSolver}.</p> * * @param coefficients Polynomial coefficients. * @param initial Start value. * @return the full set of complex roots of the polynomial * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximum number of evaluations is exceeded when solving for one of the roots * @throws NullArgumentException if the {@code coefficients} is * {@code null}. * @throws NoDataException if the {@code coefficients} array is empty. * @since 3.1 */ public Complex[] solveAllComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException { return solveAllComplex(coefficients, initial, Integer.MAX_VALUE); } /** * Find all complex roots for the polynomial with the given * coefficients, starting from the given initial value. * <p> * Note: This method is not part of the API of {@link BaseUnivariateSolver}.</p> * * @param coefficients polynomial coefficients * @param initial start value * @param maxEval maximum number of evaluations * @return the full set of complex roots of the polynomial * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximum number of evaluations is exceeded when solving for one of the roots * @throws NullArgumentException if the {@code coefficients} is * {@code null} * @throws NoDataException if the {@code coefficients} array is empty * @since 3.5 */ public Complex[] solveAllComplex(double[] coefficients, double initial, int maxEval) throws NullArgumentException, NoDataException, TooManyEvaluationsException { setup(maxEval, new PolynomialFunction(coefficients), Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, initial); return complexSolver.solveAll(ComplexUtils.convertToComplex(coefficients), new Complex(initial, 0d)); } /** * Find a complex root for the polynomial with the given coefficients, * starting from the given initial value. * <p> * Note: This method is not part of the API of {@link BaseUnivariateSolver}.</p> * * @param coefficients Polynomial coefficients. * @param initial Start value. * @return a complex root of the polynomial * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximum number of evaluations is exceeded. * @throws NullArgumentException if the {@code coefficients} is * {@code null}. * @throws NoDataException if the {@code coefficients} array is empty. * @since 3.1 */ public Complex solveComplex(double[] coefficients, double initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException { return solveComplex(coefficients, initial, Integer.MAX_VALUE); } /** * Find a complex root for the polynomial with the given coefficients, * starting from the given initial value. * <p> * Note: This method is not part of the API of {@link BaseUnivariateSolver}.</p> * * @param coefficients polynomial coefficients * @param initial start value * @param maxEval maximum number of evaluations * @return a complex root of the polynomial * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximum number of evaluations is exceeded * @throws NullArgumentException if the {@code coefficients} is * {@code null} * @throws NoDataException if the {@code coefficients} array is empty * @since 3.1 */ public Complex solveComplex(double[] coefficients, double initial, int maxEval) throws NullArgumentException, NoDataException, TooManyEvaluationsException { setup(maxEval, new PolynomialFunction(coefficients), Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, initial); return complexSolver.solve(ComplexUtils.convertToComplex(coefficients), new Complex(initial, 0d)); } /** * Class for searching all (complex) roots. */ private class ComplexSolver { /** * Check whether the given complex root is actually a real zero * in the given interval, within the solver tolerance level. * * @param min Lower bound for the interval. * @param max Upper bound for the interval. * @param z Complex root. * @return {@code true} if z is a real zero. */ public boolean isRoot(double min, double max, Complex z) { if (isSequence(min, z.getReal(), max)) { double tolerance = FastMath.max(getRelativeAccuracy() * z.abs(), getAbsoluteAccuracy()); return (FastMath.abs(z.getImaginary()) <= tolerance) || (z.abs() <= getFunctionValueAccuracy()); } return false; } /** * Find all complex roots for the polynomial with the given * coefficients, starting from the given initial value. * * @param coefficients Polynomial coefficients. * @param initial Start value. * @return the point at which the function value is zero. * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximum number of evaluations is exceeded. * @throws NullArgumentException if the {@code coefficients} is * {@code null}. * @throws NoDataException if the {@code coefficients} array is empty. */ public Complex[] solveAll(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException { if (coefficients == null) { throw new NullArgumentException(); } final int n = coefficients.length - 1; if (n == 0) { throw new NoDataException(LocalizedFormats.POLYNOMIAL); } // Coefficients for deflated polynomial. final Complex c[] = new Complex[n + 1]; for (int i = 0; i <= n; i++) { c[i] = coefficients[i]; } // Solve individual roots successively. final Complex root[] = new Complex[n]; for (int i = 0; i < n; i++) { final Complex subarray[] = new Complex[n - i + 1]; System.arraycopy(c, 0, subarray, 0, subarray.length); root[i] = solve(subarray, initial); // Polynomial deflation using synthetic division. Complex newc = c[n - i]; Complex oldc = null; for (int j = n - i - 1; j >= 0; j--) { oldc = c[j]; c[j] = newc; newc = oldc.add(newc.multiply(root[i])); } } return root; } /** * Find a complex root for the polynomial with the given coefficients, * starting from the given initial value. * * @param coefficients Polynomial coefficients. * @param initial Start value. * @return the point at which the function value is zero. * @throws org.apache.commons.math3.exception.TooManyEvaluationsException * if the maximum number of evaluations is exceeded. * @throws NullArgumentException if the {@code coefficients} is * {@code null}. * @throws NoDataException if the {@code coefficients} array is empty. */ public Complex solve(Complex coefficients[], Complex initial) throws NullArgumentException, NoDataException, TooManyEvaluationsException { if (coefficients == null) { throw new NullArgumentException(); } final int n = coefficients.length - 1; if (n == 0) { throw new NoDataException(LocalizedFormats.POLYNOMIAL); } final double absoluteAccuracy = getAbsoluteAccuracy(); final double relativeAccuracy = getRelativeAccuracy(); final double functionValueAccuracy = getFunctionValueAccuracy(); final Complex nC = new Complex(n, 0); final Complex n1C = new Complex(n - 1, 0); Complex z = initial; Complex oldz = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); while (true) { // Compute pv (polynomial value), dv (derivative value), and // d2v (second derivative value) simultaneously. Complex pv = coefficients[n]; Complex dv = Complex.ZERO; Complex d2v = Complex.ZERO; for (int j = n-1; j >= 0; j--) { d2v = dv.add(z.multiply(d2v)); dv = pv.add(z.multiply(dv)); pv = coefficients[j].add(z.multiply(pv)); } d2v = d2v.multiply(new Complex(2.0, 0.0)); // Check for convergence. final double tolerance = FastMath.max(relativeAccuracy * z.abs(), absoluteAccuracy); if ((z.subtract(oldz)).abs() <= tolerance) { return z; } if (pv.abs() <= functionValueAccuracy) { return z; } // Now pv != 0, calculate the new approximation. final Complex G = dv.divide(pv); final Complex G2 = G.multiply(G); final Complex H = G2.subtract(d2v.divide(pv)); final Complex delta = n1C.multiply((nC.multiply(H)).subtract(G2)); // Choose a denominator larger in magnitude. final Complex deltaSqrt = delta.sqrt(); final Complex dplus = G.add(deltaSqrt); final Complex dminus = G.subtract(deltaSqrt); final Complex denominator = dplus.abs() > dminus.abs() ? dplus : dminus; // Perturb z if denominator is zero, for instance, // p(x) = x^3 + 1, z = 0. if (denominator.equals(new Complex(0.0, 0.0))) { z = z.add(new Complex(absoluteAccuracy, absoluteAccuracy)); oldz = new Complex(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY); } else { oldz = z; z = z.subtract(nC.divide(denominator)); } incrementEvaluationCount(); } } } } Other Java examples (source code examples) Here is a short list of links related to this Java LaguerreSolver.java source code file: my book on functional programming   new blog posts   Copyright 1998-2021 Alvin Alexander, alvinalexander.com All Rights Reserved. A percentage of advertising revenue from pages under the /java/jwarehouse URI on this website is paid back to open source projects.  
__label__pos
0.999273
Uploaded image for project: 'Core Server' 1. Core Server 2. SERVER-4649 mongod primary locks up and never kills cursors stalling connections for ever XMLWordPrintable Details • Type: Bug • Status: Closed • Priority: Critical - P2 • Resolution: Incomplete • Affects Version/s: 2.0.1 • Fix Version/s: None • Component/s: None • Labels: • Environment: Debian Squeeze with official 10gen deb packages. Two servers running on a replicaset. Each server is also running numactl --interleave=all wrapper. Mixed clients but mainly used by the PHP driver. • Operating System: ALL Description At what seems to be random times, the mongod primary never seems to finish some queries. Some cursors had been running for 6+ hours. It has only happened on the primary. The log always has these entries when this occurs: [conn123812] warning: virtual size (129449MB) - mapped size (123342MB) is large. could indicate a memory leak [initandlisten] connection accepted from 172.16.49.98:40540 #123818 [conn123816] end connection 172.16.49.98:40539 [conn123817] Assertion failure cc->_pinValue < 100 db/clientcursor.h 309 [conn123817] killcursors exception: assertion db/clientcursor.h:309 1ms And as we can see in the log, the queries that work seem to take forever: [conn123170] query x.scores nscanned:1015 scanAndOrder:1 nreturned:306 reslen:12260 302422ms The server resources doesn't seem to be exhausted and restarting the server gets everything back to normal again. Attachments 1. currentop.log 998 kB 2. mms.gif mms.gif 65 kB 3. mms2.gif mms2.gif 131 kB 4. oplog.log 2.44 MB 5. oplog - start to crash.log 1.89 MB 6. pinvalue.txt 30 kB Activity People Assignee: kristina Kristina Chodorow Reporter: balboah Johnny Boy Participants: Votes: 0 Vote for this issue Watchers: 7 Start watching this issue Dates Created: Updated: Resolved:
__label__pos
0.744122
Mastering Zoom on Your Laptop: A Simplified Guide In an era where remote ways of working, learning, and communicating have become the new normal, it is absolutely essential to be proficient in using online tools and platforms. Among these, Zoom has established itself as one of the prime go-to applications for video conferencing and online meetings. Whether you’re using Zoom for work, education, or catching up with friends and family, understanding its interface and knowing how to set up meetings will empower you with seamless communication. Furthermore, getting to grips with troubleshooting common problems will ensure your conversations aren’t interrupted, and discovering advanced features will enhance your Zoom experience. Understanding Zoom Interface Understanding the Zoom Interface Zoom is a popular video conferencing platform used by businesses, educational institutions, and casual users. Its interface is quite straightforward with critical control buttons positioned at visible spots. To get started, download Zoom Client for Meetings from official website, install it, then follow the prompts to sign in or create an account. The main Zoom interface, or the Home Screen, is where you can start a new meeting, join a meeting, schedule a meeting, or share your screen. Locating Audio and Video Settings Once you join or start a meeting, you will be in Zoom’s interface for meetings. The controls are mostly found on a toolbar at the bottom of the screen. Here, you will find buttons for both your audio (microphone) and video (webcam). With the mute and stop video options, you can control your audio and video settings during a meeting. By clicking on the upward arrow next to each of these buttons, a drop-down bar opens allowing you to alter your microphone, speaker, and video settings. Sharing Your Screen Next to the audio and video control buttons, you will find the “Share Screen” button. This tool allows you to share your screen with the other participants in the meeting. Clicking it brings up an array of options, allowing you to choose which part or window of your screen you want to share. Understanding Chat and Participants Control To the right of the “Share Screen” button, you will find buttons for “Chat” and “Participants.” The “Chat” button opens a sidebar where you can type in messages to the other participants. The “Participants” button opens a sidebar where you can see who else is in the meeting. You can also manage participants here if you are the host. Navigating More Options At the far right of the toolbar, you’ll see a button with three dots labeled “More.” Clicking on this gives you more options like “Record,” “Live Transcript,” or “Breakout Rooms.” Navigating Settings There’s also a “Settings” option available on the home screen near your profile picture. Clicking it opens a new window with many options that control how Zoom behaves. Here, you can set preferences for features like Audio, Video, Share Screen, and more. Remember, familiarity with the Zoom interface increases with use. So don’t be afraid of clicking around and exploring different features. An image depicting the Zoom interface with various control buttons and options. Setting up Zoom Meetings Downloading and Installing Zoom To get started, download and install the Zoom application on your laptop. Visit the official website of Zoom (www.zoom.us) and click ‘Download’ under the ‘Resources’ tab at the top right corner of the homepage. Choose ‘Zoom Client for Meetings’ from the dropdown menu and run the .exe file to install the software. Follow the prompts to complete the installation. Setting up a Zoom Account After installation, you need to create a Zoom account or sign in if you already have one. You can sign up with an email, SSO (Single Sign-On), Google or Facebook. Once logged in, the platform will direct you to your Zoom profile. Scheduling a Meeting To schedule a meeting, click the ‘Schedule’ icon on your Zoom home screen. A window will open where you can input details such as meeting title, date and time, duration and timezone. You will also see options to require a meeting passcode, enable a waiting room, or automatically record the meeting. Inviting Participants Once you’ve scheduled a meeting, you can invite participants by clicking on the ‘Participants’ button at the bottom of the meeting window, then select ‘Invite’. You can invite people via email, or copy the meeting invitation and send it through other means like a text or instant messaging app. Starting a Meeting Starting a meeting is as simple as clicking the ‘Start’ button next to the scheduled meeting in the ‘Meetings’ tab or clicking the ‘New Meeting’ button to start an impromptu meeting on the Zoom home screen. Muting/Un-muting and Video On/Off During a meeting, controls are available at the bottom of the window. The microphone icon is used to mute or un-mute your audio. Click the icon once to mute and again to un-mute. Similarly, the camera icon controls your video. Click it to turn your video off and again to turn it back on. Use of Chat Feature The chat feature in Zoom can be accessed by clicking the ‘Chat’ icon during a meeting. A window will open on the right side where you can type your message and press enter to send. You can choose to send a message to everyone in the meeting or to a specific participant. Remember, learning a new software can take time Remember, learning a new software can take time, so don’t be discouraged if you don’t get everything right immediately. Practice frequently to get familiar with the Zoom interface and its features. Illustration of using Zoom on a laptop for a virtual meeting Troubleshooting Common Problems Troubleshooting Connectivity Issues on Zoom One of the most common issues faced by Zoom users is related to connectivity. If you experience a slow or unstable internet connection, you may be unable to join meetings or experience interruptions during a meeting. Here’s how you deal with that: 1. Try changing your location to improve the quality of the WiFi signal. 2. If you’re using wireless internet, try connecting directly to your modem or router via an Ethernet cable. 3. Close any unnecessary applications that might be using your internet bandwidth. 4. If you are in a meeting and experiencing poor connectivity, turning off your video can improve the situation. 5. Avoid VPNs, as they can affect your connection speed considerably. If you are still having issues, you may need to contact your internet service provider for assistance. Troubleshooting Audio Problems on Zoom Another common issue on Zoom is trouble with the audio, such as not being able to hear others or being unable to be heard. Here is some advice on how to troubleshoot audio issues: 1. Make sure your computer’s audio is not muted and that the volume level is adequate. 2. Check if the correct speaker and microphone is selected in the Zoom settings. If you have multiple audio devices, the wrong one might be selected. 3. Test your speaker and microphone from the Zoom settings to check if they are working properly. 4. If you are using a headset or external microphone, make sure they are properly plugged in and working. If you complete these steps and still encounter audio problems, restart your computer and try rejoining the Zoom meeting. Troubleshooting Video Problems on Zoom Video problems, like a black screen or poor video quality, are also common on Zoom. Follow these steps to resolve video issues: 1. Ensure that your camera is turned on and that Zoom has permission to access it. 2. From Zoom settings, verify that the correct camera is selected and that the camera is not being used by another application. 3. Check if your camera lens is clean. Smudges or dust could affect the quality of the video. 4. If the video quality is poor, try improving the lighting conditions in your room or adjust your device’s camera settings if available. If you have trouble after following these suggestions, consider updating your device’s drivers or contacting the manufacturer for help. And remember: keep your Zoom application up to date to minimize issues. A person troubleshooting connectivity issues on Zoom Exploring Advanced Features Activating Zoom’s Advanced Features To activate Zoom’s advanced features on your laptop, you first need to download Zoom from “zoom.us/download” and install it. After successful installation, sign into your Zoom account, or create a new one if you don’t already have one. Creating and Managing Breakout Rooms The breakout rooms feature allows you to split your Zoom meeting into separated sessions. This could be helpful for group brainstorming and breakout discussions or workshops. To use this feature, follow these steps: 1. Launch Zoom and start a meeting. 2. Scroll down on your Zoom Screen and click on the ‘Breakout Rooms’ option. 3. Specify the total number of rooms you want to create and how you want to assign participants to these rooms, either automatically or manually. 4. After setting up your rooms, you can start them immediately, or close all rooms when the discussion time ends. Changing Zoom Backgrounds Changing the background during a Zoom meeting can help to maintain privacy and create a more professional or fun meeting environment. Here’s how: 1. Once you’ve started a meeting, go to the menu at the bottom of your screen. 2. Click ‘Choose Virtual Background.’ 3. You’ll then see a collection of default background options, or you can upload your own by clicking on the ‘+’ sign. Recording Zoom Meetings Recording your Zoom meetings can be a great tool for referencing and for people who missed the meetings. To do so, follow the steps below: 1. Start a Zoom meeting. 2. At the bottom of the screen, click ‘Record.’ 3. A dropdown menu will appear. Choose either ‘Record on this Computer’ or ‘Record to the Cloud.’ 4. After the meeting, just press ‘Stop Recording.’ If saved to your computer, the video file will save to a designated folder. Exploring other Add-Ons After becoming familiar with these Zoom features, explore other add-ons by visiting the “zoom.us/feature” web page. It displays all the advanced features like Waiting Room, Co-hosting, Polling, Live Transcription, Webinar controls etc. You can further click on each feature to read a detailed explanation and instruction on how to enable it. A laptop displaying Zoom advanced features Photo by cwmonty on Unsplash In a nutshell, understanding how to operate Zoom effectively is a skill that is indispensible in today’s online world. Aiding you in this journey, this guide has delved into the basics of the Zoom Interface, the process of setting up Zoom Meetings, troubleshooting common issues, and exploring advanced features. Armed with this knowledge, you now have the tools to utilize Zoom to its full potential, accommodating smooth and productive online meetings. Remember, the mastery of digital platforms like Zoom extends far beyond professional settings, infiltrating educational, social, and personal realms too. So dive in and explore the world of possibilities that Zoom has to offer.
__label__pos
0.624772
Help Recurring task - How to reset a column each week Topic Labels: Formulas 1800 1 cancel Showing results for  Search instead for  Did you mean:  Noemie_Lamberti 4 - Data Explorer 4 - Data Explorer Hello, Quick question! I have a table with recurring tasks. Every week I have to redo these same tasks. I know the progress of my task thanks to “Multiple Select” (Ex: In progress, to be done…) but I would like this column to be reset at the beginning of each week. Is it possible to create a formula to set the status of these tasks to “To do” every Monday? Thanks for your help ! 1 Reply 1 Formulas cannot modify the contents of other fields. They can only read those other fields to pull data into the formula for processing. That said, what you want isn’t completely out of reach, but it’ll take a bit more setup to pull it off. One option is to use a service like Zapier or Integromat to modify those recurring tasks on a weekly basis. Another is to use the scripting action beta, which could be used to trigger a script to refresh those every week. I’ve got such a setup that refreshes certain things in my planning base every day, and it works great. In my case, the update is done with a script, but you might be able to get it to work with the simpler record update option depending on how you set it up. If you’d like any help with this, drop me a message.
__label__pos
0.606013
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleInstances #-} module Text.Trifecta.Hunk ( Hunk(..) , hunk ) where import Data.ByteString import qualified Data.ByteString.UTF8 as UTF8 import Data.FingerTree as FingerTree import Data.Function (on) import Data.Hashable import Data.Interned import Data.String import Text.Trifecta.Delta data Hunk = Hunk {-# UNPACK #-} !Id !Delta {-# UNPACK #-} !ByteString deriving Show hunk :: ByteString -> Hunk hunk = intern -- instance Show Hunk where showsPrec d (Hunk _ _ b) = showsPrec d b instance IsString Hunk where fromString = hunk . UTF8.fromString instance Eq Hunk where (==) = (==) `on` identity instance Hashable Hunk where hash = hash . identity instance Ord Hunk where compare = compare `on` identity instance HasDelta Hunk where delta (Hunk _ d _) = d instance Interned Hunk where type Uninterned Hunk = ByteString data Description Hunk = Describe {-# UNPACK #-} !ByteString deriving (Eq) describe = Describe identify i bs = Hunk i (delta bs) bs identity (Hunk i _ _) = i cache = hunkCache instance Uninternable Hunk where unintern (Hunk _ _ bs) = bs instance Hashable (Description Hunk) where hash (Describe bs) = hash bs hunkCache :: Cache Hunk hunkCache = mkCache {-# NOINLINE hunkCache #-} instance Measured Delta Hunk where measure = delta
__label__pos
0.97808
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. So I just started playing with SignalR but can't get past the most basic setup of getting it to work. I can place breakpoints in the below controller and see the client connecting, however the client just gets a WebException immediately without any useful message regarding what the issue is. Does anything look wrong with this simple usage? public class LiveController : PersistentConnection { public override Task ProcessRequestAsync(HostContext context) { return base.ProcessRequestAsync(context); } protected override Task OnConnectedAsync(IRequest request, string connectionId) { return base.OnConnectedAsync(request, connectionId); } protected override Task OnReceivedAsync(IRequest request, string connectionId, string data) { return base.OnReceivedAsync(request, connectionId, data); } protected override Connection CreateConnection(string connectionId, IEnumerable<string> signals, IEnumerable<string> groups) { return base.CreateConnection(connectionId, signals, groups); } } And here is the client side: var connection = new Connection("http://192.168.0.102/live/"); connection.Start().ContinueWith(task => { dispatcher.BeginInvoke(() => { if (task.IsFaulted) { MessageBox.Show("Connection failed!"); } else { MessageBox.Show("Success!"); } }); }); And the exception: System.Net.WebException occurred HResult=-2146233079 Message=Exception of type 'System.Net.WebException' was thrown. Source=System.Windows StackTrace: at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at Microsoft.AspNet.SignalR.Client.Http.HttpHelper.<>c__DisplayClass2.<GetHttpResponseAsync>b__0(IAsyncResult ar) InnerException: System.Net.WebException HResult=-2146233079 Message=Exception of type 'System.Net.WebException' was thrown. Source=System.Windows StackTrace: at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState) InnerException: share|improve this question add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Browse other questions tagged or ask your own question.
__label__pos
0.761793
/ Wordpress / Поле Color Picker Поле Color Picker 19.09.2019 426 Используем на сайте функционал поля выбора цвета (Color Picker). Поле у страницы или записи // Add field Color Picker for page add_action( 'add_meta_boxes', 'mytheme_add_meta_box' ); if ( ! function_exists( 'mytheme_add_meta_box' ) ) { function mytheme_add_meta_box(){ add_meta_box( 'header-page-metabox-options', esc_html__('Header Color', 'mytheme' ), 'mytheme_header_meta_box', 'page', 'side', 'low'); } } add_action( 'admin_enqueue_scripts', 'mytheme_backend_scripts'); if ( ! function_exists( 'mytheme_backend_scripts' ) ){ function mytheme_backend_scripts( $hook ) { wp_enqueue_style( 'wp-color-picker'); wp_enqueue_script( 'wp-color-picker'); } } if ( ! function_exists( 'mytheme_header_meta_box' ) ) { function mytheme_header_meta_box( $post ) { $custom = get_post_custom( $post->ID ); $header_color = ( isset( $custom['header_color'][0] ) ) ? $custom['header_color'][0] : ''; wp_nonce_field( 'mytheme_header_meta_box', 'mytheme_header_meta_box_nonce' ); ?> <script> jQuery(document).ready(function($){ $('.color_field').each(function(){ $(this).wpColorPicker(); }); }); </script> <div class="pagebox"> <p><?php esc_attr_e('Choose a color for your post header.', 'mytheme' ); ?></p> <input class="color_field" type="hidden" name="header_color" value="<?php esc_attr_e( $header_color ); ?>"/> </div> <?php } } if ( ! function_exists( 'mytheme_save_header_meta_box' ) ) { function mytheme_save_header_meta_box( $post_id ) { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } if( !current_user_can( 'edit_pages' ) ) { return; } if ( !isset( $_POST['header_color'] ) || !wp_verify_nonce( $_POST['mytheme_header_meta_box_nonce'], 'mytheme_header_meta_box' ) ) { return; } $header_color = (isset($_POST['header_color']) && $_POST['header_color']!='') ? $_POST['header_color'] : ''; update_post_meta($post_id, 'header_color', $header_color); } } add_action( 'save_post', 'mytheme_save_header_meta_box' ); Вывод данного поля: <div style="background: <?php echo get_post_meta($post->ID, 'header_color', true); ?>;"> Color Picker в настройках темы function color_customizer($wp_customize){ $wp_customize->add_section( 'theme_colors_settings', array( 'title' => __( 'Theme Colors Settings', 'themeslug' ), 'priority' => 5, ) ); $theme_colors = array(); // Navigation Background Color $theme_colors[] = array( 'slug'=>'color_section_name', 'default' => '#000000', 'label' => __('Color Section Title', 'themeslug') ); foreach( $theme_colors as $color ) { $wp_customize->add_setting( $color['slug'], array( 'default' => $color['default'], 'sanitize_callback' => 'sanitize_hex_color', 'type' => 'option', 'capability' => 'edit_theme_options' ) ); $wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, $color['slug'], array('label' => $color['label'], 'section' => 'theme_colors_settings', 'settings' => $color['slug']) ) ); } } add_action( 'customize_register', 'color_customizer' ); Поделиться в соц. сетях: • Комментарии • Вложения Добавить комментарий Пока нет комментариев. Будь первым! Поле Color Picker Разделение записей по алфавиту Рекомендации для васРазделение записей по алфавитуOpttour.ru Спасибо! Наш менеджер свяжется с Вами в течении 5 минут.
__label__pos
0.80516
summaryrefslogtreecommitdiff path: root/scan.c blob: 538b30efc7f537b3bf1d5b183d55b3118870c786 (plain) 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 #include <net/if.h> #include <errno.h> #include <string.h> #include <ctype.h> #include <stdbool.h> #include <netlink/genl/genl.h> #include <netlink/genl/family.h> #include <netlink/genl/ctrl.h> #include <netlink/msg.h> #include <netlink/attr.h> #include "nl80211.h" #include "iw.h" #define WLAN_CAPABILITY_ESS (1<<0) #define WLAN_CAPABILITY_IBSS (1<<1) #define WLAN_CAPABILITY_CF_POLLABLE (1<<2) #define WLAN_CAPABILITY_CF_POLL_REQUEST (1<<3) #define WLAN_CAPABILITY_PRIVACY (1<<4) #define WLAN_CAPABILITY_SHORT_PREAMBLE (1<<5) #define WLAN_CAPABILITY_PBCC (1<<6) #define WLAN_CAPABILITY_CHANNEL_AGILITY (1<<7) #define WLAN_CAPABILITY_SPECTRUM_MGMT (1<<8) #define WLAN_CAPABILITY_QOS (1<<9) #define WLAN_CAPABILITY_SHORT_SLOT_TIME (1<<10) #define WLAN_CAPABILITY_APSD (1<<11) #define WLAN_CAPABILITY_RADIO_MEASURE (1<<12) #define WLAN_CAPABILITY_DSSS_OFDM (1<<13) #define WLAN_CAPABILITY_DEL_BACK (1<<14) #define WLAN_CAPABILITY_IMM_BACK (1<<15) /* DMG (60gHz) 802.11ad */ /* type - bits 0..1 */ #define WLAN_CAPABILITY_DMG_TYPE_MASK (3<<0) #define WLAN_CAPABILITY_DMG_TYPE_IBSS (1<<0) /* Tx by: STA */ #define WLAN_CAPABILITY_DMG_TYPE_PBSS (2<<0) /* Tx by: PCP */ #define WLAN_CAPABILITY_DMG_TYPE_AP (3<<0) /* Tx by: AP */ #define WLAN_CAPABILITY_DMG_CBAP_ONLY (1<<2) #define WLAN_CAPABILITY_DMG_CBAP_SOURCE (1<<3) #define WLAN_CAPABILITY_DMG_PRIVACY (1<<4) #define WLAN_CAPABILITY_DMG_ECPAC (1<<5) #define WLAN_CAPABILITY_DMG_SPECTRUM_MGMT (1<<8) #define WLAN_CAPABILITY_DMG_RADIO_MEASURE (1<<12) static unsigned char ms_oui[3] = { 0x00, 0x50, 0xf2 }; static unsigned char ieee80211_oui[3] = { 0x00, 0x0f, 0xac }; static unsigned char wfa_oui[3] = { 0x50, 0x6f, 0x9a }; struct scan_params { bool unknown; enum print_ie_type type; bool show_both_ie_sets; }; #define IEEE80211_COUNTRY_EXTENSION_ID 201 union ieee80211_country_ie_triplet { struct { __u8 first_channel; __u8 num_channels; __s8 max_power; } __attribute__ ((packed)) chans; struct { __u8 reg_extension_id; __u8 reg_class; __u8 coverage_class; } __attribute__ ((packed)) ext; } __attribute__ ((packed)); static int parse_random_mac_addr(struct nl_msg *msg, char *arg) { char *a_addr, *a_mask, *sep; unsigned char addr[ETH_ALEN], mask[ETH_ALEN]; char *addrs = arg + 9; if (*addrs != '=') return 0; addrs++; sep = strchr(addrs, '/'); a_addr = addrs; if (!sep) return 1; *sep = 0; a_mask = sep + 1; if (mac_addr_a2n(addr, a_addr) || mac_addr_a2n(mask, a_mask)) return 1; NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr); NLA_PUT(msg, NL80211_ATTR_MAC_MASK, ETH_ALEN, mask); return 0; nla_put_failure: return -ENOBUFS; } static int handle_scan(struct nl80211_state *state, struct nl_cb *cb, struct nl_msg *msg, int argc, char **argv, enum id_input id) { struct nl_msg *ssids = NULL, *freqs = NULL; char *eptr; int err = -ENOBUFS; int i; enum { NONE, FREQ, IES, SSID, MESHID, DONE, } parse = NONE; int freq; bool passive = false, have_ssids = false, have_freqs = false; size_t ies_len = 0, meshid_len = 0; unsigned char *ies = NULL, *meshid = NULL, *tmpies; unsigned int flags = 0; ssids = nlmsg_alloc(); if (!ssids) return -ENOMEM; freqs = nlmsg_alloc(); if (!freqs) { nlmsg_free(ssids); return -ENOMEM; } for (i = 0; i < argc; i++) { switch (parse) { case NONE: if (strcmp(argv[i], "freq") == 0) { parse = FREQ; have_freqs = true; break; } else if (strcmp(argv[i], "ies") == 0) { parse = IES; break; } else if (strcmp(argv[i], "lowpri") == 0) { flags |= NL80211_SCAN_FLAG_LOW_PRIORITY; break; } else if (strcmp(argv[i], "flush") == 0) { flags |= NL80211_SCAN_FLAG_FLUSH; break; } else if (strcmp(argv[i], "ap-force") == 0) { flags |= NL80211_SCAN_FLAG_AP; break; } else if (strncmp(argv[i], "randomise", 9) == 0 || strncmp(argv[i], "randomize", 9) == 0) { flags |= NL80211_SCAN_FLAG_RANDOM_ADDR; err = parse_random_mac_addr(msg, argv[i]); if (err) goto nla_put_failure; break; } else if (strcmp(argv[i], "ssid") == 0) { parse = SSID; have_ssids = true; break; } else if (strcmp(argv[i], "passive") == 0) { parse = DONE; passive = true; break; } else if (strcmp(argv[i], "meshid") == 0) { parse = MESHID; break; } case DONE: return 1; case FREQ: freq = strtoul(argv[i], &eptr, 10); if (eptr != argv[i] + strlen(argv[i])) { /* failed to parse as number -- maybe a tag? */ i--; parse = NONE; continue; } NLA_PUT_U32(freqs, i, freq); break; case IES: ies = parse_hex(argv[i], &ies_len); if (!ies) goto nla_put_failure; parse = NONE; break; case SSID: NLA_PUT(ssids, i, strlen(argv[i]), argv[i]); break; case MESHID: meshid_len = strlen(argv[i]); meshid = (unsigned char *) malloc(meshid_len + 2); if (!meshid) goto nla_put_failure; meshid[0] = 114; /* mesh element id */ meshid[1] = meshid_len; memcpy(&meshid[2], argv[i], meshid_len); meshid_len += 2; parse = NONE; break; } } if (ies || meshid) { tmpies = (unsigned char *) malloc(ies_len + meshid_len); if (!tmpies) goto nla_put_failure; if (ies) { memcpy(tmpies, ies, ies_len); free(ies); } if (meshid) { memcpy(&tmpies[ies_len], meshid, meshid_len); free(meshid); } NLA_PUT(msg, NL80211_ATTR_IE, ies_len + meshid_len, tmpies); free(tmpies); } if (!have_ssids) NLA_PUT(ssids, 1, 0, ""); if (!passive) nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids); if (have_freqs) nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs); if (flags) NLA_PUT_U32(msg, NL80211_ATTR_SCAN_FLAGS, flags); err = 0; nla_put_failure: nlmsg_free(ssids); nlmsg_free(freqs); return err; } static void tab_on_first(bool *first) { if (!*first) printf("\t"); else *first = false; } static void print_ssid(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" "); print_ssid_escaped(len, data); printf("\n"); } #define BSS_MEMBERSHIP_SELECTOR_VHT_PHY 126 #define BSS_MEMBERSHIP_SELECTOR_HT_PHY 127 static void print_supprates(const uint8_t type, uint8_t len, const uint8_t *data) { int i; printf(" "); for (i = 0; i < len; i++) { int r = data[i] & 0x7f; if (r == BSS_MEMBERSHIP_SELECTOR_VHT_PHY && data[i] & 0x80) printf("VHT"); else if (r == BSS_MEMBERSHIP_SELECTOR_HT_PHY && data[i] & 0x80) printf("HT"); else printf("%d.%d", r/2, 5*(r&1)); printf("%s ", data[i] & 0x80 ? "*" : ""); } printf("\n"); } static void print_ds(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" channel %d\n", data[0]); } static const char *country_env_str(char environment) { switch (environment) { case 'I': return "Indoor only"; case 'O': return "Outdoor only"; case ' ': return "Indoor/Outdoor"; default: return "bogus"; } } static void print_country(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" %.*s", 2, data); printf("\tEnvironment: %s\n", country_env_str(data[2])); data += 3; len -= 3; if (len < 3) { printf("\t\tNo country IE triplets present\n"); return; } while (len >= 3) { int end_channel; union ieee80211_country_ie_triplet *triplet = (void *) data; if (triplet->ext.reg_extension_id >= IEEE80211_COUNTRY_EXTENSION_ID) { printf("\t\tExtension ID: %d Regulatory Class: %d Coverage class: %d (up to %dm)\n", triplet->ext.reg_extension_id, triplet->ext.reg_class, triplet->ext.coverage_class, triplet->ext.coverage_class * 450); data += 3; len -= 3; continue; } /* 2 GHz */ if (triplet->chans.first_channel <= 14) end_channel = triplet->chans.first_channel + (triplet->chans.num_channels - 1); else end_channel = triplet->chans.first_channel + (4 * (triplet->chans.num_channels - 1)); printf("\t\tChannels [%d - %d] @ %d dBm\n", triplet->chans.first_channel, end_channel, triplet->chans.max_power); data += 3; len -= 3; } return; } static void print_powerconstraint(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" %d dB\n", data[0]); } static void print_tpcreport(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" TX power: %d dBm\n", data[0]); /* printf(" Link Margin (%d dB) is reserved in Beacons\n", data[1]); */ } static void print_erp(const uint8_t type, uint8_t len, const uint8_t *data) { if (data[0] == 0x00) printf(" <no flags>"); if (data[0] & 0x01) printf(" NonERP_Present"); if (data[0] & 0x02) printf(" Use_Protection"); if (data[0] & 0x04) printf(" Barker_Preamble_Mode"); printf("\n"); } static void print_cipher(const uint8_t *data) { if (memcmp(data, ms_oui, 3) == 0) { switch (data[3]) { case 0: printf("Use group cipher suite"); break; case 1: printf("WEP-40"); break; case 2: printf("TKIP"); break; case 4: printf("CCMP"); break; case 5: printf("WEP-104"); break; default: printf("%.02x-%.02x-%.02x:%d", data[0], data[1] ,data[2], data[3]); break; } } else if (memcmp(data, ieee80211_oui, 3) == 0) { switch (data[3]) { case 0: printf("Use group cipher suite"); break; case 1: printf("WEP-40"); break; case 2: printf("TKIP"); break; case 4: printf("CCMP"); break; case 5: printf("WEP-104"); break; case 6: printf("AES-128-CMAC"); break; case 8: printf("GCMP"); break; default: printf("%.02x-%.02x-%.02x:%d", data[0], data[1] ,data[2], data[3]); break; } } else printf("%.02x-%.02x-%.02x:%d", data[0], data[1] ,data[2], data[3]); } static void print_auth(const uint8_t *data) { if (memcmp(data, ms_oui, 3) == 0) { switch (data[3]) { case 1: printf("IEEE 802.1X"); break; case 2: printf("PSK"); break; default: printf("%.02x-%.02x-%.02x:%d", data[0], data[1] ,data[2], data[3]); break; } } else if (memcmp(data, ieee80211_oui, 3) == 0) { switch (data[3]) { case 1: printf("IEEE 802.1X"); break; case 2: printf("PSK"); break; case 3: printf("FT/IEEE 802.1X"); break; case 4: printf("FT/PSK"); break; case 5: printf("IEEE 802.1X/SHA-256"); break; case 6: printf("PSK/SHA-256"); break; case 7: printf("TDLS/TPK"); break; default: printf("%.02x-%.02x-%.02x:%d", data[0], data[1] ,data[2], data[3]); break; } } else printf("%.02x-%.02x-%.02x:%d", data[0], data[1] ,data[2], data[3]); } static void print_rsn_ie(const char *defcipher, const char *defauth, uint8_t len, const uint8_t *data) { bool first = true; __u16 version, count, capa; int i; version = data[0] + (data[1] << 8); tab_on_first(&first); printf("\t * Version: %d\n", version); data += 2; len -= 2; if (len < 4) { tab_on_first(&first); printf("\t * Group cipher: %s\n", defcipher); printf("\t * Pairwise ciphers: %s\n", defcipher); return; } tab_on_first(&first); printf("\t * Group cipher: "); print_cipher(data); printf("\n"); data += 4; len -= 4; if (len < 2) { tab_on_first(&first); printf("\t * Pairwise ciphers: %s\n", defcipher); return; } count = data[0] | (data[1] << 8); if (2 + (count * 4) > len) goto invalid; tab_on_first(&first); printf("\t * Pairwise ciphers:"); for (i = 0; i < count; i++) { printf(" "); print_cipher(data + 2 + (i * 4)); } printf("\n"); data += 2 + (count * 4); len -= 2 + (count * 4); if (len < 2) { tab_on_first(&first); printf("\t * Authentication suites: %s\n", defauth); return; } count = data[0] | (data[1] << 8); if (2 + (count * 4) > len) goto invalid; tab_on_first(&first); printf("\t * Authentication suites:"); for (i = 0; i < count; i++) { printf(" "); print_auth(data + 2 + (i * 4)); } printf("\n"); data += 2 + (count * 4); len -= 2 + (count * 4); if (len >= 2) { capa = data[0] | (data[1] << 8); tab_on_first(&first); printf("\t * Capabilities:"); if (capa & 0x0001) printf(" PreAuth"); if (capa & 0x0002) printf(" NoPairwise"); switch ((capa & 0x000c) >> 2) { case 0: printf(" 1-PTKSA-RC"); break; case 1: printf(" 2-PTKSA-RC"); break; case 2: printf(" 4-PTKSA-RC"); break; case 3: printf(" 16-PTKSA-RC"); break; } switch ((capa & 0x0030) >> 4) { case 0: printf(" 1-GTKSA-RC"); break; case 1: printf(" 2-GTKSA-RC"); break; case 2: printf(" 4-GTKSA-RC"); break; case 3: printf(" 16-GTKSA-RC"); break; } if (capa & 0x0040) printf(" MFP-required"); if (capa & 0x0080) printf(" MFP-capable"); if (capa & 0x0200) printf(" Peerkey-enabled"); if (capa & 0x0400) printf(" SPP-AMSDU-capable"); if (capa & 0x0800) printf(" SPP-AMSDU-required"); printf(" (0x%.4x)\n", capa); data += 2; len -= 2; } if (len >= 2) { int pmkid_count = data[0] | (data[1] << 8); if (len >= 2 + 16 * pmkid_count) { tab_on_first(&first); printf("\t * %d PMKIDs\n", pmkid_count); /* not printing PMKID values */ data += 2 + 16 * pmkid_count; len -= 2 + 16 * pmkid_count; } else goto invalid; } if (len >= 4) { tab_on_first(&first); printf("\t * Group mgmt cipher suite: "); print_cipher(data); printf("\n"); data += 4; len -= 4; } invalid: if (len != 0) { printf("\t\t * bogus tail data (%d):", len); while (len) { printf(" %.2x", *data); data++; len--; } printf("\n"); } } static void print_rsn(const uint8_t type, uint8_t len, const uint8_t *data) { print_rsn_ie("CCMP", "IEEE 802.1X", len, data); } static void print_ht_capa(const uint8_t type, uint8_t len, const uint8_t *data) { printf("\n"); print_ht_capability(data[0] | (data[1] << 8)); print_ampdu_length(data[2] & 3); print_ampdu_spacing((data[2] >> 2) & 7); print_ht_mcs(data + 3); } static const char* ntype_11u(uint8_t t) { switch (t) { case 0: return "Private"; case 1: return "Private with Guest"; case 2: return "Chargeable Public"; case 3: return "Free Public"; case 4: return "Personal Device"; case 5: return "Emergency Services Only"; case 14: return "Test or Experimental"; case 15: return "Wildcard"; default: return "Reserved"; } } static const char* vgroup_11u(uint8_t t) { switch (t) { case 0: return "Unspecified"; case 1: return "Assembly"; case 2: return "Business"; case 3: return "Educational"; case 4: return "Factory and Industrial"; case 5: return "Institutional"; case 6: return "Mercantile"; case 7: return "Residential"; case 8: return "Storage"; case 9: return "Utility and Miscellaneous"; case 10: return "Vehicular"; case 11: return "Outdoor"; default: return "Reserved"; } } static void print_interworking(const uint8_t type, uint8_t len, const uint8_t *data) { /* See Section 7.3.2.92 in the 802.11u spec. */ printf("\n"); if (len >= 1) { uint8_t ano = data[0]; printf("\t\tNetwork Options: 0x%hx\n", (unsigned short)(ano)); printf("\t\t\tNetwork Type: %i (%s)\n", (int)(ano & 0xf), ntype_11u(ano & 0xf)); if (ano & (1<<4)) printf("\t\t\tInternet\n"); if (ano & (1<<5)) printf("\t\t\tASRA\n"); if (ano & (1<<6)) printf("\t\t\tESR\n"); if (ano & (1<<7)) printf("\t\t\tUESA\n"); } if ((len == 3) || (len == 9)) { printf("\t\tVenue Group: %i (%s)\n", (int)(data[1]), vgroup_11u(data[1])); printf("\t\tVenue Type: %i\n", (int)(data[2])); } if (len == 9) printf("\t\tHESSID: %02hx:%02hx:%02hx:%02hx:%02hx:%02hx\n", data[3], data[4], data[5], data[6], data[7], data[8]); else if (len == 7) printf("\t\tHESSID: %02hx:%02hx:%02hx:%02hx:%02hx:%02hx\n", data[1], data[2], data[3], data[4], data[5], data[6]); } static void print_11u_advert(const uint8_t type, uint8_t len, const uint8_t *data) { /* See Section 7.3.2.93 in the 802.11u spec. */ /* TODO: This code below does not decode private protocol IDs */ int idx = 0; printf("\n"); while (idx < (len - 1)) { uint8_t qri = data[idx]; uint8_t proto_id = data[idx + 1]; printf("\t\tQuery Response Info: 0x%hx\n", (unsigned short)(qri)); printf("\t\t\tQuery Response Length Limit: %i\n", (qri & 0x7f)); if (qri & (1<<7)) printf("\t\t\tPAME-BI\n"); switch(proto_id) { case 0: printf("\t\t\tANQP\n"); break; case 1: printf("\t\t\tMIH Information Service\n"); break; case 2: printf("\t\t\tMIH Command and Event Services Capability Discovery\n"); break; case 3: printf("\t\t\tEmergency Alert System (EAS)\n"); break; case 221: printf("\t\t\tVendor Specific\n"); break; default: printf("\t\t\tReserved: %i\n", proto_id); break; } idx += 2; } } static void print_11u_rcon(const uint8_t type, uint8_t len, const uint8_t *data) { /* See Section 7.3.2.96 in the 802.11u spec. */ int idx = 0; int ln0 = data[1] & 0xf; int ln1 = ((data[1] & 0xf0) >> 4); int ln2 = 0; printf("\n"); if (ln1) ln2 = len - 2 - ln0 - ln1; printf("\t\tANQP OIs: %i\n", data[0]); if (ln0 > 0) { printf("\t\tOI 1: "); if (2 + ln0 > len) { printf("Invalid IE length.\n"); } else { for (idx = 0; idx < ln0; idx++) { printf("%02hx", data[2 + idx]); } printf("\n"); } } if (ln1 > 0) { printf("\t\tOI 2: "); if (2 + ln0 + ln1 > len) { printf("Invalid IE length.\n"); } else { for (idx = 0; idx < ln1; idx++) { printf("%02hx", data[2 + ln0 + idx]); } printf("\n"); } } if (ln2 > 0) { printf("\t\tOI 3: "); if (2 + ln0 + ln1 + ln2 > len) { printf("Invalid IE length.\n"); } else { for (idx = 0; idx < ln2; idx++) { printf("%02hx", data[2 + ln0 + ln1 + idx]); } printf("\n"); } } } static const char *ht_secondary_offset[4] = { "no secondary", "above", "[reserved!]", "below", }; static void print_ht_op(const uint8_t type, uint8_t len, const uint8_t *data) { static const char *protection[4] = { "no", "nonmember", "20 MHz", "non-HT mixed", }; static const char *sta_chan_width[2] = { "20 MHz", "any", }; printf("\n"); printf("\t\t * primary channel: %d\n", data[0]); printf("\t\t * secondary channel offset: %s\n", ht_secondary_offset[data[1] & 0x3]); printf("\t\t * STA channel width: %s\n", sta_chan_width[(data[1] & 0x4)>>2]); printf("\t\t * RIFS: %d\n", (data[1] & 0x8)>>3); printf("\t\t * HT protection: %s\n", protection[data[2] & 0x3]); printf("\t\t * non-GF present: %d\n", (data[2] & 0x4) >> 2); printf("\t\t * OBSS non-GF present: %d\n", (data[2] & 0x10) >> 4); printf("\t\t * dual beacon: %d\n", (data[4] & 0x40) >> 6); printf("\t\t * dual CTS protection: %d\n", (data[4] & 0x80) >> 7); printf("\t\t * STBC beacon: %d\n", data[5] & 0x1); printf("\t\t * L-SIG TXOP Prot: %d\n", (data[5] & 0x2) >> 1); printf("\t\t * PCO active: %d\n", (data[5] & 0x4) >> 2); printf("\t\t * PCO phase: %d\n", (data[5] & 0x8) >> 3); } static void print_capabilities(const uint8_t type, uint8_t len, const uint8_t *data) { int i, base, bit; bool first = true; for (i = 0; i < len; i++) { base = i * 8; for (bit = 0; bit < 8; bit++) { if (!(data[i] & (1 << bit))) continue; if (!first) printf(","); else first = false; #define CAPA(bit, name) case bit: printf(" " name); break switch (bit + base) { CAPA(0, "HT Information Exchange Supported"); CAPA(1, "reserved (On-demand Beacon)"); CAPA(2, "Extended Channel Switching"); CAPA(3, "reserved (Wave Indication)"); CAPA(4, "PSMP Capability"); CAPA(5, "reserved (Service Interval Granularity)"); CAPA(6, "S-PSMP Capability"); CAPA(7, "Event"); CAPA(8, "Diagnostics"); CAPA(9, "Multicast Diagnostics"); CAPA(10, "Location Tracking"); CAPA(11, "FMS"); CAPA(12, "Proxy ARP Service"); CAPA(13, "Collocated Interference Reporting"); CAPA(14, "Civic Location"); CAPA(15, "Geospatial Location"); CAPA(16, "TFS"); CAPA(17, "WNM-Sleep Mode"); CAPA(18, "TIM Broadcast"); CAPA(19, "BSS Transition"); CAPA(20, "QoS Traffic Capability"); CAPA(21, "AC Station Count"); CAPA(22, "Multiple BSSID"); CAPA(23, "Timing Measurement"); CAPA(24, "Channel Usage"); CAPA(25, "SSID List"); CAPA(26, "DMS"); CAPA(27, "UTC TSF Offset"); CAPA(28, "TDLS Peer U-APSD Buffer STA Support"); CAPA(29, "TDLS Peer PSM Support"); CAPA(30, "TDLS channel switching"); CAPA(31, "Interworking"); CAPA(32, "QoS Map"); CAPA(33, "EBR"); CAPA(34, "SSPN Interface"); CAPA(35, "Reserved"); CAPA(36, "MSGCF Capability"); CAPA(37, "TDLS Support"); CAPA(38, "TDLS Prohibited"); CAPA(39, "TDLS Channel Switching Prohibited"); CAPA(40, "Reject Unadmitted Frame"); CAPA(44, "Identifier Location"); CAPA(45, "U-APSD Coexistence"); CAPA(46, "WNM-Notification"); CAPA(47, "Reserved"); CAPA(48, "UTF-8 SSID"); default: printf(" %d", bit); break; } #undef CAPA } } printf("\n"); } static void print_tim(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" DTIM Count %u DTIM Period %u Bitmap Control 0x%x " "Bitmap[0] 0x%x", data[0], data[1], data[2], data[3]); if (len - 4) printf(" (+ %u octet%s)", len - 4, len - 4 == 1 ? "" : "s"); printf("\n"); } static void print_ibssatim(const uint8_t type, uint8_t len, const uint8_t *data) { printf(" %d TUs", (data[1] << 8) + data[0]); } static void print_vht_capa(const uint8_t type, uint8_t len, const uint8_t *data) { printf("\n"); print_vht_info(data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24), data + 4); } static void print_vht_oper(const uint8_t type, uint8_t len, const uint8_t *data) { const char *chandwidths[] = { [0] = "20 or 40 MHz", [1] = "80 MHz", [3] = "80+80 MHz", [2] = "160 MHz", }; printf("\n"); printf("\t\t * channel width: %d (%s)\n", data[0], data[0] < ARRAY_SIZE(chandwidths) ? chandwidths[data[0]] : "unknown"); printf("\t\t * center freq segment 1: %d\n", data[1]); printf("\t\t * center freq segment 2: %d\n", data[2]); printf("\t\t * VHT basic MCS set: 0x%.2x%.2x\n", data[4], data[3]); } static void print_obss_scan_params(const uint8_t type, uint8_t len, const uint8_t *data) { printf("\n"); printf("\t\t * passive dwell: %d TUs\n", (data[1] << 8) | data[0]); printf("\t\t * active dwell: %d TUs\n", (data[3] << 8) | data[2]); printf("\t\t * channel width trigger scan interval: %d s\n", (data[5] << 8) | data[4]); printf("\t\t * scan passive total per channel: %d TUs\n", (data[7] << 8) | data[6]); printf("\t\t * scan active total per channel: %d TUs\n", (data[9] << 8) | data[8]); printf("\t\t * BSS width channel transition delay factor: %d\n", (data[11] << 8) | data[10]); printf("\t\t * OBSS Scan Activity Threshold: %d.%02d %%\n", ((data[13] << 8) | data[12]) / 100, ((data[13] << 8) | data[12]) % 100); } static void print_secchan_offs(const uint8_t type, uint8_t len, const uint8_t *data) { if (data[0] < ARRAY_SIZE(ht_secondary_offset)) printf(" %s (%d)\n", ht_secondary_offset[data[0]], data[0]); else printf(" %d\n", data[0]); } static void print_bss_load(const uint8_t type, uint8_t len, const uint8_t *data) { printf("\n"); printf("\t\t * station count: %d\n", (data[1] << 8) | data[0]); printf("\t\t * channel utilisation: %d/255\n", data[2]); printf("\t\t * available admission capacity: %d [*32us]\n", (data[4] << 8) | data[3]); } static void print_mesh_conf(const uint8_t type, uint8_t len, const uint8_t *data) { printf("\n"); printf("\t\t * Active Path Selection Protocol ID: %d\n", data[0]); printf("\t\t * Active Path Selection Metric ID: %d\n", data[1]); printf("\t\t * Congestion Control Mode ID: %d\n", data[2]); printf("\t\t * Synchronization Method ID: %d\n", data[3]); printf("\t\t * Authentication Protocol ID: %d\n", data[4]); printf("\t\t * Mesh Formation Info:\n"); printf("\t\t\t Number of Peerings: %d\n", (data[5] & 0x7E) >> 1); if (data[5] & 0x01) printf("\t\t\t Connected to Mesh Gate\n"); if (data[5] & 0x80) printf("\t\t\t Connected to AS\n"); printf("\t\t * Mesh Capability\n"); if (data[6] & 0x01) printf("\t\t\t Accepting Additional Mesh Peerings\n"); if (data[6] & 0x02) printf("\t\t\t MCCA Supported\n"); if (data[6] & 0x04) printf("\t\t\t MCCA Enabled\n"); if (data[6] & 0x08) printf("\t\t\t Forwarding\n"); if (data[6] & 0x10) printf("\t\t\t MBCA Supported\n"); if (data[6] & 0x20) printf("\t\t\t TBTT Adjusting\n"); if (data[6] & 0x40) printf("\t\t\t Mesh Power Save Level\n"); } struct ie_print { const char *name; void (*print)(const uint8_t type, uint8_t len, const uint8_t *data); uint8_t minlen, maxlen; uint8_t flags; }; static void print_ie(const struct ie_print *p, const uint8_t type, uint8_t len, const uint8_t *data) { int i; if (!p->print) return; printf("\t%s:", p->name); if (len < p->minlen || len > p->maxlen) { if (len > 1) { printf(" <invalid: %d bytes:", len); for (i = 0; i < len; i++) printf(" %.02x", data[i]); printf(">\n"); } else if (len) printf(" <invalid: 1 byte: %.02x>\n", data[0]); else printf(" <invalid: no data>\n"); return; } p->print(type, len, data); } #define PRINT_IGN { \ .name = "IGNORE", \ .print = NULL, \ .minlen = 0, \ .maxlen = 255, \ } static const struct ie_print ieprinters[] = { [0] = { "SSID", print_ssid, 0, 32, BIT(PRINT_SCAN) | BIT(PRINT_LINK), }, [1] = { "Supported rates", print_supprates, 0, 255, BIT(PRINT_SCAN), }, [3] = { "DS Parameter set", print_ds, 1, 1, BIT(PRINT_SCAN), }, [5] = { "TIM", print_tim, 4, 255, BIT(PRINT_SCAN), }, [6] = { "IBSS ATIM window", print_ibssatim, 2, 2, BIT(PRINT_SCAN), }, [7] = { "Country", print_country, 3, 255, BIT(PRINT_SCAN), }, [11] = { "BSS Load", print_bss_load, 5, 5, BIT(PRINT_SCAN), }, [32] = { "Power constraint", print_powerconstraint, 1, 1, BIT(PRINT_SCAN), }, [35] = { "TPC report", print_tpcreport, 2, 2, BIT(PRINT_SCAN), }, [42] = { "ERP", print_erp, 1, 255, BIT(PRINT_SCAN), }, [45] = { "HT capabilities", print_ht_capa, 26, 26, BIT(PRINT_SCAN), }, [47] = { "ERP D4.0", print_erp, 1, 255, BIT(PRINT_SCAN), }, [74] = { "Overlapping BSS scan params", print_obss_scan_params, 14, 255, BIT(PRINT_SCAN), }, [61] = { "HT operation", print_ht_op, 22, 22, BIT(PRINT_SCAN), }, [62] = { "Secondary Channel Offset", print_secchan_offs, 1, 1, BIT(PRINT_SCAN), }, [191] = { "VHT capabilities", print_vht_capa, 12, 255, BIT(PRINT_SCAN), }, [192] = { "VHT operation", print_vht_oper, 5, 255, BIT(PRINT_SCAN), }, [48] = { "RSN", print_rsn, 2, 255, BIT(PRINT_SCAN), }, [50] = { "Extended supported rates", print_supprates, 0, 255, BIT(PRINT_SCAN), }, [113] = { "MESH Configuration", print_mesh_conf, 7, 7, BIT(PRINT_SCAN), }, [114] = { "MESH ID", print_ssid, 0, 32, BIT(PRINT_SCAN) | BIT(PRINT_LINK), }, [127] = { "Extended capabilities", print_capabilities, 0, 255, BIT(PRINT_SCAN), }, [107] = { "802.11u Interworking", print_interworking, 0, 255, BIT(PRINT_SCAN), }, [108] = { "802.11u Advertisement", print_11u_advert, 0, 255, BIT(PRINT_SCAN), }, [111] = { "802.11u Roaming Consortium", print_11u_rcon, 0, 255, BIT(PRINT_SCAN), }, }; static void print_wifi_wpa(const uint8_t type, uint8_t len, const uint8_t *data) { print_rsn_ie("TKIP", "IEEE 802.1X", len, data); } static bool print_wifi_wmm_param(const uint8_t *data, uint8_t len) { int i; static const char *aci_tbl[] = { "BE", "BK", "VI", "VO" }; if (len < 19) goto invalid; if (data[0] != 1) { printf("Parameter: not version 1: "); return false; } printf("\t * Parameter version 1"); data++; if (data[0] & 0x80) printf("\n\t\t * u-APSD"); data += 2; for (i = 0; i < 4; i++) { printf("\n\t\t * %s:", aci_tbl[(data[0] >> 5) & 3]); if (data[0] & 0x10) printf(" acm"); printf(" CW %d-%d", (1 << (data[1] & 0xf)) - 1, (1 << (data[1] >> 4)) - 1); printf(", AIFSN %d", data[0] & 0xf); if (data[2] | data[3]) printf(", TXOP %d usec", (data[2] + (data[3] << 8)) * 32); data += 4; } printf("\n"); return true; invalid: printf("invalid: "); return false; } static void print_wifi_wmm(const uint8_t type, uint8_t len, const uint8_t *data) { int i; switch (data[0]) { case 0x00: printf(" information:"); break; case 0x01: if (print_wifi_wmm_param(data + 1, len - 1)) return; break; default: printf(" type %d:", data[0]); break; } for(i = 1; i < len; i++) printf(" %.02x", data[i]); printf("\n"); } static const char * wifi_wps_dev_passwd_id(uint16_t id) { switch (id) { case 0: return "Default (PIN)"; case 1: return "User-specified"; case 2: return "Machine-specified"; case 3: return "Rekey"; case 4: return "PushButton"; case 5: return "Registrar-specified"; default: return "??"; } } static void print_wifi_wps(const uint8_t type, uint8_t len, const uint8_t *data) { bool first = true; __u16 subtype, sublen; while (len >= 4) { subtype = (data[0] << 8) + data[1]; sublen = (data[2] << 8) + data[3]; if (sublen > len) break; switch (subtype) { case 0x104a: tab_on_first(&first); printf("\t * Version: %d.%d\n", data[4] >> 4, data[4] & 0xF); break; case 0x1011: tab_on_first(&first); printf("\t * Device name: %.*s\n", sublen, data + 4); break; case 0x1012: { uint16_t id; tab_on_first(&first); if (sublen != 2) { printf("\t * Device Password ID: (invalid " "length %d)\n", sublen); break; } id = data[4] << 8 | data[5]; printf("\t * Device Password ID: %u (%s)\n", id, wifi_wps_dev_passwd_id(id)); break; } case 0x1021: tab_on_first(&first); printf("\t * Manufacturer: %.*s\n", sublen, data + 4); break; case 0x1023: tab_on_first(&first); printf("\t * Model: %.*s\n", sublen, data + 4); break; case 0x1024: tab_on_first(&first); printf("\t * Model Number: %.*s\n", sublen, data + 4); break; case 0x103b: { __u8 val = data[4]; tab_on_first(&first); printf("\t * Response Type: %d%s\n", val, val == 3 ? " (AP)" : ""); break; } case 0x103c: { __u8 val = data[4]; tab_on_first(&first); printf("\t * RF Bands: 0x%x\n", val); break; } case 0x1041: { __u8 val = data[4]; tab_on_first(&first); printf("\t * Selected Registrar: 0x%x\n", val); break; } case 0x1042: tab_on_first(&first); printf("\t * Serial Number: %.*s\n", sublen, data + 4); break; case 0x1044: { __u8 val = data[4]; tab_on_first(&first); printf("\t * Wi-Fi Protected Setup State: %d%s%s\n", val, val == 1 ? " (Unconfigured)" : "", val == 2 ? " (Configured)" : ""); break; } case 0x1047: tab_on_first(&first); printf("\t * UUID: "); if (sublen != 16) { printf("(invalid, length=%d)\n", sublen); break; } printf("%02x%02x%02x%02x-%02x%02x-%02x%02x-" "%02x%02x-%02x%02x%02x%02x%02x%02x\n", data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19]); break; case 0x1054: { tab_on_first(&first); if (sublen != 8) { printf("\t * Primary Device Type: (invalid " "length %d)\n", sublen); break; } printf("\t * Primary Device Type: " "%u-%02x%02x%02x%02x-%u\n", data[4] << 8 | data[5], data[6], data[7], data[8], data[9], data[10] << 8 | data[11]); break; } case 0x1057: { __u8 val = data[4]; tab_on_first(&first); printf("\t * AP setup locked: 0x%.2x\n", val); break; } case 0x1008: case 0x1053: { __u16 meth = (data[4] << 8) + data[5]; bool comma = false; tab_on_first(&first); printf("\t * %sConfig methods:", subtype == 0x1053 ? "Selected Registrar ": ""); #define T(bit, name) do { \ if (meth & (1<<bit)) { \ if (comma) \ printf(","); \ comma = true; \ printf(" " name); \ } } while (0) T(0, "USB"); T(1, "Ethernet"); T(2, "Label"); T(3, "Display"); T(4, "Ext. NFC"); T(5, "Int. NFC"); T(6, "NFC Intf."); T(7, "PBC"); T(8, "Keypad"); printf("\n"); break; #undef T } default: { const __u8 *subdata = data + 4; __u16 tmplen = sublen; tab_on_first(&first); printf("\t * Unknown TLV (%#.4x, %d bytes):", subtype, tmplen); while (tmplen) { printf(" %.2x", *subdata); subdata++; tmplen--; } printf("\n"); break; } } data += sublen + 4; len -= sublen + 4; } if (len != 0) { printf("\t\t * bogus tail data (%d):", len); while (len) { printf(" %.2x", *data); data++; len--; } printf("\n"); } } static const struct ie_print wifiprinters[] = { [1] = { "WPA", print_wifi_wpa, 2, 255, BIT(PRINT_SCAN), }, [2] = { "WMM", print_wifi_wmm, 1, 255, BIT(PRINT_SCAN), }, [4] = { "WPS", print_wifi_wps, 0, 255, BIT(PRINT_SCAN), }, }; static inline void print_p2p(const uint8_t type, uint8_t len, const uint8_t *data) { bool first = true; __u8 subtype; __u16 sublen; while (len >= 3) { subtype = data[0]; sublen = (data[2] << 8) + data[1]; if (sublen > len - 3) break; switch (subtype) { case 0x02: /* capability */ tab_on_first(&first); if (sublen < 2) { printf("\t * malformed capability\n"); break; } printf("\t * Group capa: 0x%.2x, Device capa: 0x%.2x\n", data[3], data[4]); break; case 0x0d: /* device info */ if (sublen < 6 + 2 + 8 + 1) { printf("\t * malformed device info\n"); break; } /* fall through for now */ case 0x00: /* status */ case 0x01: /* minor reason */ case 0x03: /* device ID */ case 0x04: /* GO intent */ case 0x05: /* configuration timeout */ case 0x06: /* listen channel */ case 0x07: /* group BSSID */ case 0x08: /* ext listen timing */ case 0x09: /* intended interface address */ case 0x0a: /* manageability */ case 0x0b: /* channel list */ case 0x0c: /* NoA */ case 0x0e: /* group info */ case 0x0f: /* group ID */ case 0x10: /* interface */ case 0x11: /* operating channel */ case 0x12: /* invitation flags */ case 0xdd: /* vendor specific */ default: { const __u8 *subdata = data + 4; __u16 tmplen = sublen; tab_on_first(&first); printf("\t * Unknown TLV (%#.2x, %d bytes):", subtype, tmplen); while (tmplen) { printf(" %.2x", *subdata); subdata++; tmplen--; } printf("\n"); break; } } data += sublen + 3; len -= sublen + 3; } if (len != 0) { tab_on_first(&first); printf("\t * bogus tail data (%d):", len); while (len) { printf(" %.2x", *data); data++; len--; } printf("\n"); } } static inline void print_hs20_ind(const uint8_t type, uint8_t len, const uint8_t *data) { /* I can't find the spec for this...just going off what wireshark uses. */ printf("\n"); if (len > 0) printf("\t\tDGAF: %i\n", (int)(data[0] & 0x1)); else printf("\t\tUnexpected length: %i\n", len); } static const struct ie_print wfa_printers[] = { [9] = { "P2P", print_p2p, 2, 255, BIT(PRINT_SCAN), }, [16] = { "HotSpot 2.0 Indication", print_hs20_ind, 1, 255, BIT(PRINT_SCAN), }, }; static void print_vendor(unsigned char len, unsigned char *data, bool unknown, enum print_ie_type ptype) { int i; if (len < 3) { printf("\tVendor specific: <too short> data:"); for(i = 0; i < len; i++) printf(" %.02x", data[i]); printf("\n"); return; } if (len >= 4 && memcmp(data, ms_oui, 3) == 0) { if (data[3] < ARRAY_SIZE(wifiprinters) && wifiprinters[data[3]].name && wifiprinters[data[3]].flags & BIT(ptype)) { print_ie(&wifiprinters[data[3]], data[3], len - 4, data + 4); return; } if (!unknown) return; printf("\tMS/WiFi %#.2x, data:", data[3]); for(i = 0; i < len - 4; i++) printf(" %.02x", data[i + 4]); printf("\n"); return; } if (len >= 4 && memcmp(data, wfa_oui, 3) == 0) { if (data[3] < ARRAY_SIZE(wfa_printers) && wfa_printers[data[3]].name && wfa_printers[data[3]].flags & BIT(ptype)) { print_ie(&wfa_printers[data[3]], data[3], len - 4, data + 4); return; } if (!unknown) return; printf("\tWFA %#.2x, data:", data[3]); for(i = 0; i < len - 4; i++) printf(" %.02x", data[i + 4]); printf("\n"); return; } if (!unknown) return; printf("\tVendor specific: OUI %.2x:%.2x:%.2x, data:", data[0], data[1], data[2]); for (i = 3; i < len; i++) printf(" %.2x", data[i]); printf("\n"); } void print_ies(unsigned char *ie, int ielen, bool unknown, enum print_ie_type ptype) { while (ielen >= 2 && ielen >= ie[1]) { if (ie[0] < ARRAY_SIZE(ieprinters) && ieprinters[ie[0]].name && ieprinters[ie[0]].flags & BIT(ptype)) { print_ie(&ieprinters[ie[0]], ie[0], ie[1], ie + 2); } else if (ie[0] == 221 /* vendor */) { print_vendor(ie[1], ie + 2, unknown, ptype); } else if (unknown) { int i; printf("\tUnknown IE (%d):", ie[0]); for (i=0; i<ie[1]; i++) printf(" %.2x", ie[2+i]); printf("\n"); } ielen -= ie[1] + 2; ie += ie[1] + 2; } } static void print_capa_dmg(__u16 capa) { switch (capa & WLAN_CAPABILITY_DMG_TYPE_MASK) { case WLAN_CAPABILITY_DMG_TYPE_AP: printf(" DMG_ESS"); break; case WLAN_CAPABILITY_DMG_TYPE_PBSS: printf(" DMG_PCP"); break; case WLAN_CAPABILITY_DMG_TYPE_IBSS: printf(" DMG_IBSS"); break; } if (capa & WLAN_CAPABILITY_DMG_CBAP_ONLY) printf(" CBAP_Only"); if (capa & WLAN_CAPABILITY_DMG_CBAP_SOURCE) printf(" CBAP_Src"); if (capa & WLAN_CAPABILITY_DMG_PRIVACY) printf(" Privacy"); if (capa & WLAN_CAPABILITY_DMG_ECPAC) printf(" ECPAC"); if (capa & WLAN_CAPABILITY_DMG_SPECTRUM_MGMT) printf(" SpectrumMgmt"); if (capa & WLAN_CAPABILITY_DMG_RADIO_MEASURE) printf(" RadioMeasure"); } static void print_capa_non_dmg(__u16 capa) { if (capa & WLAN_CAPABILITY_ESS) printf(" ESS"); if (capa & WLAN_CAPABILITY_IBSS) printf(" IBSS"); if (capa & WLAN_CAPABILITY_CF_POLLABLE) printf(" CfPollable"); if (capa & WLAN_CAPABILITY_CF_POLL_REQUEST) printf(" CfPollReq"); if (capa & WLAN_CAPABILITY_PRIVACY) printf(" Privacy"); if (capa & WLAN_CAPABILITY_SHORT_PREAMBLE) printf(" ShortPreamble"); if (capa & WLAN_CAPABILITY_PBCC) printf(" PBCC"); if (capa & WLAN_CAPABILITY_CHANNEL_AGILITY) printf(" ChannelAgility"); if (capa & WLAN_CAPABILITY_SPECTRUM_MGMT) printf(" SpectrumMgmt"); if (capa & WLAN_CAPABILITY_QOS) printf(" QoS"); if (capa & WLAN_CAPABILITY_SHORT_SLOT_TIME) printf(" ShortSlotTime"); if (capa & WLAN_CAPABILITY_APSD) printf(" APSD"); if (capa & WLAN_CAPABILITY_RADIO_MEASURE) printf(" RadioMeasure"); if (capa & WLAN_CAPABILITY_DSSS_OFDM) printf(" DSSS-OFDM"); if (capa & WLAN_CAPABILITY_DEL_BACK) printf(" DelayedBACK"); if (capa & WLAN_CAPABILITY_IMM_BACK) printf(" ImmediateBACK"); } static int print_bss_handler(struct nl_msg *msg, void *arg) { struct nlattr *tb[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); struct nlattr *bss[NL80211_BSS_MAX + 1]; char mac_addr[20], dev[20]; static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = { [NL80211_BSS_TSF] = { .type = NLA_U64 }, [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 }, [NL80211_BSS_BSSID] = { }, [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 }, [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 }, [NL80211_BSS_INFORMATION_ELEMENTS] = { }, [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 }, [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 }, [NL80211_BSS_STATUS] = { .type = NLA_U32 }, [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 }, [NL80211_BSS_BEACON_IES] = { }, }; struct scan_params *params = arg; int show = params->show_both_ie_sets ? 2 : 1; bool is_dmg = false; nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); if (!tb[NL80211_ATTR_BSS]) { fprintf(stderr, "bss info missing!\n"); return NL_SKIP; } if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS], bss_policy)) { fprintf(stderr, "failed to parse nested attributes!\n"); return NL_SKIP; } if (!bss[NL80211_BSS_BSSID]) return NL_SKIP; mac_addr_n2a(mac_addr, nla_data(bss[NL80211_BSS_BSSID])); printf("BSS %s", mac_addr); if (tb[NL80211_ATTR_IFINDEX]) { if_indextoname(nla_get_u32(tb[NL80211_ATTR_IFINDEX]), dev); printf("(on %s)", dev); } if (bss[NL80211_BSS_STATUS]) { switch (nla_get_u32(bss[NL80211_BSS_STATUS])) { case NL80211_BSS_STATUS_AUTHENTICATED: printf(" -- authenticated"); break; case NL80211_BSS_STATUS_ASSOCIATED: printf(" -- associated"); break; case NL80211_BSS_STATUS_IBSS_JOINED: printf(" -- joined"); break; default: printf(" -- unknown status: %d", nla_get_u32(bss[NL80211_BSS_STATUS])); break; } } printf("\n"); if (bss[NL80211_BSS_TSF]) { unsigned long long tsf; tsf = (unsigned long long)nla_get_u64(bss[NL80211_BSS_TSF]); printf("\tTSF: %llu usec (%llud, %.2lld:%.2llu:%.2llu)\n", tsf, tsf/1000/1000/60/60/24, (tsf/1000/1000/60/60) % 24, (tsf/1000/1000/60) % 60, (tsf/1000/1000) % 60); } if (bss[NL80211_BSS_FREQUENCY]) { int freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]); printf("\tfreq: %d\n", freq); if (freq > 45000) is_dmg = true; } if (bss[NL80211_BSS_BEACON_INTERVAL]) printf("\tbeacon interval: %d TUs\n", nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL])); if (bss[NL80211_BSS_CAPABILITY]) { __u16 capa = nla_get_u16(bss[NL80211_BSS_CAPABILITY]); printf("\tcapability:"); if (is_dmg) print_capa_dmg(capa); else print_capa_non_dmg(capa); printf(" (0x%.4x)\n", capa); } if (bss[NL80211_BSS_SIGNAL_MBM]) { int s = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]); printf("\tsignal: %d.%.2d dBm\n", s/100, s%100); } if (bss[NL80211_BSS_SIGNAL_UNSPEC]) { unsigned char s = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]); printf("\tsignal: %d/100\n", s); } if (bss[NL80211_BSS_SEEN_MS_AGO]) { int age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]); printf("\tlast seen: %d ms ago\n", age); } if (bss[NL80211_BSS_INFORMATION_ELEMENTS] && show--) { if (bss[NL80211_BSS_BEACON_IES]) printf("\tInformation elements from Probe Response " "frame:\n"); print_ies(nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]), nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]), params->unknown, params->type); } if (bss[NL80211_BSS_BEACON_IES] && show--) { printf("\tInformation elements from Beacon frame:\n"); print_ies(nla_data(bss[NL80211_BSS_BEACON_IES]), nla_len(bss[NL80211_BSS_BEACON_IES]), params->unknown, params->type); } return NL_SKIP; } static struct scan_params scan_params; static int handle_scan_dump(struct nl80211_state *state, struct nl_cb *cb, struct nl_msg *msg, int argc, char **argv, enum id_input id) { if (argc > 1) return 1; memset(&scan_params, 0, sizeof(scan_params)); if (argc == 1 && !strcmp(argv[0], "-u")) scan_params.unknown = true; else if (argc == 1 && !strcmp(argv[0], "-b")) scan_params.show_both_ie_sets = true; scan_params.type = PRINT_SCAN; nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, print_bss_handler, &scan_params); return 0; } static int handle_scan_combined(struct nl80211_state *state, struct nl_cb *cb, struct nl_msg *msg, int argc, char **argv, enum id_input id) { char **trig_argv; static char *dump_argv[] = { NULL, "scan", "dump", NULL, }; static const __u32 cmds[] = { NL80211_CMD_NEW_SCAN_RESULTS, NL80211_CMD_SCAN_ABORTED, }; int trig_argc, dump_argc, err; if (argc >= 3 && !strcmp(argv[2], "-u")) { dump_argc = 4; dump_argv[3] = "-u"; } else if (argc >= 3 && !strcmp(argv[2], "-b")) { dump_argc = 4; dump_argv[3] = "-b"; } else dump_argc = 3; trig_argc = 3 + (argc - 2) + (3 - dump_argc); trig_argv = calloc(trig_argc, sizeof(*trig_argv)); if (!trig_argv) return -ENOMEM; trig_argv[0] = argv[0]; trig_argv[1] = "scan"; trig_argv[2] = "trigger"; int i; for (i = 0; i < argc - 2 - (dump_argc - 3); i++) trig_argv[i + 3] = argv[i + 2 + (dump_argc - 3)]; err = handle_cmd(state, id, trig_argc, trig_argv); free(trig_argv); if (err) return err; /* * WARNING: DO NOT COPY THIS CODE INTO YOUR APPLICATION * * This code has a bug, which requires creating a separate * nl80211 socket to fix: * It is possible for a NL80211_CMD_NEW_SCAN_RESULTS or * NL80211_CMD_SCAN_ABORTED message to be sent by the kernel * before (!) we listen to it, because we only start listening * after we send our scan request. * * Doing it the other way around has a race condition as well, * if you first open the events socket you may get a notification * for a previous scan. * * The only proper way to fix this would be to listen to events * before sending the command, and for the kernel to send the * scan request along with the event, so that you can match up * whether the scan you requested was finished or aborted (this * may result in processing a scan that another application * requested, but that doesn't seem to be a problem). * * Alas, the kernel doesn't do that (yet). */ if (listen_events(state, ARRAY_SIZE(cmds), cmds) == NL80211_CMD_SCAN_ABORTED) { printf("scan aborted!\n"); return 0; } dump_argv[0] = argv[0]; return handle_cmd(state, id, dump_argc, dump_argv); } TOPLEVEL(scan, "[-u] [freq <freq>*] [ies <hex as 00:11:..>] [meshid <meshid>] [lowpri,flush,ap-force] [randomise[=<addr>/<mask>]] [ssid <ssid>*|passive]", 0, 0, CIB_NETDEV, handle_scan_combined, "Scan on the given frequencies and probe for the given SSIDs\n" "(or wildcard if not given) unless passive scanning is requested.\n" "If -u is specified print unknown data in the scan results.\n" "Specified (vendor) IEs must be well-formed."); COMMAND(scan, dump, "[-u]", NL80211_CMD_GET_SCAN, NLM_F_DUMP, CIB_NETDEV, handle_scan_dump, "Dump the current scan results. If -u is specified, print unknown\n" "data in scan results."); COMMAND(scan, trigger, "[freq <freq>*] [ies <hex as 00:11:..>] [meshid <meshid>] [lowpri,flush,ap-force] [randomise[=<addr>/<mask>]] [ssid <ssid>*|passive]", NL80211_CMD_TRIGGER_SCAN, 0, CIB_NETDEV, handle_scan, "Trigger a scan on the given frequencies with probing for the given\n" "SSIDs (or wildcard if not given) unless passive scanning is requested.");
__label__pos
0.912147
DJ Your next social gathering by These MP3 & Audio Apps A phone (brief fortelecellphone ) is an electronic device intended to allow two-way audio notice. NOTE: shopping for audio codes from internet websites or inside-sport is a violation of Ankama's TOS Does Zune software occupation windows eight? In: http://mp3gain.sourceforge.net/ are all of the kinds of security software you may set up on a pc? What overture software program does iCarly usefulness? A question although to you, if i'll:i've a number of recordings of a discrete conference at different locations in response to the audio system. after all if all of them used the microphone there wont honor any points nevertheless, that was not the peapod. that organism said, would there be an optimum software the place i'd upload all the audio information in multi tracks and with a discrete operate would allow me to swallow a detached remaining audio stake where the software program would only annex the clearest pitches of every clamor string? In different words, supply presenter A would articulate in Audio discourse A. Its not that speaker A can be speaking all the time throughout the convention. Would there carry out an existing software program or function the place the software would automatically crop the excessive pitches, the actual talking voices and edit/crop them right into a discrete post? How is mP3 nORMALIZER made? SwiftKit, the present software is completely authorized contained by JaGeX's eyes - although they won't endorse the software program. There was a latest 'deter' next to the chief boards on account of a misunderstandcontained byg between a JaGeX Moderator and players where the JaGeX Moderator badly worded a solve statcontained byg that they didn't endorse the software program, leading players to consider SwiftKit was ilauthorized. Mp3 Volume booster was cleared up at a date and JaGeX acknowledged that the software program adheres to their Code of Cbybore, however that they can not endorse it as a result of it Third-celebration software. No. software could be downloaded from the internet, from other types of storage devices comparable to external exhausting drives, and any number of other methods. What is senseless software? I had over twenty different items of software program that had audio modifying capabilities.yet none of them may carry out the simpletask that I wished to carry out. Ace Your Audio production These awesome Apps Quick angle: like a variety of audio modifying software, should you wash a bit of audio the remaining leave shuffle again so that there arent any gaps. if you wish to take away murmur without shuffling the audio, you could mute or serenity the part by means of murmur. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Comments on “DJ Your next social gathering by These MP3 & Audio Apps” Leave a Reply Gravatar
__label__pos
0.981293
C# Helper http://csharphelper.com/blog Tips, tricks, and example programs for C# programmers. Wed, 22 Feb 2017 05:35:57 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.2 76205677 Convert a Rectangle into a RectangleF and vice versa in C# http://csharphelper.com/blog/2017/02/convert-a-rectangle-into-a-rectanglef-and-vice-versa-in-c/ http://csharphelper.com/blog/2017/02/convert-a-rectangle-into-a-rectanglef-and-vice-versa-in-c/#respond Wed, 22 Feb 2017 05:35:26 +0000 http://csharphelper.com/blog/2012/04/convert-a-rectangle-into-a-rectanglef-and-vice-versa-in-c/ The RectangleF structure has an overloaded assignment operator = that lets you simply set a RectangleF equal to a Rectangle, so converting a Rectangle into a RectangleF is easy. That makes sense because converting from Rectangle to RectangleF is a … Continue reading The post Convert a Rectangle into a RectangleF and vice versa in C# appeared first on C# Helper. ]]> [rectangle] The RectangleF structure has an overloaded assignment operator = that lets you simply set a RectangleF equal to a Rectangle, so converting a Rectangle into a RectangleF is easy. That makes sense because converting from Rectangle to RectangleF is a widening conversion. The integer values that define a Rectangle can be placed within float values without losing any precision. Converting a RectangleF to a Rectangle is only slightly harder. The RectangleF class provides two methods, Round and Truncate, that perform this conversion. This is a narrowing conversion because the float values that define the RectangleF don’t necessarily fit in the Rectangle structure’s integer properties. This example uses the following code to convert a Rectangle into a RectangleF and back, and draw to all three rectangles. private void Form1_Paint(object sender, PaintEventArgs e) { // Make a rectangle. Rectangle rect1 = new Rectangle(20, 20, this.ClientSize.Width - 40, this.ClientSize.Height - 40); // Convert to RectangleF. RectangleF rectf = rect1; // Convert back to Rectangle. Rectangle rect2 = Rectangle.Round(rectf); //Rectangle rect2 = Rectangle.Truncate(rectf); // Draw them. using (Pen the_pen = new Pen(Color.Red, 20)) { e.Graphics.DrawRectangle(the_pen, rect1); the_pen.Color = Color.Lime; the_pen.Width=10; e.Graphics.DrawRectangle(the_pen, rectf.X, rectf.Y, rectf.Width, rectf.Height); the_pen.Color = Color.Blue; the_pen.Width = 1; e.Graphics.DrawRectangle(the_pen, rect2); } } The code first defines a Rectangle. It uses assignment to convert it into a RectangleF and then uses the RectangleF structure’s Round method to convert it back into a Rectangle. The program then draws all three rectangles on top of each other with different line widths and colors so you can see them all. Download Example   Follow me on Twitter   RSS feed   Donate The post Convert a Rectangle into a RectangleF and vice versa in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/convert-a-rectangle-into-a-rectanglef-and-vice-versa-in-c/feed/ 0 515 Make a hangman game in C# http://csharphelper.com/blog/2017/02/make-a-hangman-game-in-c/ http://csharphelper.com/blog/2017/02/make-a-hangman-game-in-c/#respond Mon, 20 Feb 2017 16:40:25 +0000 http://csharphelper.com/blog/2012/04/make-a-hangman-game-in-c/ Special thanks to Jeff Scarterfield for the skeleton drawing used by the program. This example builds a simple hangman game that uses the dictionary created by the example Use LINQ to select words of certain lengths from a file in … Continue reading The post Make a hangman game in C# appeared first on C# Helper. ]]> [hangman] Special thanks to Jeff Scarterfield for the skeleton drawing used by the program. This example builds a simple hangman game that uses the dictionary created by the example Use LINQ to select words of certain lengths from a file in C#. If you don’t know how hangman works, the program shows you blank spaces at the top where the letters in a word go and you have to guess the letters. Each time you make a wrong guess, the program displays another part of the hanged man, or in this example, a skeleton. If you build the entire skeleton, you lose. If you guess all of the letters first, you win. This program isn’t too complicated but it is fairly long. The following code shows how the program initializes. // PictureBoxes holding skeleton pictures. private PictureBox[] PictureBoxes; // The index of the current skeleton picture. private int CurrentPictureIndex = 0; // Words. private string[] Words; // The current word. private string CurrentWord = ""; // Labels to show the current word's letters. private List<Label> LetterLabels = new List<Label>(); // A list holding the letter buttons. private List<Button> KeyboardButtons; // Prepare to play. private void Form1_Load(object sender, EventArgs e) { // Save references to the PictureBoxes in the array. PictureBoxes = new PictureBox[] { picSkeleton0, picSkeleton1, picSkeleton2, picSkeleton3, picSkeleton4, picSkeleton5, picSkeleton6 }; // Load the words. Words = File.ReadAllLines("Words.txt"); // Make button images. MakeButtonImages(); } The program uses the following class-level variables to keep track of what’s happening: • PictureBoxes – An array that holds a series of 7 PictureBox controls that display skeleton images of varying completeness ranging from a blank white picture to the full skeleton. • CurrentPicture – The index of the currently visible PictureBox. When this equals the index of the last PictureBox, the user is seeing the full skeleton and therefore has lost the game. • Words – An array holding the word dictionary. • CurrentWord – The current word that the user is trying to guess. • LetterLabels – The Label controls that display the current word’s letters or the blank spots where the letters will go. • KeyboardButtons – The buttons that act as a keyboard. The form’s Load event handler initializes the PictureBoxes array, uses File.ReadAllLines to load the Words array, and calls the following MakeButtonImages method to prepare the keyboard buttons. // Make the button images. private void MakeButtonImages() { // Prepare the buttons. KeyboardButtons = new List<Button>(); foreach (Control ctl in this.Controls) { if ((ctl is Button) && (!(ctl == btnNewGame))) { // Set the button's name. ctl.Name = "btn" + ctl.Text; // Attach the Click event handler. ctl.Click += btnKey_Click; // Make the button's image. MakeButtonImage(ctl as Button); // Save in the Buttons list for later use. KeyboardButtons.Add(ctl as Button); } } } When I first built the keyboard buttons, the letters didn’t center nicely over the buttons for some reason, possibly because the buttons were so small. To make them look nicer, I decided to make each button display an image holding its letter. The MakeButtonImages method creates the button’s images. The MakeButtonImages method loops through the controls on the form. For every control that is a button except the New Game button, the program sets the button’s name to btn plus its letter. It adds the btnKey_Click event handler to the button’s Click event, and calls the MakeButtonImage method to make the button’s image. Finally it adds the button to the KeyboardButtons list. The following code shows the MakeButtonImage method // Give this button an image thet fits better than its letter. private void MakeButtonImage(Button btn) { Bitmap bm = new Bitmap( btn.ClientSize.Width, btn.ClientSize.Height); using (Graphics gr = Graphics.FromImage(bm)) { gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; using (StringFormat string_format = new StringFormat()) { string_format.Alignment = StringAlignment.Center; string_format.LineAlignment = StringAlignment.Center; gr.DrawString(btn.Text, btn.Font, Brushes.Black, btn.ClientRectangle, string_format); } } btn.Tag = btn.Text; btn.Image = bm; btn.Text = ""; } This method creates a Bitmap to fit the button’s client area. It makes an associated Graphics object and draws the button’s text centered on the Bitmap. It then saves the button’s letter in its Tag property, sets the button’s Image property to the Bitmap, and clears the button’s Text property so it displays only the image. At this point the program is ready to run, although all of the keyboard buttons are initially disabled and the letter labels list is empty. When the user clicks the New Game button, the following code prepares the program for a new hangman game. // Prepare for a new game. private void btnNewGame_Click(object sender, EventArgs e) { // Delete old letter labels. foreach (Label lbl in LetterLabels) { flpLetters.Controls.Remove(lbl); lbl.Dispose(); } // Pick a new word. Random rand = new Random(); CurrentWord = Words[rand.Next(Words.Length)].ToUpper(); // Console.WriteLine(CurrentWord); // Create new letter labels. LetterLabels = new List<Label>(); foreach (char ch in CurrentWord) { Label lbl = new Label(); flpLetters.Controls.Add(lbl); lbl.Tag = ch.ToString(); lbl.Size = btnQ.Size; lbl.TextAlign = ContentAlignment.MiddleCenter; lbl.BackColor = Color.White; lbl.BorderStyle = BorderStyle.Fixed3D; LetterLabels.Add(lbl); } // Hide the won/lost labels. lblWon.Visible = false; lblLost.Visible = false; // Enable the letter buttons. foreach (Button letter_btn in KeyboardButtons) letter_btn.Enabled = true; // Display the first picture. PictureBoxes[CurrentPictureIndex].Visible = false; CurrentPictureIndex = 0; PictureBoxes[CurrentPictureIndex].Visible = true; } The code starts by deleting any letter labels that were created for the previous word. Those labels were contained in a FlowLayoutPanel named flpLetters so the code removes them from that control’s Controls collection and then disposes of each label. The code then picks a random word from the Words list for the next game. It creates a new LetterLabels list and builds a Label for each of the new word’s letters. For each letter, the code: • Creates the label • Adds the label to the FlowLayoutPanel • Sets the label’s Tag property to the word’s corresponding letter • Centers the label’s text • Sets the label’s foreground and background colors • Adds the label to the LetterLabels list Note that the code does not set the new labels’ Text properties. The btnNewGame_Click event handler continues by hiding the labels that indicate that the user won or lost. It then enables the keyboard buttons. Finally the code hides the previously displayed skeleton picture, sets CurrentPictureIndex to 0 (the index of the blank picture), and displays the blank picture. The last piece of the program is the following btnKey_Click event handler, which executes when the user clicks a keyboard button. // A key was clicked. private void btnKey_Click(object sender, EventArgs e) { // Disable this button so the user can't click it again. Button btn = sender as Button; btn.Enabled = false; // See if this letter is in the current word. string ch = btn.Tag.ToString(); if (CurrentWord.Contains(ch)) { // Good guess. Display matching letters. bool has_won = true; foreach (Label lbl in LetterLabels) { // See if this letter matches the current guess. if (lbl.Tag.ToString() == ch) lbl.Text = ch.ToString(); // See if the user has found this letter. if (lbl.Text == "") has_won = false; } // See if the user has won. if (has_won) { lblWon.Visible = true; foreach (Button letter_btn in KeyboardButtons) letter_btn.Enabled = false; } } else { // Bad guess. Show the next picture. PictureBoxes[CurrentPictureIndex].Visible = false; CurrentPictureIndex++; PictureBoxes[CurrentPictureIndex].Visible = true; // See if the user has lost. if (CurrentPictureIndex == PictureBoxes.Length - 1) { lblLost.Visible = true; foreach (Button letter_btn in KeyboardButtons) letter_btn.Enabled = false; foreach (Label lbl in LetterLabels) lbl.Text = lbl.Tag.ToString(); } } } The event handler first disables the clicked button so the user can’t click it again. It then gets the button’s Tag property, converts it to the button’s letter, and determines whether the letter is in the current word. If the letter is in the word, the program loops through the letters labels. If a label corresponds to the letter, the code displays the letter in the label. If any label’s text is still blank, then the user has not guessed all of the letters yet and the game continues. If the user has guessed all of the letters, the program displays the “you won” message and disables all of the keyboard buttons. If the guessed letter is not in the word, the program hides the currently displayed skeleton image, increments CurrentPictureIndex to show the next skeleton image, and displays that image. Then if the current image is the last one, the program displays the “you lost” message, disables all of the keyboard buttons, and makes each label letter display its letter. If you like you can invent a scoring system for the game and save statistics such as high scores and win/loss percentages in the registry or in program settings. Also note that the dictionary that the program uses comes from words that are common to several dictionaries. That means a lot of the words are unusual so the game is fairly hard. You can change the dictionary if you like to make the game easier. For example, if you want to give the game to third graders, you might want to use easier words. It might also be interesting to use a domain-specific dictionary containing words about a particular topic such as programming. Download Example   Follow me on Twitter   RSS feed   Donate The post Make a hangman game in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/make-a-hangman-game-in-c/feed/ 0 517 Use LINQ to select words of certain lengths from a file in C# http://csharphelper.com/blog/2017/02/use-linq-to-select-words-of-certain-lengths-from-a-file-in-c/ http://csharphelper.com/blog/2017/02/use-linq-to-select-words-of-certain-lengths-from-a-file-in-c/#comments Thu, 16 Feb 2017 18:35:41 +0000 http://csharphelper.com/blog/2012/04/use-linq-to-select-specific-words-from-a-file-to-build-a-dictionary-in-c/ This example uses LINQ to read a file, remove unwanted characters, select words of a specified length, and save the result in a new file. Recently I needed a big word list so I searched around for public domain dictionaries. … Continue reading The post Use LINQ to select words of certain lengths from a file in C# appeared first on C# Helper. ]]> [LINQ] This example uses LINQ to read a file, remove unwanted characters, select words of a specified length, and save the result in a new file. Recently I needed a big word list so I searched around for public domain dictionaries. I found one that was close to what I needed in the file 6of12.txt in the 12Dicts package available here. That file has several problems that make it not quite prefect for my use: • It contains words that are too short and too long for my purposes. • It includes non-alphabetic characters at the end of some words to give extra information about them. • Some words contain embedded non-alphabetic characters as in A-bomb and bric-a-brac. The following code shows how the program processes the file. // Select words that have the given minimum length. private void btnSelect_Click(object sender, EventArgs e) { // Remove non-alphabetic characters at the ends of words. Regex end_regex = new Regex("[^a-zA-Z]+$"); string[] all_lines = File.ReadAllLines("6of12.txt"); var end_query = from string word in all_lines select end_regex.Replace(word, ""); // Remove words that still contain non-alphabetic characters. Regex middle_regex = new Regex("[^a-zA-Z]"); var middle_query = from string word in end_query where !middle_regex.IsMatch(word) select word; // Make a query to select lines of the desired length. int min_length = (int)nudMinLength.Value; int max_length = (int)nudMaxLength.Value; var length_query = from string word in middle_query where (word.Length >= min_length) && (word.Length <= max_length) select word; // Write the selected lines into a new file. string[] selected_lines = length_query.ToArray(); File.WriteAllLines("Words.txt", selected_lines); MessageBox.Show("Selected " + selected_lines.Length + " words out of " + all_lines.Length + "."); } The code starts by using a LINQ query to remove non-alphabetic characters from the ends of words. It then uses a second LINQ query to select only words that now contain no non-alphabetic characters. (That eliminates A-bomb and bric-a-brac.) Next a third LINQ query selects words with lengths between those indicated by the user. Finally the code invokes the final query’s ToArray method to convert the results into an array of words. It then uses File.WriteAllLines to write the words into a new file named Words.txt. The code finishes by displaying the number of words in the new and original files. Download Example   Follow me on Twitter   RSS feed   Donate The post Use LINQ to select words of certain lengths from a file in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/use-linq-to-select-words-of-certain-lengths-from-a-file-in-c/feed/ 2 518 Draw a golden spiral in C# http://csharphelper.com/blog/2017/02/draw-a-golden-spiral-in-c/ http://csharphelper.com/blog/2017/02/draw-a-golden-spiral-in-c/#comments Wed, 15 Feb 2017 20:10:29 +0000 http://csharphelper.com/blog/2012/05/draw-a-phi-spiral-or-golden-spiral-in-c/ This example shows how to draw a golden spiral (or phi spiral) in C#. The example Draw a nested series of golden rectangles in C# draws nested rectangles and connects their corners to make a square “spiral.” This example makes … Continue reading The post Draw a golden spiral in C# appeared first on C# Helper. ]]> [example] This example shows how to draw a golden spiral (or phi spiral) in C#. The example Draw a nested series of golden rectangles in C# draws nested rectangles and connects their corners to make a square “spiral.” This example makes a smooth spiral. If you check the Circular Spiral box, the program approximates the phi spiral by using circular arcs. For each square that is removed from a rectangle, it uses the following code to draw an arc connecting two of the square’s corners. if (chkCircularSpiral.Checked) { // Draw a circular arc from the spiral. RectangleF rect; switch (orientation) { case RectOrientations.RemoveLeft: rect = new RectangleF( (float)x, (float)y, (float)(2 * hgt), (float)(2 * hgt)); gr.DrawArc(Pens.Red, rect, 180, 90); break; case RectOrientations.RemoveTop: rect = new RectangleF( (float)(x - wid), (float)y, (float)(2 * wid), (float)(2 * wid)); gr.DrawArc(Pens.Red, rect, -90, 90); break; case RectOrientations.RemoveRight: rect = new RectangleF( (float)(x + wid - 2 * hgt), (float)(y - hgt), (float)(2 * hgt), (float)(2 * hgt)); gr.DrawArc(Pens.Red, rect, 0, 90); break; case RectOrientations.RemoveBottom: rect = new RectangleF( (float)x, (float)(y + hgt - 2 * wid), (float)(2 * wid), (float)(2 * wid)); gr.DrawArc(Pens.Red, rect, 90, 90); break; } } This code simply draws an appropriate arc depending on the position of the square inside its rectangle. If you check the True Spiral box, the program draws a logarithmic spiral with growth factor φ so its radius increases by a factor of the golden ratio φ for every quarter turn. (Actually I wonder if the growth factor shouldn’t be the factor by which it grows in a complete circle.) In any case, the program uses the following code to draw a logarithmic spiral. if (chkTrueSpiral.Checked && points.Count > 1) { // Draw the true spiral. PointF start = points[0]; PointF origin = points[points.Count - 1]; float dx = start.X - origin.X; float dy = start.Y - origin.Y; double radius = Math.Sqrt(dx * dx + dy * dy); double theta = Math.Atan2(dy, dx); const int num_slices = 1000; double dtheta = Math.PI / 2 / num_slices; double factor = 1 - (1 / phi) / num_slices * 0.78; List<PointF> new_points = new List<PointF>(); // Repeat until dist is too small to see. while (radius > 0.1) { PointF new_point = new PointF( (float)(origin.X + radius * Math.Cos(theta)), (float)(origin.Y + radius * Math.Sin(theta))); new_points.Add(new_point); theta += dtheta; radius *= factor; } gr.DrawLines(Pens.Blue, new_points.ToArray()); } This code sets the spiral’s outermost point to be the first point used by the square spiral. It uses the last point found (where the rectangles become vanishingly small) as the spiral’s origin. Next the code calculates the factor by which it will reduce the radius for each change in angle dtheta. With a change in angle of π / 2, the radius should ideally decrease by a factor of 1 – (1 / φ). The program divides both dtheta and this factor by num_slices to make a smooth curve. I honestly don’t know why I need the factor of 0.78 here to make the curve fit the rectangles well. If you leave it out, the curve draws a nice spiral but it lies well inside the rectangles. If you have any ideas, post a comment below. After setting up the parameters, the program enters a loop where it generates a new point on the spiral and multiplies the spiral’s radius by the scale factor to move to the next point. It continues the loop until the radius becomes too small to see and then connects the points. With the mystery factor of 0.78, the spiral does a good job of fitting the rectangles. If you draw both spirals at the same time, you’ll see that the circular approximation is remarkably close to the true spiral. Download the example program to see the rest of the code. Download Example   Follow me on Twitter   RSS feed   Donate The post Draw a golden spiral in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/draw-a-golden-spiral-in-c/feed/ 3 500 Draw a nested series of golden rectangles in C# http://csharphelper.com/blog/2017/02/draw-a-nested-series-of-golden-rectangles-in-c/ http://csharphelper.com/blog/2017/02/draw-a-nested-series-of-golden-rectangles-in-c/#comments Tue, 14 Feb 2017 18:00:38 +0000 http://csharphelper.com/blog/2012/04/draw-a-nested-series-of-golden-rectangles-in-c/ This program draws golden rectangles, rectangles whose side ratio is equal to φ. For information on φ, see Examine the relationship between the Fibonacci sequence and phi in C#. The program first draws a golden rectangle. It then removes the … Continue reading The post Draw a nested series of golden rectangles in C# appeared first on C# Helper. ]]> [golden rectangles] This program draws golden rectangles, rectangles whose side ratio is equal to φ. For information on φ, see Examine the relationship between the Fibonacci sequence and phi in C#. The program first draws a golden rectangle. It then removes the square from one end of the rectangle to produce another golden rectangle. It continues removing the squares at the ends of rectangles to make new golden rectangles until the rectangles are too small to see. The program starts by building a Bitmap and doing some set up such as defining the largest golden rectangle that the program will draw. The most interesting part of the program is the following DrawPhiRectanglesOnGraphics method. // Draw rectangles on a Graphics object. private void DrawPhiRectanglesOnGraphics(Graphics gr, List<PointF> points, float x, float y, float wid, float hgt, RectOrientations orientation) { if ((wid < 1) || (hgt < 1)) return; // Draw this rectangle. gr.DrawRectangle(Pens.Blue, x, y, wid, hgt); // Recursively draw the next rectangle. switch (orientation) { case RectOrientations.RemoveLeft: points.Add(new PointF(x, y + hgt)); x += hgt; wid -= hgt; orientation = RectOrientations.RemoveTop; break; case RectOrientations.RemoveTop: points.Add(new PointF(x, y)); y += wid; hgt -= wid; orientation = RectOrientations.RemoveRight; break; case RectOrientations.RemoveRight: points.Add(new PointF(x + wid, y)); wid -= hgt; orientation = RectOrientations.RemoveBottom; break; case RectOrientations.RemoveBottom: points.Add(new PointF(x + wid, y + hgt)); hgt -= wid; orientation = RectOrientations.RemoveLeft; break; } DrawPhiRectanglesOnGraphics(gr, points, x, y, wid, hgt, orientation); } If the rectangle is smaller than one pixel wide or tall, the method simply exits. Otherwise it draws the rectangle. Next the program checks the rectangle’s orientation. The following code shows the RectOrientation enumeration. // Orientations for the rectangles. private enum RectOrientations { RemoveLeft, RemoveTop, RemoveRight, RemoveBottom } These enumerations determine which part of a golden rectangle to remove. For example, the first rectangle is wider than it is tall. The program removes the square on the rectangle’s left end to create a new smaller rectangle on the right end. That rectangle is taller than it is wide so the program removes the square from its top end. The DrawPhiRectanglesOnGraphics method uses a switch statement to determine which part of the current rectangle it should remove to make the next one. It also updates the orientation parameter so the next call to DrawPhiRectanglesOnGraphics draws the next rectangle correctly. The enumeration defines its values in the order in which the program removes the rectangle ends: left, top, right, bottom. That keeps the new rectangles in the center of the original rectangle. The code in the switch statement also saves an “origin” point for each rectangle in a point list. After calculating the new rectangle’s size, position, and orientation, the DrawPhiRectanglesOnGraphics method calls itself recursively to draw the next golden rectangle. After the original call to DrawPhiRectanglesOnGraphics returns, the calling code connects the saved “origin” points to draw a spiral. (I tried drawing the spiral smoothly but a simple call to DrawCurve doesn’t work. More about this in my next post.) Download Example   Follow me on Twitter   RSS feed   Donate The post Draw a nested series of golden rectangles in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/draw-a-nested-series-of-golden-rectangles-in-c/feed/ 2 519 Examine the relationship between the Fibonacci sequence and phi in C# http://csharphelper.com/blog/2017/02/examine-the-relationship-between-the-fibonacci-sequence-and-phi-in-c/ http://csharphelper.com/blog/2017/02/examine-the-relationship-between-the-fibonacci-sequence-and-phi-in-c/#respond Mon, 13 Feb 2017 23:25:49 +0000 http://csharphelper.com/blog/2012/04/examine-the-relationship-between-the-fibonacci-sequence-and-phi-in-c/ The golden ratio (also called the golden mean, golden section, or divine proportion) is a number that pops up in a surprising number of places in geometry and nature. This number is also called φ (phi, pronounced either “fee” or … Continue reading The post Examine the relationship between the Fibonacci sequence and phi in C# appeared first on C# Helper. ]]> [Fibonacci] The golden ratio (also called the golden mean, golden section, or divine proportion) is a number that pops up in a surprising number of places in geometry and nature. This number is also called φ (phi, pronounced either “fee” or “fie”, but as far as I know not “foe” or “fum”). Consider the rectangles on the right. The ratio of the side lengths in the larger rectangle containing both the green and yellow parts is (A + B) / A. If you remove the green square with side lengths A, you get the smaller yellow rectangle. The ratio of the side lengths in the smaller yellow rectangle is A / B. The golden ratio φ is the value A / B that makes these two ratios the same. In other words, (A + B) / A = A / B. Geometrically it means that if you remove the green square from the larger rectangle, the result is a smaller rectangle with the same aspect ratio as the original rectangle. Because the smaller rectangle has the same aspect ratio, you can repeat the process and remove a B x B square from the smaller rectangle to get an even smaller rectangle that still has the same aspect ratio. You can repeat this process indefinitely to get some interesting results, which I may look at later. Suppose you let A = 1 and solve the equation (A + B) / A = A / B. Plugging in A = 1 gives: (1 + B) / 1 = 1 / B Multiplying both sides by B gives: B + B2 = 1 Subtracting 1 from both sides and rearranging a bit gives: B2 + B - 1 = 0 Now you can plug this into the quadratic formula to get: The value φ (phi) is the ratio of the long side to the short side. In this case, that’s (A + B) / A. Because we assumed A was 1, the preceding equation means: Ignoring the negative distance, φ = (1 + Sqrt(5)) / 2 ≈ 1.618. One surprising place that φ pops up is the Fibonacci sequence. Recall that the Fibonacci sequence is defined by Fib(n) = Fib(n – 1) + Fib(n – 2). Each value is the sum of the two before it so the sequence is 0, 1, 1, 2, 3, 5, … It turns out that if you divide one number in the Fibonacci sequence by the previous number Fib(n) / Fib(n – 1), you get an approximation of φ. This program generates some of the values in the sequence, calculates their approximations for φ, and determines how close they are to the true value. It also graphs the approximations and the true value so you can see how quickly the approximations converge on the true value. When the program starts, it executes the following Form_Load event handler. // The Fibonacci values. private double[] Fibonacci; // Phi. private double Phi; // Make a list of Fibonacci numbers. private void Form1_Load(object sender, EventArgs e) { // Display phi. Phi = (1 + Math.Sqrt(5)) / 2; txtPhi.Text = Phi.ToString("n15"); // Calculate Fibonacci values. Fibonacci = new double[45]; Fibonacci[0] = 0; Fibonacci[1] = 1; for (int n = 2; n < Fibonacci.Length; n++) { Fibonacci[n] = Fibonacci[n - 1] + Fibonacci[n - 2]; } // Display values. for (int n = 0; n < Fibonacci.Length; n++) { ListViewItem item = lvwValues.Items.Add(n.ToString()); item.SubItems.Add(Fibonacci[n].ToString()); if (n > 1) { double ratio = Fibonacci[n] / Fibonacci[n - 1]; item.SubItems.Add(ratio.ToString("n15")); double difference = ratio - Phi; item.SubItems.Add(difference.ToString("e2")); } } lvwValues.AutoResizeColumns( ColumnHeaderAutoResizeStyle.ColumnContent); } The program displays the true value of φ calculated by (1 + Math.Sqrt(5)) / 2. It then calculates 45 Fibonacci numbers. It loops through the numbers calculating the φ approximation and adding the values, approximations, and differences from the true value to a ListView control for display. The PictureBox control’s Paint and Resize event handlers call the following DrawGraph method to draw the graph of the φ approximations. // Draw the graph on a Graphics object. private void DrawGraph(Graphics gr) { gr.SmoothingMode = SmoothingMode.AntiAlias; using (Pen thin_pen = new Pen(Color.Black, 0)) { // Make a trsnaformation matrix to make drawing easier. const float xmin = -0.1f; const float ymin = -0.1f; const float xmax = 9.1f; const float ymax = 2.2f; RectangleF src_rect = new RectangleF( xmin, ymin, xmax - xmin, ymax - ymin); PointF[] pts = { new PointF(0, picGraph.ClientSize.Height), new PointF( picGraph.ClientSize.Width, picGraph.ClientSize.Height), new PointF(0, 0) }; Matrix trans = new Matrix(src_rect, pts); // Draw numbers along the X-axis. List<PointF> x_pt_list = new List<PointF>(); for (int x = (int)xmin; x <= xmax; x++) { x_pt_list.Add(new PointF(x, 0.1f)); } PointF[] x_pt_array = x_pt_list.ToArray(); trans.TransformPoints(x_pt_array); using (StringFormat string_format = new StringFormat()) { string_format.Alignment = StringAlignment.Center; string_format.LineAlignment = StringAlignment.Far; int index = 0; for (int x = (int)xmin; x <= xmax; x++) { gr.DrawString(x.ToString(), this.Font, Brushes.Black, x_pt_array[index], string_format); index++; } } // Draw numbers along the Y-axis. List<PointF> y_pt_list = new List<PointF>(); for (int y = (int)ymin; y <= ymax; y++) { y_pt_list.Add(new PointF(0.2f, y)); } PointF[] y_pt_array = y_pt_list.ToArray(); trans.TransformPoints(y_pt_array); using (StringFormat string_format = new StringFormat()) { string_format.Alignment = StringAlignment.Near; string_format.LineAlignment = StringAlignment.Center; int index = 0; for (int y = (int)ymin; y <= ymax; y++) { gr.DrawString(y.ToString(), this.Font, Brushes.Black, y_pt_array[index], string_format); index++; } } // Transform the Graphics object for drawing. gr.Transform = new Matrix(src_rect, pts); // Draw the axes. gr.DrawLine(thin_pen, xmin, 0, xmax, 0); for (int y = (int)ymin; y <= ymax; y++) { gr.DrawLine(thin_pen, -0.1f, y, 0.1f, y); } gr.DrawLine(thin_pen, 0, ymin, 0, ymax); for (int x = (int)xmin; x <= xmax; x++) { gr.DrawLine(thin_pen, x, -0.1f, x, 0.1f); } // Draw phi. thin_pen.Color = Color.Green; gr.DrawLine(thin_pen, xmin, (float)Phi, xmax, (float)Phi); // Draw the points. List<PointF> fib_points = new List<PointF>(); for (int n = 2; n <= xmax; n++) { float ratio = (float)(Fibonacci[n] / Fibonacci[n - 1]); fib_points.Add(new PointF(n, ratio)); } thin_pen.Color = Color.Red; //gr.DrawLines(thin_pen, fib_points.ToArray()); gr.DrawCurve(thin_pen, fib_points.ToArray()); } } The code sets the Graphics object’s SmoothingMode property to produce a smooth result and then creates a zero-thickness pen that it uses for all drawing. (A pen with thickness 0 is always drawn 1 pixel wide no matter how the drawing is scaled.) Next the code defines a transformation matrix to map the world coordinates -0.1 ≤ X ≤ 9.1, -0.1 ≤ Y ≤ 2.2 to the PictureBox control’s drawing surface. The transformation flips the coordinates over so the code can use a normal mathematical Y coordinate system with Y running from bottom-to-top and the result will be mapped to the PictureBox coordinate system in pixels where Y runs from top-to-bottom. The code saves this transformation in the variable trans. Next the code draws numbers along the X and Y axes. To avoid scaling the text so the font looks weird, the program uses the saved transformation to transform the points representing where the text should be drawn. It then draws the text without any transformation at the transformed locations. The result is normal-looking text drawn where it belongs after the transformation maps it onto the PictureBox. Now the code sets the Graphics object’s transformation so future drawing is mapped from the mathematical world coordinate system to the PictureBox control’s coordinate system. It then draws the axes and a green line showing the calculated value of φ. Finally the program gets to the interesting part. It creates a list of PointF and fills it with points representing the first several φ approximations. It creates one point per X coordinate value. The code then uses the Graphics object’s DrawCurve method to connect the points with a smooth curve. Really the values only exist for integer values of X so the true data could be connected with lines instead of a smooth curve, but I think the curve looks better and does a better job of showing how the approximations quickly zoom in on the correct value. If you run the program and look at the error values displayed in the ListView control, you’ll see that the approximation quickly becomes extremely close to the correct value. For example, the 9th approximation differs from the correct value by roughly 0.001. Download Example   Follow me on Twitter   RSS feed   Donate The post Examine the relationship between the Fibonacci sequence and phi in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/examine-the-relationship-between-the-fibonacci-sequence-and-phi-in-c/feed/ 0 520 Use a TextFieldParser to read fixed-width data in C# http://csharphelper.com/blog/2017/02/use-a-textfieldparser-to-read-fixed-width-data-c/ http://csharphelper.com/blog/2017/02/use-a-textfieldparser-to-read-fixed-width-data-c/#respond Sat, 11 Feb 2017 16:30:31 +0000 http://csharphelper.com/blog/2012/05/use-the-textfieldparser-class-to-easily-read-a-file-containing-fixed-width-data-in-c/ This example uses a TextFieldParser object to load fixed-width data from a file that contains names and addresses. Each field has a fixed width. Some records also have ZIP+4 format ZIP codes (for example, 08109-2120) and the program should discard … Continue reading The post Use a TextFieldParser to read fixed-width data in C# appeared first on C# Helper. ]]> [TextFieldParser] This example uses a TextFieldParser object to load fixed-width data from a file that contains names and addresses. Each field has a fixed width. Some records also have ZIP+4 format ZIP codes (for example, 08109-2120) and the program should discard the +4 part of the data. Finally the data file contains some blank lines in the middle and at the end, and the program should ignore them. The following text shows the file. Barbara Roberts 2044 22nd St San Pablo CA24806 Ken Carson 565 Atlanta South Pkwy Atlanta GA10349 Horatio Crunch 565 Atlanta South Pkwy Atlanta GA70349-5958 Patricia Reichardt 3655 Millbranch Rd Memphis TN18116-4817 Aloysius Snuffleupagus 9252 N 49th St Pennsauken NJ08109-2120 Edgar Mallory 3655 Millbranch Rd Memphis TN38116 Jonas Grumby 2832 Amerson Way Ellenwood GA30294 Roy Hinkley 29426 Christiana Way Laguna Niguel CA92677 The example program uses the following code to read and display the data. // Load the data. private void Form1_Load(object sender, EventArgs e) { // Open a TextFieldParser using these delimiters. using (TextFieldParser parser = FileSystem.OpenTextFieldParser("Names.txt")) { // Set the field widths. parser.TextFieldType = FieldType.FixedWidth; parser.FieldWidths = new int[] { 20, 20, 30, 20, 2, 5 }; // Process the file's lines. while (!parser.EndOfData) { try { string[] fields = parser.ReadFields(); ListViewItem item = lvwPeople.Items.Add(fields[0]); for (int i = 1; i <= 5; i++) { item.SubItems.Add(fields[i]); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } lvwPeople.AutoResizeColumns( ColumnHeaderAutoResizeStyle.HeaderSize); } The code starts by creating a TextFieldParser. It sets the parser’s TextFieldType property to FixedWidth and its FieldWidths property to an array holding the fields’ widths in characters. Note that the TextFieldParser class and the FileSystem class used here are in the Microsoft.VisualBasic.FileIO namespace. The program includes the following using directive to make using the namespace easier. I also added a reference to the Microsoft.VisualBasic library at design time. // Add a reference to Microsoft.VisualBasic. using Microsoft.VisualBasic.FileIO; After creating the parser, the program loops while the parser’s EndOfData property returns false. The EndOfData property automatically changes to true after the parser reads the last record in the data file even if the file ends with some blank lines, so the parser won’t get confused. As long as EndOfData is false, the program calls the parser’s ReadFields method to read the next record’s fields into an array of strings. The program must then interpret the fields appropriately. In this example the program simply displays the first 6 fields in a ListView control, the first one as a ListView item and the others as sub-items. See also Use a TextFieldParser to read delimited data in C#. Download Example   Follow me on Twitter   RSS feed   Donate The post Use a TextFieldParser to read fixed-width data in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/use-a-textfieldparser-to-read-fixed-width-data-c/feed/ 0 509 Use a TextFieldParser to read delimited data in C# http://csharphelper.com/blog/2017/02/use-a-textfieldparser-to-read-delimited-data-in-c/ http://csharphelper.com/blog/2017/02/use-a-textfieldparser-to-read-delimited-data-in-c/#comments Fri, 10 Feb 2017 22:50:20 +0000 http://csharphelper.com/blog/2012/04/use-the-textfieldparser-class-to-easily-read-a-file-containing-delimited-data-in-c/ This example uses a TextFieldParser object to parse a data file that contains name and address data. The data contains fields delimited by commas and semi-colons. Some records also have ZIP+4 format ZIP codes (for example, 08109-2120) and the program … Continue reading The post Use a TextFieldParser to read delimited data in C# appeared first on C# Helper. ]]> [TextFieldParser] This example uses a TextFieldParser object to parse a data file that contains name and address data. The data contains fields delimited by commas and semi-colons. Some records also have ZIP+4 format ZIP codes (for example, 08109-2120) and the program should discard the +4 part of the data. Finally the data file contains some blank lines in the middle and at the end. The program should ignore them. The following text shows the test data file. Barbara,Roberts;2044 22nd St;San Pablo;CA;24806 Ken,Carson;565 Atlanta South Pkwy;Atlanta;GA;10349 Horatio,Crunch;565 Atlanta South Pkwy;Atlanta;GA;70349-5958 Patricia,Reichardt;3655 Millbranch Rd;Memphis;TN;18116-4817 Aloysius,Snuffleupagus;9252 N 49th St;Pennsauken;NJ;08109-2120 Edgar,Mallory;3655 Millbranch Rd;Memphis;TN;38116 Jonas,Grumby;2832 Amerson Way;Ellenwood;GA;30294 Roy,Hinkley;29426 Christiana Way;Laguna Niguel;CA;92677 The example program uses the following code to read and display the data. // Open a TextFieldParser using these delimiters. string[] delimiters = { ";", ",", "-" }; using (TextFieldParser parser = FileSystem.OpenTextFieldParser("Names.txt", delimiters)) { // Process the file's lines. while (!parser.EndOfData) { try { string[] fields = parser.ReadFields(); ListViewItem item = lvwPeople.Items.Add(fields[0]); for (int i = 1; i <= 5; i++) { item.SubItems.Add(fields[i]); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } The code starts by creating an array holding the delimiters that the file uses. Including – in the list allows the program to treat the +4 part of the ZIP code (if it is present) as a separate field. The program then creates a TextFieldParser object. It uses the FileSystem.OpenTextFieldParser factory method to create a new instance of the class. It passes that method the array of delimiters so the parser knows what characters to use as delimiters. Notice that the code uses a using statement so the parser’s Dispose method is automatically called when the object is no longer needed. Note also that the TextFieldParser class and the FileSystem class are contained in the Microsoft.VisualBasic.FileIO namespace. The program includes the following using directive to make using the namespace easier. I also had to add a reference to the Microsoft.VisualBasic library at design time. // Add a reference to Microsoft.VisualBasic. using Microsoft.VisualBasic.FileIO; After creating the parser, the program loops while the parser’s EndOfData property returns false. The EndOfData property automatically changes to true after the parser reads the last record in the data file even if the file ends with some blank lines so the parser won’t get confused. As long as EndOfData is false, the program calls the parser’s ReadFields method to read the next record’s fields into an array of strings. The program must then interpret the fields appropriately. In this example the program simply displays the first 6 fields in a ListView control, one as a ListView item and the others as sub-items. This is nothing that you couldn’t do yourself by using File.ReadAllLines and String.Split, but the TextFieldParser is somewhat simpler. Download Example   Follow me on Twitter   RSS feed   Donate The post Use a TextFieldParser to read delimited data in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/use-a-textfieldparser-to-read-delimited-data-in-c/feed/ 2 521 Suspend or hibernate the system in C# http://csharphelper.com/blog/2017/02/suspend-or-hibernate-the-system-in-c/ http://csharphelper.com/blog/2017/02/suspend-or-hibernate-the-system-in-c/#respond Wed, 08 Feb 2017 15:35:08 +0000 http://csharphelper.com/blog/2012/04/make-the-computer-suspend-or-hibernate-in-c/ The Application.SetSuspendState method lets an application make the system suspend or hibernate. A suspended system enters a low power mode. A hibernating system saves its memory contents to disk and then enters low power mode. Because it doesn’t need to … Continue reading The post Suspend or hibernate the system in C# appeared first on C# Helper. ]]> [hibernate] The Application.SetSuspendState method lets an application make the system suspend or hibernate. A suspended system enters a low power mode. A hibernating system saves its memory contents to disk and then enters low power mode. Because it doesn’t need to restore the saved memory, a suspended system can resume more quickly than a hibernating system. However, if the computer loses power while suspended, running programs are not properly restored. The following code lets the program suspend or hibernate the system. // Suspend. private void btnSuspend_Click(object sender, EventArgs e) { Application.SetSuspendState(PowerState.Suspend, false, false); } // Hibernate. private void btnHibernate_Click(object sender, EventArgs e) { Application.SetSuspendState(PowerState.Hibernate, false, false); } For more information about the SetSuspendState method, see Application.SetSuspendState Method. Download Example   Follow me on Twitter   RSS feed   Donate The post Suspend or hibernate the system in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/suspend-or-hibernate-the-system-in-c/feed/ 0 522 Make light pixels transparent in an image in C# http://csharphelper.com/blog/2017/02/make-light-pixels-transparent-image-c/ http://csharphelper.com/blog/2017/02/make-light-pixels-transparent-image-c/#respond Tue, 07 Feb 2017 17:48:07 +0000 http://csharphelper.com/blog/?p=4182 Recently I had an image and I wanted to make all of the light pixels transparent. Ideally I could simply make the white pixels transparent, but the image was scanned so few of the pixels were pure white. What I … Continue reading The post Make light pixels transparent in an image in C# appeared first on C# Helper. ]]> [example] Recently I had an image and I wanted to make all of the light pixels transparent. Ideally I could simply make the white pixels transparent, but the image was scanned so few of the pixels were pure white. What I really needed to do was make pixels that were mostly white transparent. This example lets you load an image. When you adjust the scroll bar, it finds the pixels with red, green, and blue color components that are all greater than the cutoff value and it makes them transparent. The following ShowImage method creates and displays the adjusted image. // Make an image setting pixels brighter // than the cutoff value to magenta. private void ShowImage() { if (OriginalImage == null) return; // Get the cutoff. int cutoff = scrBrightness.Value; // Prepare the ImageAttributes. Color low_color = Color.FromArgb(cutoff, cutoff, cutoff); Color high_color = Color.FromArgb(255, 255, 255); ImageAttributes image_attr = new ImageAttributes(); image_attr.SetColorKey(low_color, high_color); // Make the result image. int wid = OriginalImage.Width; int hgt = OriginalImage.Height; Bitmap bm = new Bitmap(wid, hgt); // Process the image. using (Graphics gr = Graphics.FromImage(bm)) { // Fill with magenta. gr.Clear(Color.Magenta); // Copy the original image onto the result // image while using the ImageAttributes. Rectangle dest_rect = new Rectangle(0, 0, wid, hgt); gr.DrawImage(OriginalImage, dest_rect, 0, 0, wid, hgt, GraphicsUnit.Pixel, image_attr); } // Display the image. picResult.Image = bm; } If no image has yet been loaded, the method simply returns. If it continues, the gets the cutoff value from the scroll bar scrBrightness. Next the method creates two colors low_color and high_color to represent the lowest and highest color values that it will convert to transparent. It creates a new ImageAttributes object and calls its SetColorKey method to give it the low and high color values. Nxet the program creates a Bitmap with the same size as the original image. It creates an associated Graphics object and clears it with the color magenta. At this point the new image is completely magenta. Next the code uses the Graphics object’s DrawImage method to draw the original image on top of the magenta background. The final parameter to DrawImage is the ImageAttributes object. If a pixel’s red, green, and blue color components are all between the corresponding values of the low and high colors saved in the ImageAttributes object’s color key, the result pixel is transparent. Because the bitmap’s background is magenta, the magenta shows through at these pixels. (I use magenta instead of allowing those pixels to be transparent so you can see them easily.) The method finishes by displaying the resulting bitmap. When you use the File menu’s Save command, the program copies the result bitmap, converts the magenta pixels to transparent, and saves the result. Note that the PNG file format supports transparency but most other formats such as BMP and JPG do not. For that reason, be sure to save the file in PNG format. Note also that there are other ways you can set the pixel transparency. For example, you can use the Bitmap object’s GetPixel and SetPixel methods or you can use the Bitmap32 class that I’ve used in other posts. The ImageAttributes object is much faster. For the best results if you will later display the image on a light-colored background, adjust the cutoff value so a few of the pixels near the dark shapes are not transparent. You can see them in the picture above as the light-colored pixels between the dark shapes and the magenta background. Those pixels will provide a smooth edge between the shapes and the background. Download the example to see additional details such as how the program loads and saves files. Download Example   Follow me on Twitter   RSS feed   Donate The post Make light pixels transparent in an image in C# appeared first on C# Helper. ]]> http://csharphelper.com/blog/2017/02/make-light-pixels-transparent-image-c/feed/ 0 4182
__label__pos
0.595688
Implementing an identity provider and relying party with Zermatt and ASP.NET MVC Zermatt is the framework recently released by Microsoft to develop claim-aware applications. You can find some announcements here and here. This framework supports the WS-Federation active and passive profiles. This last one was initially designed with an unique purpose in mind, allow the integration of "dumb clients" into the identity metasystem. As "dumb clients", I am talking about clients like web browsers that do not have the ability to handle cryptographic material. All the magic is done through some consecutive Http redirects, and today we will see how develop an identity provider and a relying party web (with ASP.NET MVC) that are involved in the whole process. The identity provider is based on the quickstart that is automatically generated in Visual Studio when you create a new MVC web application. This quickstart uses FormsAuthentication to authenticate the application users and also provides an Account controller (that internally uses ASP.NET Membership) to manage all those users. In order to integrate Zermatt in this application, I added a new controller STSController that knows to process messages for getting issue tokens with the user's claims. For the relying party, Zermatt provides some web controls to authenticate the user against the identity provider using the passive profile. Unfortunately, for the simple fact that ASP.NET MVC does not support controls with view state, we can not use them here. As workaround, I created a couple of extensions methods that generate the Urls for sending the corresponding messages to the identity provider (Login and Logout). public static class LoginUrlExtensions {    public static string LoginUrl(this UrlHelper helper, string actionName, string controllerName, string stsUrl)    {        string host = helper.ViewContext.HttpContext.Request.Url.Authority;        string schema = helper.ViewContext.HttpContext.Request.Url.Scheme;          string realm = string.Format("{0}://{1}", schema, host);        string reply = helper.Action(actionName, controllerName).Substring(1);          return string.Format("{0}?wa=wsignin1.0&wtrealm={1}&wreply={2}&wctx=rm=0&id=FederatedPassiveSignIn1&wct={3}",           stsUrl, realm, reply, XmlConvert.ToString(DateTime.Now));    }      public static string LogoutUrl(this UrlHelper helper, string actionName, string controllerName, string stsUrl)    {        string host = helper.ViewContext.HttpContext.Request.Url.Authority;        string schema = helper.ViewContext.HttpContext.Request.Url.Scheme;          string realm = string.Format("{0}://{1}", schema, host);        string reply = string.Format("{0}{1}", realm, helper.Action(actionName, controllerName));          return string.Format("{0}?wa=wsignout1.0&wreply={1}", stsUrl, reply);    } } The "actionName" and "controllerName" are just used to generate the reply address where the user must be redirect after being authenticated in the identity provider. These extension methods can be used in the view as follow, <a href="<%=Url.LoginUrl("Login", "Home", "localhost://STS")%>">Login</a> We also need a method in the relying party to parse the RRST message and generate a cookie with the user credentials and claims.   public interface IFederatedAuthentication {    IClaimsPrincipal Authenticate(); }   public class FederatedAuthentication : IFederatedAuthentication {      private string logoutUrl;        public FederatedAuthentication(string logoutUrl)      {          this.logoutUrl = logoutUrl;      }        public IClaimsPrincipal Authenticate()      {          string securityTokenXml = FederatedAuthenticationModule.Current.GetXmlTokenFromPassiveSignInResponse(System.Web.HttpContext.Current.Request, null);            FederatedAuthenticationModule current = FederatedAuthenticationModule.Current;            SecurityToken token = null;          IClaimsPrincipal authContext = current.AuthenticateUser(securityTokenXml, out token);            TicketGenerationContext context = new TicketGenerationContext(authContext, false, logoutUrl, typeof(SignInControl).Name);          current.IssueTicket(context);            return authContext;      } }   As you can see in the code above, the Zermatt module (FederatedAuthenticationModule) that parses the response message is tied to the Request object, something that we do not have direct access from a MVC controller (Well, it is bad practice if we want to test our code). That's the reason I decided to put all that code in a pluggin that can be injected later in the controller. The complete solution is available to download from this location. Any feedback would be great!!. Enjoy!!. No Comments
__label__pos
0.810319
Boost powerline adapter problems • 25 January 2021 • 7 replies • 228 views This topic has been closed for further comments. You can use the search bar to find a similar topic, or create a new one by clicking Create Topic at the top of the page. 7 replies Is there a Sonos device wired to the remote powerline adapter? Ratty - no Sonos devices wired to powerline adapters. I started with that setup (router → powerline main → powerline adapter in another room → Sonos product (via ethernet port)) but was experiencing dropouts so bought the Boost to aid the wifi direct (SonosNet) option.  Confusingly, if I remove the Boost entirely, and setup my Sonos via plugging any of the devices (say, the Play 3) directly into the router via ethernet, the wifi mesh comes up and everything works. Occasionally then the furtherest device in the house goes offline (loses wifi signal) - hence the need for the Boost. However, on an operating setup, if I then plug the Boost into the router, the whole network goes offline, until I disable TPLink (or Sonos) and allow the other to recover. The TPLink Powerlines in theory don’t have IP addresses (no option to reset them) so I’ve ruled out an IP address clash. Its got me stumped.    Anyone have any ideas? I’m afraid not - not sure that it’s helpful, but I’m using AV600 Powerline adaptors feeding a Play 5 and also a ZP90 and they work fine - I don’t use a Boost, though Badge +20 @Scropolous  The TP link powerline adapters, they aren’t by any chance the ones with wifi? @Scropolous The TP link powerline adapters, they aren’t by any chance the ones with wifi? Good point - mine aren’t…. @Scropolous The TP link powerline adapters, they aren’t by any chance the ones with wifi? @ Belly - they are indeed WiFi enabled (AV600). I’ve changed WiFi channel on router and the Av600 clone it (for a continuous extended signal) with Sonos on a separate frequency so don’t think they clash. System is currently running with TPLinks for main network mesh and Sonos on its own WiFi mesh without issue (minus Boost). Adding the Boost in results in router losing connection (eg request timeouts on google ping) until either Boost or TPlink disconnected. Badge +20 In the Sonos App, settings… System… About My System. All Sonos devices should be labelled WM0 if you have a Boost or any Sonos device hardwired.
__label__pos
0.809151
1 Пытаюсь сделать фильтрацию на yii2. Есть поле формы в ней 3 input(type="radio"), каждый инпут должен искать товары с ценой в данном диапазоне. Код контроллера где выполняется поиск: public function actionFilter() { $filter = trim(Yii::$app->request->get('filter')); $this->setMeta('MAC-SHOPPER | ' . $filter); if (!$filter) { return $this->render('filter'); } /* if ($filter <= 15) { $query = Product::find()->where(['<=', 'price', 15]); }*/ $model = new Product(); if($Button1) { $query = Product::find()->where(['between', 'price', "0", "50" ])->all(); } //Создаем объект класса Pagination //Передаем тотал каунт - общее количество записей, которыe мы вытащим $pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => 2, 'forcePageParam' => false, 'pageSizeParam' => false]); //Выполняем сам запрос //offset - с какой записи начинать //limit - количество записей $products = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('filter', compact('products', 'pages', 'filter', 'model')); } Модель товара: <?php namespace app\models; use yii\db\ActiveRecord; //класс для таблицы категории class Product extends ActiveRecord { public $Button1; public $Button2; public $Button3; public $radioButtonList; //Поведение для картинок public function behaviors() { return [ 'image' => [ 'class' => 'rico\yii2images\behaviors\ImageBehave', ] ]; } public static function tableName() { return 'product'; } public function getCategory() { //Связь таблиц, один продукт может иметь одну категорию (hasOne()) return $this->hasOne(Category::className(), ['id' => 'category_id']); } } ?> Сама форма: <?php $form = ActiveForm::begin([ 'id' => 'task-form', 'action' => \yii\helpers\Url::to(['category/filter']), ] )?> <?= $form->field($model, 'radioButtonList') ->radioList([ 'Button1' => 'от 0-1500', 'Button2' => 'от 3000-5000', 'Button3' => 'от 5000-20000' ],[ 'id' => 'radio_button', ]); ?> <?= Html::submitButton('Найти', ['class' => 'btn btn-success']);?> <?php $form = ActiveForm::end() ?> Как мне поместить в свойства $Button1, $Button2, $Button3 price из таблицы товаров, чтобы при клике на определенный инпут он выводил товары как сделано в условии контроллера(то есть по диапазону цены) 1 • что это вообще за переменные? Зачем вы их создали? У вас есть поле radioButtonList вы пытались заглянуть в него после отправки формы? – Bookin 15 сен 2017 в 20:36 1 ответ 1 0 Значит, идем в документацию, видим: The data item used to generate the radio buttons. The array values are the labels, while the array keys are the corresponding radio values. Значит, radioList первым параметром, ожидает от вас, массив где ключи это ЗНАЧЕНИЯ инпута, а значения массива - это labels (этикетка/описание). Собственно, если вы загляните в html, что выходит из вашего кода: $form->field($model, 'radioButtonList') ->radioList([ 'Button1' => 'от 0-1500', 'Button2' => 'от 3000-5000', 'Button3' => 'от 5000-20000' ]); То увидите примерно: <label>от 0-1500</label> <input type="radio" value="Button1" name="radioButtonList"/> <label>от 3000-5000</label> <input type="radio" value="Button2" name="radioButtonList"/> <label>от 5000-20000</label> <input type="radio" value="Button3" name="radioButtonList"/> Что будет если запостить такую форму? Ну к примеру постом? Что получите? Вы получите в переменой $_POST по ключу radioButtonList значение Button1, Button2 или Button3. И как же нам получить значение? Из массива на прямую - $_POST['radioButtonList'] Через метод фреймворка - Yii::$app->request->post('radioButtonList') Загрузить в модель - $model = new Product(); if($model->load(Yii::$app->request->post())){ ... $model->radioButtonList; } Пока, ваш контроллер это сплошной набор строк кода, который даже связать в голове не выходит, даже описывать не хочу. Просто укажу вам, что по умолчанию, ваша форма будет слать POST запрос. Причина ваших проблем (мне кажется, что та же причина, почему вам не хотят помогать тут) - вам стоит изучить документацию, и повторить примеры которые в ней. Это вообще как минимум. (хотя бы - ссылка). Ваш ответ By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy. Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.
__label__pos
0.529772
9 $\begingroup$ Working my way through Robby Villegas's lovely notes on withholding evaluation, I almost got Polish Notation on my first try. Here is my final solution, which seems to work well enough: ClearAll[lispify]; SetAttributes[lispify, HoldAll]; lispify[h_[args___]] := Prepend[ lispify /@ Unevaluated @ {args}, lispify[h]]; lispify[s_ /; AtomQ[s]] := s; lispify[Unevaluated[2^4 * 3^2]] produces {Times, {Power, 2, 4}, {Power, 3, 2}} My first try had only one difference, namely lispify /@ Unevaluated /@ {args} and sent me down a frustrating rabbit hole until I stumbled on the corrected one above. Would someone be so kind as to explain the details of both the correct and incorrect solution? EDIT: As a minor bonus, this enables a nice way to visualize unevaluated expression trees: ClearAll[stringulateLisp]; stringulateLisp[l_List] := stringulateLisp /@ l; stringulateLisp[e_] := ToString[e]; ClearAll[stringTree]; stringTree[l_List] := First[l][Sequence @@ stringTree /@ Rest[l]]; stringTree[e_] := e; ClearAll[treeForm]; treeForm = TreeForm@*stringTree@*stringulateLisp@*lispify; treeForm[Unevaluated[2^4 + 3^2]] Mathematica graphics $\endgroup$ 8 $\begingroup$ You must remember that Unevaluated only "works" when it is the explicit head of an expression. In the non-working format the structure looks like: TreeForm @ HoldForm[lispify /@ Unevaluated /@ {arg1, arg2}] enter image description here Note that Unevaluated does not surround arg1 and arg2 therefore they evaluate prematurely. Now compare the working structure: TreeForm @ HoldForm[lispify /@ Unevaluated @ {arg1, arg2}] enter image description here Here Unevaluated does surround arg1 and arg2 and evaluation is prevented. See also: By the way you can show an unevaluated TreeForm by using an additional Unevaluated to compensate for an apparent evaluation leak. treeForm = Function[expr, TreeForm @ Unevaluated @ Unevaluated @ expr, HoldFirst] Test: 2^4*3^2 // treeForm enter image description here Also possibly of interest: Converting expressions to "edges" for use in TreePlot, Graph | improve this answer | | $\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.932222
精华内容 下载资源 问答 • Verilog实现ALU的代码 2020-12-19 12:45:01 Verilog实现ALU的代码 • Verilog实现ALU.zip 2019-10-22 23:50:22 使用Verilog语言实现一个四位的ALU运算单元(包括设计文件和约束文件) • 实验目的 一、 掌握算术逻辑单元 (ALU) 的功能。 二、 掌握数据通路和控制器的设计方法。 三、 掌握组合电路和时序电路,以及参数化和结构化...三、 完成6位ALU的下载测试,并查看RTL电路图,以及实现电路资源和时间性 实验目的 一、 掌握算术逻辑单元 (ALU) 的功能。 二、 掌握数据通路和控制器的设计方法。 三、 掌握组合电路和时序电路,以及参数化和结构化的Verilog描述方法。 四、 了解查看电路性能和资源使用情况。 五、 利用ALU设计应用器件。 实验环境 Vivado 2019.2 on ubantu20.04 实验步骤 一、 完成ALU模块的逻辑设计和仿真 二、 查看32位ALU的RTL和综合电路图,以及综合电路资源和时间性能报告 三、 完成6位ALU的下载测试,并查看RTL电路图,以及实现电路资源和时间性能报告 四、 完成FLS的逻辑设计、仿真和下载测试 工程文件源代码 https://github.com/windwangustc/USTC 实验过程 一、 ALU模块的逻辑设计和仿真 在这里插入图片描述 根据上图的输入输出逻辑真值表,可以很容易的设计出ALU功能模块,代码如下: module alu #(parameter WIDTH=32) ( input clk, input [WIDTH-1:0] a,b, input [2:0]f, output reg [WIDTH-1:0] y, output reg z ); localparam ADD=0, SUB=1, AND=2, OR=3, XOR=4; always @(*) begin case(f) ADD: y = a+b; SUB: y = a-b; AND: y = a&b; OR: y = a|b; XOR: y = a^b; default: begin y = 0 ; z = 1; end endcase if(y) z=0; else z=1; end endmodule 以4位ALU为例进行仿真的结果如下,可以看到加减与或的逻辑结果和时序都正确,Y=0时Z输出1: 在这里插入图片描述 32位ALU的RTL: 在这里插入图片描述 二、 完成6位ALU的下载测试,并查看RTL电路图 在这里插入图片描述 6位ALU的逻辑电路图已经给出了,在原有的ALU上加上寄存器和译码器即可完成电路设计,同时有了寄存器就可以分析时间性能了,代码如下图所示。其中寄存器FABZY都是由module register实例化后得来,之后将这些寄存器同实例化后的ALU和Decoder连线即可。 module alu_6 ( input en,clk, input [7:0] sw, output z, output [5:0] y ); wire ef,ea,eb; wire [5:0] x; assign x[5:0]= sw[5:0]; wire [5:0] a,b; wire [2:0] f; wire [5:0] y_in; wire z_in; decoder_2to4 d1(.en(en),.sel(sw[7:6]),.ef(ef),.ea(ea),.eb(eb)); register #(3,0) F(.clk(clk),.rst(0),.en(ef),.d(x[2:0]),.q(f[2:0])); register #(6,0) A(.clk(clk),.rst(0),.en(ea),.d(x[5:0]),.q(a[5:0])); register #(6,0) B(.clk(clk),.rst(0),.en(eb),.d(x[5:0]),.q(b[5:0])); alu #(6) alu6 (.a(a),.b(b),.f(f),.y(y_in),.z(z_in)); register #(6,0) Y(.clk(clk),.rst(0),.en(1),.d(y_in[5:0]),.q(y[5:0])); register #(1,0) Z(.clk(clk),.rst(0),.en(1),.d(z_in),.q(z)); endmodule RTL图如下图所示,和上面给的电路图是一致的: 在这里插入图片描述 三、 完成FLS的逻辑设计、仿真和下载测试 在这里插入图片描述 根据上面的功能描述和状态转移表,可以设计出大致的数据通路,这里还需要几个选择器来选择初始状态下输入输出f1=d,f2=d,下图未画出: 在这里插入图片描述 FLS模块的代码如下,其中edge_detect是取边沿模块,目的是无论button按下持续多少个周期,都只产生一个周期的使能信号,register_2_signal是针对fn-1和fn-2的输入输出寄存器。在最后一个always块中,实现了状态机。 module FLS ( input clk, rst, en, input [6:0] d, output [6:0] f ); wire [6:0] fn_1,fn_2; reg [6:0] Fn_1,Fn_2; reg [6:0] fn_tmp; wire [6:0] fn; wire pos_edge; //generate en edge signal edge_detect Edge_input(.clk(clk),.en(en),.pos_edge(pos_edge)); //register for fn-2 and fn-1 register_2_signal #(7) RegforFeedback ( .clk(clk),.en(pos_edge),.rst(rst), .Fn_1(Fn_1),.Fn_2(Fn_2),.fn_1(fn_1),.fn_2(fn_2) ); //calculate with 7-bit ALU alu #(7) alu_7(.a(fn_1),.b(fn_2),.f(3'b000),.y(fn)); always@(*) begin if(fn_2==0) begin Fn_2 = d; Fn_1 = 0; fn_tmp = d; //original fib start with 0 1 1.... //Fn_2 = 7'b0000001; end else if(fn_1==0) begin Fn_2 = fn_2; Fn_1= d; fn_tmp= d; //original fib start with 0 1 1.... //Fn_1 = 7'b0000001; end else begin Fn_1 = fn; Fn_2 = fn_1; fn_tmp = fn; end end //output f register #(7,0) reg_f(.clk(clk),.rst(rst),.en(pos_edge),.d(fn_tmp),.q(f)); endmodule RTL电路如下,可以看到和逻辑设计中的数据通路是基本一致的: 在这里插入图片描述 FLS仿真结果如下,pos_edge是en取边沿后的触发信号,可以看到f前两次f1=d,f2=d,之后的f时序符合斐波那契序列,正确: 在这里插入图片描述 展开全文 • 算术逻辑单元(arithmetic and logic unit) 是能实现多组算术运算和逻辑运算的组合逻辑电路,简称ALU。 module ALU(A, B, Cin, Sum, Cout, Operate, Mode); input [3:0] A, B; // two operands of ALU input Cin... 算术逻辑单元(arithmetic and logic unit) 是能实现多组算术运算和逻辑运算的组合逻辑电路,简称ALU。 module ALU(A, B, Cin, Sum, Cout, Operate, Mode); input [3:0] A, B; // two operands of ALU input Cin; //carry in at the LSB input [3:0] Operate; //determine f(.) of sum = f(a, b) input Mode; //arithmetic(mode = 1'b1) or logic operation(mode = 1'b0) output [3:0] Sum; //result of ALU output Cout; //carry produced by ALU operation // carry generation bits and propogation bits. wire [3:0] G, P; // carry bits; reg [2:0] C; reg Cout; // function for carry generation: function gen; input A, B; input [1:0] Oper; begin case(Oper) 2'b00: gen = A; 2'b01: gen = A & B; 2'b10: gen = A & (~B); 2'b11: gen = 1'b0; endcase end endfunction // function for carry propergation: function prop; input A, B; input [1:0] Oper; begin case(Oper) 2'b00: prop = 1; 2'b01: prop = A | (~B); 2'b10: prop = A | B; 2'b11: prop = A; endcase end endfunction // producing carry generation bits; assign G[0] = gen(A[0], B[0], Operate[1:0]); assign G[1] = gen(A[1], B[1], Operate[1:0]); assign G[2] = gen(A[2], B[2], Operate[1:0]); assign G[3] = gen(A[3], B[3], Operate[1:0]); // producing carry propogation bits; assign P[0] = prop(A[0], B[0], Operate[3:2]); assign P[1] = prop(A[1], B[1], Operate[3:2]); assign P[2] = prop(A[2], B[2], Operate[3:2]); assign P[3] = prop(A[3], B[3], Operate[3:2]); // producing carry bits with carry-look-ahead; always @(G or P or Cin, Mode) begin if (Mode) begin C[0] = G[0] | P[0] & Cin; C[1] = G[1] | P[1] & G[0] | P[1] & P[0] & Cin; C[2] = G[2] | P[2] & G[1] | P[2] & P[1] & G[0] | P[2] & P[1] & P[0] & Cin; Cout = G[3] | P[3] & G[2] | P[3] & P[2] & G[1] | P[3] & P[2] & P[1] & G[0] | P[3] & P[2] & P[1] & P[0] & Cin; end else begin C[0] = 1'b0; C[1] = 1'b0; C[2] = 1'b0; Cout = 1'b0; end end // calculate the operation results; assign Sum[0] = (~G[0] & P[0]) ^ Cin; assign Sum[1] = (~G[1] & P[1]) ^ C[0]; assign Sum[2] = (~G[2] & P[2]) ^ C[1]; assign Sum[3] = (~G[3] & P[3]) ^ C[2]; endmodule module ALU(A, B, Cin, Sum, Cout, Operate, Mode); input [3:0] A, B; //输入信号:两个四位的操作对象A、B input Cin; //输入进位信号 input [3:0] Operate; //输入信号,决定输出sum的操作 input Mode; //算数操作(mode = 1'b1) 或者 逻辑操作(mode = 1'b0) output [3:0] Sum; //输出ALU计算结果 output Cout; //输出ALU操作产生的进位信号 wire [3:0] G, P; //进位生成位和增长位 reg [2:0] C; reg Cout; function gen; //进位信号生成函数 input A, B; //函数输入信号A、B input [1:0] Oper; //函数输入操作信号Oper begin case(Oper) 2'b00: gen = A; //生成A信号 2'b01: gen = A & B; //生成A和B相与信号 2'b10: gen = A & (~B); //生成A和~B相与信号 2'b11: gen = 1'b0; //生成低电平信号 endcase end endfunction function prop; //进位信号增长函数 input A, B; //函数输入信号A、B input [1:0] Oper; //函数输入操作信号Oper begin case(Oper) 2'b00: prop = 1; //返回高电平信号 2'b01: prop = A | (~B); //返回A和~B相或信号 2'b10: prop = A | B; //返回A和B相或信号 2'b11: prop = A; //返回A信号 endcase end endfunction //产生进位生成位信号 assign G[0] = gen(A[0], B[0], Operate[1:0]); assign G[1] = gen(A[1], B[1], Operate[1:0]); assign G[2] = gen(A[2], B[2], Operate[1:0]); assign G[3] = gen(A[3], B[3], Operate[1:0]); //产生进位增长位信号 assign P[0] = prop(A[0], B[0], Operate[3:2]); assign P[1] = prop(A[1], B[1], Operate[3:2]); assign P[2] = prop(A[2], B[2], Operate[3:2]); assign P[3] = prop(A[3], B[3], Operate[3:2]); //产生带进位提前的进位 always @(G or P or Cin, Mode) begin if (Mode) begin C[0] = G[0] | P[0] & Cin; C[1] = G[1] | P[1] & G[0] | P[1] & P[0] & Cin; C[2] = G[2] | P[2] & G[1] | P[2] & P[1] & G[0] | P[2] & P[1] & P[0] & Cin; Cout = G[3] | P[3] & G[2] | P[3] & P[2] & G[1] | P[3] & P[2] & P[1] & G[0] | P[3] & P[2] & P[1] & P[0] & Cin; end else begin C[0] = 1'b0; C[1] = 1'b0; C[2] = 1'b0; Cout = 1'b0; end end //计算操作结果 assign Sum[0] = (~G[0] & P[0]) ^ Cin; assign Sum[1] = (~G[1] & P[1]) ^ C[0]; assign Sum[2] = (~G[2] & P[2]) ^ C[1]; assign Sum[3] = (~G[3] & P[3]) ^ C[2]; endmodule   展开全文 • Verilog 语言实现alu的设计 用Verilog 语言实现alu的设计 • [verilog]ALU实现 万次阅读 2018-04-12 09:19:34 module alu( input signed [31:0] alu_a, input signed [31:0] alu_b, input [4:0] alu_op, output reg [31:0] alu_out ); parameter A_NOP = 5'h00; parameter A_ADD = 5'h01; parameter A_SUB = 5'h02; ...   `timescale 1ns / 1ps // // Company: // Engineer: // // Create Date: 16:44:32 03/29/2018 // Design Name: // Module Name: alu // Project Name: // Target Devices: // Tool versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // // module alu( input signed [31:0] alu_a, input signed [31:0] alu_b, input [4:0] alu_op, output reg [31:0] alu_out ); parameter A_NOP = 5'h00; parameter A_ADD = 5'h01; parameter A_SUB = 5'h02; parameter A_AND = 5'h03; parameter A_OR = 5'h04; parameter A_XOR = 5'h05; parameter A_NOR = 5'h06; always@(*) begin case (alu_op) A_NOP:alu_out = 32'b0; A_ADD:alu_out = alu_a + alu_b; A_SUB:alu_out = alu_a - alu_b; A_AND:alu_out = alu_a & alu_b; A_OR :alu_out = alu_a | alu_b; A_XOR:alu_out = alu_a ^ alu_b; A_NOR:alu_out = alu_a ~^ alu_b; endcase end endmodule   下面写一个top模块进行实例化 `timescale 1ns / 1ps // // Company: // Engineer: // // Create Date: 16:45:31 03/29/2018 // Design Name: // Module Name: top // Project Name: // Target Devices: // Tool versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // // module top( input [31:0] a, input [31:0] b, output [31:0] out ); wire [31:0] c; wire [31:0] d; wire [31:0] e; alu al0(a,b,5'h01,c); alu al1(b,c,5'h01,d); alu al2(c,d,5'h01,e); alu al3(d,e,5'h01,out); endmodule   展开全文 • Verilog HDL是一种硬件描述语言(HDL:Hardware Description Language),以文本形式来描述数字系统硬件的结构和行为的语言,用它可以表示逻辑电路图、逻辑表达式,还可以表示数字逻辑系统所完成的逻辑功能。 Verilog... • VERILOG实现的4位 ALU 模块实现 5种运算 加减 与或非 • 算术逻辑单元(Arithmetic&logical Unit)是中央处理器(CPU)的执行单元,是所有中央处理器的核心组成部分,由"And Gate"(与门) 和"Or Gate"(或门)构成的算术逻辑单元,主要功能是进行二位元的算术运算,如加减乘... • Verilog 实现一个简单的ALU 万次阅读 多人点赞 2019-10-31 20:49:33 Verilog实现一个简单的ALU,使其具有进行N位有符号数的加法、减法及大小比较运算的功能。本篇文章实现的ALU以N = 8为例,想要实现其他位宽的数据运算,可以通过修改N的值来实现。 代码实现: /*------------------... 简介: 用Verilog实现一个简单的ALU,使其具有进行N位有符号数的加法、减法及大小比较运算的功能。本篇文章实现的ALU以N = 8为例,想要实现其他位宽的数据运算,可以通过修改N的值来实现。 代码实现: /*---------------------------------------------------------------- Filename: alu.v Function: 设计一个N位的ALU(可实现两个N位有符号整数加 减 比较运算) Author: Zhang Kaizhou Date: 2019-10-31 20:40:42 -----------------------------------------------------------------*/ module alu(ena, clk, opcode, data1, data2, y); //定义alu位宽 parameter N = 8; //输入范围[-128, 127] //定义输入输出端口 input ena, clk; input [1 : 0] opcode; input signed [N - 1 : 0] data1, data2; //输入有符号整数范围为[-128, 127] output signed [N : 0] y; //输出范围有符号整数范围为[-255, 255] //内部寄存器定义 reg signed [N : 0] y; //状态编码 parameter ADD = 2'b00, SUB = 2'b01, COMPARE = 2'b10; //逻辑实现 always@(posedge clk) begin if(ena) begin casex(opcode) ADD: y <= data1 + data2; //实现有符号整数加运算 SUB: y <= data1 - data2; //实现有符号数减运算 COMPARE: y <= (data1 > data2) ? 1 : ((data1 == data2) ? 0 : 2); //data1 = data2 输出0; data1 > data2 输出1; data1 < data2 输出2; default: y <= 0; endcase end end endmodule /*------------------------------------ Filename: alu_t.v Function: 测试alu模块的逻辑功能 Author: Zhang Kaizhou Date: 2019-10-31 20:42:38 ------------------------------------*/ `timescale 1ns/1ns `define half_period 5 module alu_t(y); //alu位宽定义 parameter N = 8; //输出端口定义 output signed [N : 0] y; //寄存器及连线定义 reg ena, clk; reg [1 : 0] opcode; reg signed [N - 1 : 0] data1, data2; //产生测试信号 initial begin //设置电路初始状态 #10 clk = 0; ena = 0; opcode = 2'b00; data1 = 8'd0; data2 = 8'd0; #10 ena = 1; //第一组测试 #10 data1 = 8'd8; data2 = 8'd5; //y = 8 + 5 = 13 #20 opcode = 2'b01; // y = 8 - 5 = 3 #20 opcode = 2'b10; // 8 > 5 y = 1 //第二组测试 #10 data1 = 8'd127; data2 = 8'd127; opcode = 2'b00; //y = 127 + 127 = 254 #20 opcode = 2'b01; //y = 127 - 127 = 0 #20 opcode = 2'b10; // 127 == 127 y = 0 //第三组测试 #10 data1 = -8'd128; data2 = -8'd128; opcode = 2'b00; //y = -128 + -128 = -256 #20 opcode = 2'b01; //y = -128 - (-128) = 0 #20 opcode = 2'b10; // -128 == -128 y = 0 //第四组测试 #10 data1 = -8'd52; data2 = 8'd51; opcode = 2'b00; //y = -52 + 51 = -1 #20 opcode = 2'b01; //y = -52 - 51 = -103 #20 opcode = 2'b10; //-52 < 51 y = 2 #100 $stop; end //产生时钟 always #`half_period clk = ~clk; //实例化 alu m0(.ena(ena), .clk(clk), .opcode(opcode), .data1(data1), .data2(data2), .y(y)); endmodule ModelSim仿真结果: 在这里插入图片描述 总结: 由上面的仿真结果可知,本次设计的ALU的逻辑功能达到的设计预期。 本次设计的关键点在于通过 “singed"的关键字定义输入输出数据为有符号的整数。这样使得加减运算变得十分简单,可以直接采用”+" "-"符号来实现相关运算,从而免去了自己设计有符号加法器的繁琐过程。 附注: 关于原码 反码 补码转换相关问题的总结: 在数字电路中,运算基本单元为0 1 代码构成的二进制数。在计算机存储器中,数字是以其二进制补码的形式存放的。 带符号数的二进制表示是以 符号位 + 数值位表示的。正数符号位为0,负数符号位为1。 例如:假定二进制数长度为8位,其中最高位为符号位。 1. 原码表示法: 5 = 0000 0101B -5 = 1000 0101B 2. 反码表示法: 5 = 0000 0101B -5 = 1111 1010B 3. 补码表示法: 5 = 0000 0101B -5 = 1111 1011B 由以上可知: 1. 正数的原码,反码,补码均相同。 2. 负数的反码 = 原码各位取反(除符号位)。 3. 负数的补码 = 反码 + 1。 4. +0的补码 = -0的补码 = 0000 0000B 【重要】 1. 位宽为N的二进制数能够表示的有符号整数的范围为[-2^(n - 1), 2^(n - 1) - 1]。 例如N = 8,即一个8位二进制数能够表示的有符号整数的范围为[-2^7, 2^7 - 1] = [-128, 127]。 2. 位宽为N的二进制数能够表示的无符号整数的范围为[0, 2^n - 1]。 例如N = 8,即一个8位二进制数能够表示的无符号整数的范围为[0, 2^8 - 1] = [0, 255]。 展开全文 • 32位ALU设计(verilog实现) 千次阅读 多人点赞 2020-11-06 18:40:42 ​ 算术逻辑单元(arithmetic and logic unit) 是能实现多组算术运算和逻辑运算的组合逻辑电路,简称ALU。算术逻辑单元是中央处理器(CPU)的执行单元,是所有中央处理器的核心组成部分,由"And Gate"(与门) 和"Or ... • alu verilog HDL 语言实现 2009-12-10 22:26:47 verilog HDL语言实现ALU 运行于quartus II • 1.题目 2.源码 // ********************************************************************************* // Project Name : 74381_ALU // Email : [email protected] // Website : https://home.cnbl... • 简单ALU(算术逻辑单元)的verilog实现,可实现两数相加、相减,或一个数的加1、减1操作。 小结: 要学会看RTL图,能够根据RTL图大致判断功能的正确性 代码: 1 module alu_add_sub( 2 rst_n, 3 ... • DE1-SoC_ALU_程序 用DE1-SoC板的多周期输入实现。 DE1-SoC板,ModelSim ALTERA入门版和Quartus II Web Edition 14.1 • Verilog HDL8位ALU 2015-11-17 14:55:19 Verilog HDL语言实现的一个8位ALU硬件电路 • Verilog HDL语言实现一个4位的ALU 千次阅读 多人点赞 2019-01-22 12:37:03 编写一个4位的ALU实现8种逻辑运算功能 在设计ALU的代码之前,首先应学会任务task和函数function,利用任务和函数可以把一个很大的程序模块分解成许多较小的任务和函数便于理解和调试。 task和function的相同点和... • ALU设计 用Verilog HDL 2013-04-16 10:09:24 Verilog HDL设计一个模块,该模块实现了一个4bit的ALU,可以对两个4bit二进制操作数进行算术运算和逻辑运算  算术运算包括加法与减法  逻辑运算包括与运算、或运算  设计一个模块,利用Verilog HDL模块元件实例... • 使用Verilog语言实现一个四位的ALU运算单元实验内容需要实现的功能设计思路约束文件测试最后 设计思路主要来自这里,不过原文的乘法实现有一些小问题,我做了一些修改。 实验内容 设计一个算术逻辑单元 输入信号:... • 8位RISC CPU的Verilog实现 文章目录8位RISC CPU的Verilog实现一. 设计需求二. 硬件组成2.1 存储器2.1.1 ROM2.2.2 RAM2.2 CPU2.2.1 PC2.2.2 累加器2.2.3 地址选择器2.2.4 ALU2.2.5 通用寄存器2.2.6 IR2.3 内部结构... • 1、利用Verilog语言完成单周期MIPS指令处理器的设计, 2、锻炼复杂电路的设计能力。 二、实验要求 完成单周期MIPS指令处理器设计,并下载到FPGA开发板上,开发板的LED灯显示ALU的计算结果,处理器的时钟由开发板上的... 空空如也 空空如也 1 2 3 4 收藏数 64 精华内容 25 关键字: verilog实现alu
__label__pos
0.826224