text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Hello everyone, Previously, I think if I am using namespace ns1, and declaring and defining a public class cs1 using C# Class Library project, I have to name the output DLL name to be ns1.dll. I have this idea because I noticed that Microsoft names the DLLs, like System.dll for name space System, System.Data.dll for name space System.Data. Now I tried that I can name the output DLL name to arbitrary name (not ns1), like mylib.dll. Then the applications which use the DLL still work. So, I think the conclusion should be, we can use arbitrary name which is not related to namespace. Right? thanks in advance, George
http://cboard.cprogramming.com/csharp-programming/93119-dll-output-file-naming-convension.html
CC-MAIN-2014-23
refinedweb
114
74.69
have to modify the game code so it determines a winner or a tie and halts the game when it is finished with some msg indicating the results. i.e. X Wins, O Wins, TIE. Here is the java code for the game so far /** A 3 x 3 tic-tac-toe board. */ public class TicTacToe { private String[][] board; private static final int ROWS = 3; private static final int COLUMNS = 3; /** Constructs an empty board. */ public TicTacToe() { board = new String, String player) { if (board[i][j].equals(" ")) board[i][j] = player; } /** Creates a string representation of the board, such as |x o| | x | | o| @return the string representation */ public String toString() { String r = ""; for (int i = 0; i < ROWS; i++) { r = r + "|"; for (int j = 0; j < COLUMNS; j++) r = r + board[i][j]; r = r + "|\n"; } return r; } } Edited by Dogstopper:
http://www.dreamincode.net/forums/topic/209923-tic-tac-toe-game/
CC-MAIN-2016-50
refinedweb
142
66.07
Business Planning and Simulation version for Netweaver successfully leverages the Netweaver infrastructure and we can use the data stored in infocubes in the Enterprise Data Warehouse in BPC7NW. In this blog we will discuss what tools and techniques we can use to get the transactional data stored in any infocube in BW into BPC Application using Data Manager in BPC7NW. Options available for cube to cube data load: There are many options available to the users of BPC7NW to get transactional data from a BW cube to BPC Application. Here are some of them: - We can export the transactional data from any infocube in the form of flat file and then use Data Manager in BPC7NW to load that data from flat file to BPC Application. The advantage of this option is that it is relatively very simple to administer and very flexible to adapt since we are dealing with a flat file when it comes to importing data into BPC Application. The limitation of this option is that here we are really not leveraging the BW platform. If we have to load data from any other non-BW source, we can use exactly the same approach – export data from that external data source to a flat file and then import that flat file into BPC. So in essence, in this option we are treating BW infocube as any other external data source. There is another ostensible limitation that this option may portray – that this process can not be automated. If we have to get a flat file export from an infocube and then import that flat file into BPC, then it may appear that there has to be a handoff from the flat file export to the import of flat file. However we can overcome this limitation, if we want to, by creating a custom process chain that in turn executes the process chain to import the flat file data into BPC Application. You can read more about that at Running BPC process chains within non-BPC process chains - We can leverage BW Extraction, Transformation and Loading (ETL) tools to transfer transactional data from any infocube to the infocube used by BPC Application. BPC Application in BPC7NW generates its own infocube in its namespace. We can use standard BW ETL techniques to transform and load the data to the cube used by the BPC Application. (You can read more about BPC namespace at A reservation of a different kind – why, what and how of BPC namespace). This option also is valid one and it indeed leverages the BW platform and also this can very well be automated if we desire to do so. Further this option can handle deltas very efficiently since we can use the delta handling mechanisms in BW. Lastly, using the ETL toolset is a proven, scalable and very robust technique to handle data within BW. However this option is also beset with several limitations. Firstly, infocube for the BPC Application will need to be switched to loading mode while loading it using ETL and then switch it back to planning mode after loading is complete. This means that during that time, it will not be available for planning through BPC front end. So the ETL load has to coordinated with the BPC users to avoid any potential mishaps like the automated process switching the BPC cube to loading mode when a planner is in the middle of updating his/her plan. Secondly, in BPC7NW, we can maintain validations to validate the data written to BPC Application so that invalid records are not written and data integrity is maintained. If we use BW ETL, it will bypass this validation mechanism completely and there is a risk of invalid records being written to BPC application. The validation mechanism will not check the records that have already been written. Thirdly, the BPC audit logs will not be updated if we use BW ETL since it won’t invoke any BPC audit functionality. Fourthly, the data will always be additive – for example if we have 10 in the cube and then write 100, the result will always be 110. This is just a consideration rather than a limitation. Finally, if and when the BPC user executes ‘full optimize’ for the BPC Application, BPC may end up generating a totally new cube which is more optimized than the previous one. In that case, all the ETL work that was done for the previous cube will be dropped from the new cube. At present, the ‘full optimize’ option does not automatically inherit the ETL configuration done on the earlier BPC cube. The building blocks for the ETL like the datasource, infosource etc will still be there in BW but they would be required to be linked again to the new cube. - This brings us to the third option which we will discuss in much more detail. This option is to use the Data Manager in BPC7NW to load transactional data from any Infoprovider in BW to the BPC Application. This option overcomes almost all the limitations enumerated above since this is executed from within BPC itself. This can very well be scheduled from within Data Manager or by invoking the Data Manager process chain from a custom process chain. So let us see how exactly we should go about realizing this. Creating transformation file: Before we run the data manager package to load data, we should prepare the transformation and conversion files. An example of a transformation file that we can use to load data from other infoproviders is given below. Please note the mapping section. The dimension names in the BPC Application are mapped to the corresponding characteristics from the Infoprovider from where we want to load the data. Please note that as far as the BPC dimension names are concerned, we are using the dimension names (and not the technical names of the BW characteristics corresponding to those dimensions) whereas when we map them to the Infoprovider characteristics, we must use the technical names of the BW characteristics. For example, the TIME dimension in BPC is mapped to 0FISCPER characteristic in BW. Here TIME is the BPC Dimension name whereas 0FISCPER is the technical name of the BW characteristic in the source Infoprovider. Also please note the mapping for AMOUNT. The AMOUNT is mapped to the technical mane of the key figure in the source Infoprovider. So in this case, ZMAOUNT01 is the technical name of the key figure in the source Infoprovider. In this regard, please note that the source BW Infoprovider can have multiple key figures. If so, we can choose only one key figure in a transformation file since our BPC cube has only one key figure. If for any reason, you have a situation where you have to get data from two or more key figures, you can use multiple transformation files and run the data manager package multiple times with each transformation file. However in that case, please note that the data from all those key figures will end up in the same single key figure in the BPC cube. What if there is no corresponding characteristic in the source Infoprovider for a dimension in BPC? What if we want to have a single default value in the data load regardless of what exists in the source Infoprovider? Well, in that case, we can use the keyword *NEWCOL in the transformation file for the corresponding BPC dimension. Please see the example of the transformation file below. Here for the category dimension, we are forcing the default value of FORECAST in the data load. Similarly for the dimension P_DATASRC, even if there is no corresponding BW characteristic in the source Infoprovider, it is OK – we can always pass the default value through our transformation file. What if we want to load only a subset of the data from the source Infoprovider? In that case, we can enter our selection in the transformation file. Please see the example of the following transformation file: Please note that in the OPTIONS section, we have entered a selection to select data from only two characteristic values C2000 and C1000 of the characteristic ZACCT01. Hence we are selecting only a subset of the source Infoprovider. You can enter selections from multiple characteristics here in the selection and thus load data from a specific data slice in the source from Infoprovider. Creating conversion file: In addition to the transformation file, we can have conversion files and refer them in the transformation files. This is necessary if the master data values in the BPC dimension in the BPC Application (dimension members) and the characteristics in the source Infoprovider (characteristic values) are different. Those conversion files we can refer in the transformation file as shown below: Here, the conversions for TIME dimension are read from the file ZBICGR01TIME.XLS. That conversion file can have the mapping between internal (BPC) time dimension members and external (0FISCPER) values. That conversion file is shown below: Here ? is used as a wildcard so that we don’t have to write conversion for each year. This conversion file can work for any year. Another example of the conversion file for account is shown below: In addition to writing such conversion files for BPC dimensions, we can write the conversion for AMOUNT if necessary. For example, if we want to change the data coming over for a particular dimension member during the load, we can write the formula in the conversion file for AMOUNT as shown below: So in this case, the data for account CE0004220 will be increased by 10% during the load. Validating the transformation file: After we prepare the transformation and conversion files, the next step would be to get the transformation validated with the source Infoprovider. BPC7NW gives additional options for validation as shown below: We should select the option ‘transaction data from infocube’ and enter the technical name of the Infoprovider. Please note that though the option here reads ‘transaction data from infocube’ it works with DSO also in the same way. The validation then can validate our transformation and conversion files against the data in the source Infoprovider and gives us the result as shown below: Running the data manager package: Once we have our transformation files validated, we are in a good shape to run our data manager package to load the data from the source Infoprovider. There is a delivered process chain and data manager package to load data from Infoprovider as shown below: If we run this package, we can enter the technical name of the source Infoprovider and the transformation file and schedule the load. Upon completion, we can get the success message in the data manager package status as shown below: So far we have seen how we can use the data manager features to load data from any Infoprovider in BW to BPC Application. This raises another question. Can we use the same technique to load data from one BPC application to another BPC application in the same Appset or for that matter from any application in any other Appset within BPC7NW? The answer is an emphatic ‘yes’. We can treat the BPC application in the same or other appset as just another BW cube with characteristics and key figure. The only consideration is using this approach to load data from other applications in other appsets is that we have to maintain the /CPMB name space technical names of the characteristics of those dimensions in the transformation file against the dimension names of the target application and while running the package, we have to enter the /CPMB namespace technical name of the infocube pertinent to the source BPC application. An example of the transformation file used for such data transfer is shown below. Thus we can see that we can effectively leverage the Netweaver platform to transfer the transactional data from one infocube to another using Data Manager package. Amazing blog pravin. You almost covered all the common possible scenario in data load. I am wondering how other keyfigures values like Quantity and price are handled in single Keyfigure model.Do we have to follow Account based model by creating another dimension called KFY and have member value Qty to store quantity and PRC for storin Price. Thanks, sanjay. The key figure scenario can be solved by creating another staging BW info provider with single KF struture. transformation can be created using Rule groups to acheive this to laod the data to staging BW info provider.and data can be loaded from staging BW info provider using data manager wihtout any transformation needed. Some tips on how to handle the concept of characteristic relationships, data slices and Multiprovider in BPC 7.0NW will be very useful. regards, Lokesh Nandula Regards, Vinod Swarnapuri You have covered all the aspects required. Keep it up. This is an excellent blog explaining all the benefits and limitations of each method. But I have few queries. Firstly in the blog for running BPC process chains within custome process chain, we have used a XML transformation file. While here we have used a transformation and a conversion file. Why is this different. And how do we specify the conversion in case of custome process chain method, as we are using XML file. Secondly, To load data directly from BW InfoProvider to BPC Cube, the last method explained how can we automate this using process chain. Can this also be included in custom chains. Any help would be greately appreciated. Regards, Tintu Your questions may be answered here:;jsessionid=(J2EE3414700)ID1897954850DB00258195100095085303End?blog=/pub/wlg/15626 The XML version of the transformation file is created when you validate and process the transformation file. Hence in case of the transformation file described in this blog also the XML version will be created. I want to know that, while loading data from BW info provider to BPC using data manager, does the structure of BW info provider should match the BPC cube struture? does BW info provider need to have all info objects of length 20 and Char datatype? The structure need not match but you need to use conversion files to convert the source data to 20 char dimension members in BPC. I think this an excellent and interesting blog. I have some doubts about the third method. When I design a transformation file with more than one Round, when you validate or execute it, it only loads data belonging to the last Round, not all the Rounds. How can I load all data belonging to all Rounds? In this way, it would allow me to reduce the number of the Transformation Files. On the other hand, could you explain, if it is possible, an example about how to automate loading data from BW InfoProvider to BPC Cube, creating an only custom process chain, that works with multiple Transformation files. It would allow me to load data from several transformation files with an only package. Thanks in advance, Albert The transformation file in 7NW supports only one round and hence only the last round is considered. For automating the laoding of data, please refer to:;jsessionid=(J2EE3414700)ID1897954850DB00258195100095085303End?blog=/pub/wlg/15626 Thank you for this excellent blog. I followed your instructions and loaded data succesfully. At the end of the process , the data manager log detail seems like that: Task name Append Load: Reject Count: 0 Submit Count: 35473 Application: Inspection. Package Status: SUCCESS But i am not able to bring data to my reports and also i can not see loaded data on my BPC cube directly. Is there another step for activating data or something like that? Thanks. Regards, Muge. There is no step to activate the data. The data should be availalble immediately. One way out to recheck the data is to view the data in the infocube (through the BW way – transaction listcube) Regards Pravin You have covered all the points. I have one doubt : I have understood from the blog that we can load only full load. Please let me know how to load delta through the Data Management Pakage. Thanks. With regards, Anand Kumar At present it is full load. For delta load, you can have a DSO before you load the records into BPc and every time after loading into BPC you can clear the DSO. Please note that this is a BW solution/work around to handle deltas and not a BPC solution. I’m really interested in the third method, but I can’t find the package “LoadData” (load data from infoprovider) in the list available. Did you made something special to make it available ? (on my side the closer package available seems to be “LoadInfoProvider” and it needs to be “called” from the target cube (in current view), and since it’s not a BPC cube, it’s not available in the list) Thanks in advance for your help. Guillaume P. I have a question regarding data transfer from BPC NW 7.5 to BW cube. Wich choices I have to do this? Do I have to use files? Best regards, Vitor Ramalho Is there any blog that says how can I load data to BW cube using a BADI? I hope that I can avoid using flat files. Thanks. Then use this assing: *MAPPING ID=ID RESPONSABLE=0RESP_USER BPC=*IF(ID(2:2)=*STR(I) then *STR(I);*IF(ID(2:2)=*STR(D) AND ID(4:4)=*STR(Z) then *STR();*STR(D))) PAIS=*IF(ID(1:1)=*STR(C) then *STR(CHILE);*STR(PERU)) In Validate get Error for Field BPC : The number in parentheses is incorrect, check your formula *IF(ID(2:2)=*STR(I) then *STR(I);*IF(ID(2:2)=*STR(D) AND ID(4:4)=*STR(Z) then *STR();*STR(D))) This line working good : PAIS=*IF(ID(1:1)=*STR(C) then *STR(CHILE);*STR(PERU)) Examples value for 0PROFIT_CTR is : CD1Z0101 CD101C01 PI1CA001 CI1CA001 I look sintaxis and is good number in parentheses. I test this : BPC=*IF(ID(2:2)=*STR(D) AND ID(4:4)=*STR(Z) then *STR();*STR(D)) And GET error : *IF formula is not valid, check your formula Maybe problem is in “AND” stament ? Very nice article. Is there any way that we can make the Transformation File dynamically change the SELECTION criteria without user input? For example, say we only want to load the previous months data using the using the source of the TIME dimension from BW, could we make the selection “smart” enough to automatically do this? Or would we have to resort to either a manual change of the Transformation file or use of a Delta in BW? I liked this weblog. It was very useful. But it would have been nice if it was also part of the e-learning.
https://blogs.sap.com/2009/04/16/loading-transactional-data-from-any-infocube-to-bpc-application-in-bpc7nw/
CC-MAIN-2018-05
refinedweb
3,145
59.33
Wouldn’t it be cool to be able to connect MS Access or other database to a Bing Map and use some of the cool features? I got nothing in this blog about specifically using MS Access, however, if you want to see a blog that does connect to XML data and you are an advanced beginner or better, then go to the blog and read through:, I am working on getting there. Some people write blogs about things they know, I do blog entries for no good reason, sort of a stream of consciousness like Ulysses, without all of the weird sexual overtones. I think it would be cool to connect to MS Access, and it would be nice to have a clear step-by-step on how to do that, it’s not in this blog. Where I like the idea of the Bing Map App, let’s dig into Bing SilverLight Interactive Map Control for this blog. And I will ignore my original statement about MS Access and come back to it in a later blog. I just got distracted by the thought that what the heck is XAML and why does it exist, how painful. It isn’t really painful after you stare at it for a few months, XAML is similar to the XML used in World Of Warcraft, the XML is used with the Lua code to build external applications that work with World of Warcraft. In a similar way, XAML acts as the user interface, in this case the reason for XAML is that there are a large number of ways now that the users interface with software, so drag and drop can work, but some people like to write the interface rather do the drag and drop kind of design. Go figure, I don’t really care, but tend to like drag and drop, but put up with the code writers. There are just a lot of people in control of software design that are code writers, not drag and droppers. Go figure, you need both. Let’s go over the map control again, and again, and again, till I get it, that is why I teach, so I can learn from the method of teaching: I opened up an ASP.NET Web Site in Visual Studio Ultimate, but you definitely use Visual Web Developer (Visual Web Dev) Add the SilverLight Libraries using Add Reference To make use of the SilverLight Interactive Map Control, you need the Bing Map SDK ID or you get this , The page appears to tell you where to go to get the developer account, on Nov. 8, 2010, it isn’t the correct web page, the page shown resolves to MSDN.Microsoft.com, close, but no credentials. To get credentials, see my blog, () which if I wasn’t so paranoid about any redirector, I would shorten. Links active as of Nov. 8, 2010 Once you got your credential all set up, you can now utilize the Silverlight control, as I have discussed earlier, (and I have given up on using the cute code containers for short code snips, I start with a comment and end with a comment): <!--- Start of Code: ---> <UserControl x: <Grid x: <m:Map </Grid> </UserControl> <!--- End of Code ---> To work with this usercontrol (the SilverLight Interactive Map Control is a type of Usercontrol), you can place the map mode into C# control. This is similar to using PHP, except that you have more advanced design and security management using C#. //Start of code using System.Windows.Controls; using Microsoft.Maps.MapControl; namespace SilverlightTestApplication { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); myMap.Mode = new AerialMode(); } } } // End of code In Secret communications X017Y, I will go over the addition of buttons and then eventually get to the way to connect to a data source like MS Access 2010. End of Secret Communications X016Y NNNN Legal Note: Restrictions:
http://blogs.msdn.com/b/devschool/archive/2010/11/08/secret-communications-x016y-connecting-ms-access-to-a-bing-map.aspx
CC-MAIN-2015-22
refinedweb
653
64.54
On 11/26/2014 07:10 PM, Ronghai Wu wrote: Hi Robert, Should I prescribe Dijkl to each vertex like the prestress, or only need to prescribe to each element? Ideally, it would be to evaluate/prescribe Dijkl in the coordinates that are passed to the material function - those coordinates are the quadrature points, where the Dijkl is needed. In the last version of your script, the prestress is not prescibed in vertices. Instead, it is prescribed to each element - it is just repeated to all the points that fall to each element. So if having Dijkl piece-wise constant (over elements) is ok for you, you can define in exactly the same way as the prestress - define it in elements (centres) and repeat n_qp times using np.repeat(). Besides, if using strain = pb.evaluate('ev_cauchy_strain.2.Omega(u)', mode='el_avg'), the shear value in strain is sigma_xy or 2*sigma_xy? See [1]. [1]... Cheers, r. Regards Ronghai 在 2014年11月26日星期三UTC+1下午3时14分44秒,Robert Cimrman写道: > On 11/26/2014 02:39 PM, Ronghai Wu wrote: Hi Robert, Now I encounter a more complicated case. What if the stiffness tensor is not constant, but a function of eta, as shown in PDF "non-constant elastic tensor.pdf". Is it possible to implement it based on the modified code "Ronghai.py"? So eta is a known function of position? This can be done by a material parameter given by a user-defined function again [1], just like you do the prestress. The function would be something like: def get_d(ts, coors, mode=None, **kwargs): if mode == 'qp': x = coors[:, 0] y = coors[:, 1] value = ... return {'D' : value} and in the code, use something like: d_fun = Function('d_fun', get_d) m = Material('m', function=d_fun) Also, if you need to work with the elastic tensors, use dw_lin_elastic term instead of dw_lin_elastic_iso. r. [1] Regards Ronghai
https://mail.python.org/archives/list/sfepy@python.org/message/4HKTNET2MYEIKBUTWQIG2MKFUEWPZSK2/
CC-MAIN-2020-24
refinedweb
309
60.85
Day 21: Search engine Previously on symfony With AJAX interactions, web services, RSS feed, a hat ful of site management features, and a growing number or users, askeet has almost all that a web 2.0 application could ask for. The symfony community debated about what could be added on top of that, in order to make askeet a real killer application. Some of the suggestions included features that were already planned for initially. Others concerned small additions that will take only a couple minutes to implement, and that will probably be added shortly after the 1.0 release. Askeet aims to be a living open-source application, and you can start raising tickets or proposing evolutions in the askeet trac system. And you can also contribute patches and adapt or extend the application as you wish. But please wait a few more days, for the advent calendar has some more surprises for you before Christmas. How to build a search engine? The most popular suggestion about the 21st day addition proved to be a search engine. If the Zsearch extension (a PHP implementation of the Lucene search engine from Apache) had already been released by Zend, this would have been a piece of cake to implement. Unfortunately, Zend seems to take longer than expected to launch their PHP framework, so we need to find another solution. Integrating a foreign library (like, for instance, mnoGoSearch) would probably take more than one hour, and lots of custom adaptations would be necessary to obtain a good result for the askeet specific content. Plus, foreign search libraries are often platform or database dependant, and not all of them are open-source, and that's something we don't want for askeet. The MySQL database offers a full-text indexation and search for text content, but it is restricted to MyISAM tables. Once again, basing our search engine on a database-specific component would limit the possible uses of the askeet application, and we want to do everything to preserve the large compatibility it has so far. The only alternative left is to develop a full-text PHP search engine by ourselves. And we have less than one hour, so we'd better get started.: A new SearchIndex table is added to the askeet schema.xml before rebuilding the model: <table name="ask_search_index" phpName="SearchIndex"> <column name="question_id" type="integer" /> <foreign-key <reference local="question_id" foreign="id"/> </foreign-key> <column name="word" type="varchar" size="255" /> <index name="word_index"> <index-column </index> <column name="weight" type="integer" /> </table> The onDelete attribute ensures that the deletion of a question will lead to the deletion of all the records in the SearchIndex table related to this question, as explained yesterday. Splitting phrases into words The input content that will be used to build the index is a set of sentences (question title and body) and tags. What is eventually needed is a list of words. This means that we need to split the sentences into words, ignoring all punctuation, numbers, and putting all words to lowercase. The str_word_count() PHP function will do the trick: // split into words $words = str_word_count(strtolower($phrase), 1); ... Stop words Some words, like "a," "of," "the," "I,", "it", "you," and "and", have to be ignored when indexing some text content. This is because they have no distinctive value, they appear in almost every text content, they slow down a text search and make it return a lot of poorly interesting results that have nothing to do with a user's query. They are known as stop words. The stop words are specific to a given language. For the askeet search engine, we will use a custom list of stop words. Add the following method to the askeet/lib/myTools.class.php class: public static function removeStopWordsFromArray($words) { $stop_words = array( ', ); return array_diff($words, $stop_words); } Stemming The first thing that you should notice in the example question given above is that words having the same radical should be seen as a single one. 'Children' should increase the weight of 'child', as should 'sign' do for 'signs'. So before indexing words, they have to be reduced to their greatest common divisor, and in linguistics vocabulary, this is called a stem, or "the base part of the word including derivational affixes but not inflectional morphemes, i. e. the part of the word that remains unchanged through inflection". There are lots of rules to transform a word into its stem, and these rules are all language-dependant. One of the best stemming techniques for the English language so far is called the Porter Stemming Algorithm and, as we are very lucky, it has been ported to PHP5 in an open-source script available from tartarus.org. The PorterStemmer class provides a ::stem($word) method that is perfect for our needs. So we can write a method, still in myTools.class.php, that turns a phrase into an array of stem words: [php] public static function stemPhrase($phrase) { // split into words $words = str_word_count(strtolower($phrase), 1); // ignore stop words $words = myTools::removeStopWordsFromArray($words); // stem words $stemmed_words = array(); foreach ($words as $word) { // ignore 1 and 2 letter words if (strlen($word) <= 2) { continue; } $stemmed_words[] = PorterStemmer::stem($word, true); } return $stemmed_words; } Of course, you have to put the PorterStemmer.class.php in the same askeet/lib/ directory for this to work.. That's why we need to give weight to words according to the part of the question they come from. As the weight factors have to be easily accessible, to make them vary if we want to fine tune our search engine algorithm, we will put them in the application configuration file ( askeet/apps/frontend/config/app.yml): all: ... search: body_weight: 1 title_weight: 2 tag_weight: 3 In order to apply the weight to a word, we simply repeat the content of a string as many times as the weight factor of its origin: ... // question body $raw_text = str_repeat(' '.strip_tags($question->getHtmlBody()), sfConfig::get('app_search_body_weight')); // question title $raw_text .= str_repeat(' '.$question->getTitle(), sfConfig::get('app_search_title_weight')); ... The basic weight of the words will be given by their number of occurrences in the text. The array_count_values() PHP function will help us for that: ... //. So the following should not surprise you. Open the askeet/lib/model/Question.php file and add in: public function save($con = null) { $con = sfContext::getInstance()->getDatabaseConnection('propel'); try { $con->begin(); $ret = parent::save($con); $this->updateSearchIndex(); $con->commit(); return $ret; } catch (Exception $e) { $con->rollback(); throw $e; } } public function updateSearchIndex() { // delete existing SearchIndex entries about the current question $c = new Criteria(); $c->add(SearchIndexPeer::QUESTION_ID, $this->getId()); SearchIndexPeer::doDelete($c); // create a new entry for each of the words of the question foreach ($this->getWords() as $word => $weight) { $index = new SearchIndex(); $index->setQuestionId($this->getId()); $index->setWord($word); $index->setWeight($weight); $index->save(); } } public function getWords() { // body $raw_text = str_repeat(' '.strip_tags($this->getHtmlBody()), sfConfig::get('app_search_body_weight')); // title $raw_text .= str_repeat(' '.$this->getTitle(), sfConfig::get('app_search_title_weight')); // title and body stemming $stemmed_words = myTools::stemPhrase($raw_text); // unique words with weight $words = array_count_values($stemmed_words); // add tags $max = 0; foreach ($this->getPopularTags(20) as $tag => $count) { if (!$max) { $max = $count; } $stemmed_tag = PorterStemmer::stem($tag); if (!isset($words[$stemmed_tag])) { $words[$stemmed_tag] = 0; } $words[$stemmed_tag] += ceil(($count / $max) * sfConfig::get('app_search_tag_weight')); } return $words; } We also have to update the question index each time a tag is added to it, so override the save() method of the Tag model object as well:: The search function AND or OR? We want the search function to manage both 'AND' and 'OR' searches. For instance, if a user enters 'family zodiac', he (she?) must be given the choice to look only for the questions where both the two terms appear (that's an 'AND'), or for all the questions where at least one of the term appears (that's an 'OR'). The trouble is that these two options lead to different queries: // OR query SELECT DISTINCT question_id, COUNT(*) AS nb, SUM(weight) AS total_weight FROM ask_search_index WHERE (word = "family" OR word = "zodiac") GROUP BY question_id ORDER BY nb DESC, total_weight DESC // AND query SELECT DISTINCT question_id, COUNT(*) AS nb, SUM(weight) AS total_weight FROM ask_search_index WHERE (word = "family" OR word = "zodiac") GROUP BY question_id HAVING nb = 2 ORDER BY nb DESC, total_weight DESC Thanks to the HAVING keyword (explained, for instance, at w3schools), the AND SQL query is only one line longer than the OR one. As the GROUP BY is on the id column, and because there is only one index occurrence for a given word in a question, if a question_id is returned twice, it is because the question matches both the 'family' and 'zodiac' term. Neat, isn't it? The search method For the search to work, we need to apply the same treatment to the search phrase as to the content, so that the words entered by the user are reduced to the same kind of stem that lies in the index. Since it returns a set of questions without any foreign constraint, we decide to implement it as a method of the QuestionPeer object. The search results need to be paginated. As we use a complex request, the sfPropelPager object cannot be employed here, so we will do a pagination by hand, using an offset. There is one more thing to remember: askeet is made to work with universes (that was the subject of the eighteenth day tutorial). This means that a search function must only return the questions tagged with the current app_permanent_tag if the user is browsing askeet in a universe. All these conditions make the SQL query slightly more difficult to read, but not much different from the ones described above: public static function search($phrase, $exact = false, $offset = 0, $max = 10) { $words = array_values(myTools::stemPhrase($phrase)); $nb_words = count($words); if (!$words) { return array(); } $con = sfContext::getInstance()->getDatabaseConnection('propel'); // define the base query $query = ' SELECT DISTINCT '.SearchIndexPeer::QUESTION_ID.', COUNT(*) AS nb, SUM('.SearchIndexPeer::WEIGHT.') AS total_weight FROM '.SearchIndexPeer::TABLE_NAME; if (sfConfig::get('app_permanent_tag')) { $query .= ' WHERE '; } else { $query .= ' LEFT JOIN '.QuestionTagPeer::TABLE_NAME.' ON '.QuestionTagPeer::QUESTION_ID.' = '.SearchIndexPeer::QUESTION_ID.' WHERE '.QuestionTagPeer::NORMALIZED_TAG.' = ? AND '; } $query .= ' ('.implode(' OR ', array_fill(0, $nb_words, SearchIndexPeer::WORD.' = ?')).') GROUP BY '.SearchIndexPeer::QUESTION_ID; // AND query? if ($exact) { $query .= ' HAVING nb = '.$nb_words; } $query .= ' ORDER BY nb DESC, total_weight DESC'; // prepare the statement $stmt = $con->prepareStatement($query); $stmt->setOffset($offset); $stmt->setLimit($max); $placeholder_offset = 1; if (sfConfig::get('app_permanent_tag')) { $stmt->setString(1, sfConfig::get('app_permanent_tag')); $placeholder_offset = 2; } for ($i = 0; $i < $nb_words; $i++) { $stmt->setString($i + $placeholder_offset, $words[$i]); } $rs = $stmt->executeQuery(ResultSet::FETCHMODE_NUM); // Manage the results $questions = array(); while ($rs->next()) { $questions[] = self::retrieveByPK($rs->getInt(1)); } return $questions; } The method returns a list of Question objects, ordered by pertinence. The search form The search form has to be always available, so we choose to put it in the sidebar. As there are two distinct sidebars, they should include the same partial: // add to defaultSuccess.php and questionSuccess.php in askeet/apps/frontend/modules/sidebar/templates/ <h2>find it</h2> <?php include_partial('question/search') ?> // create the following askeet/apps/frontend/modules/question/templates/_search.php fragment <?php echo form_tag('@search_question') ?> <?php echo input_tag('search', htmlspecialchars($sf_params->get('search')), array('style' => 'width: 150px')) ?> <?php echo submit_tag('search it', 'class=small') ?> <?php echo checkbox_tag('search_all', 1, $sf_params->get('search_all')) ?> <label for="search_all" class="small">search with all words</label> </form> The @search_question rule has to be defined in the routing.yml: search_question: url: /search/* param: { module: question, action: search } Do you know what this question/search action does? Almost nothing, since most of the work is handled by the QuestionPeer::search() method described above: public function executeSearch () { if ($this->getRequestParameter('search')) { $this->questions = QuestionPeer::search($this->getRequestParameter('search'), $this->getRequestParameter('search_all', false), ($this->getRequestParameter('page', 1) - 1) * sfConfig::get('app_search_results_max'), sfConfig::get('app_search_results_max')); } else { $this->redirect('@homepage'); } } The action has to translate a page request parameter into an offset for the ::search() method. The app_search_results_max is the number of results per page, and as usual, it is an application parameter defined in the app.yml file: all: search: results_max: 10 Display the search result The hardest part of the job is done, we just have to display the search result in a askeet/apps/frontend/modules/question/templates/searchSuccess.php. As we didn't implement a real pagination to keep the query light, the template has no information about the total number of results. The pagination will just display a 'more results' link at the bottom of the result list if the number of results equals the maximum of results per page: <?php use_helper('Global') ?> <h1>questions matching "<?php echo htmlspecialchars($sf_params->get('search')) ?>"</h1> <?php foreach($questions as $question): ?> <?php include_partial('question/question_block', array('question' => $question)) ?> <?php endforeach ?> <?php if ($sf_params->get('page') > 1 && !count($questions)): ?> <div>There is no more result for your search.</div> <?php elseif (!count($questions)): ?> <div>Sorry, there is no question matching your search terms.</div> <?php endif ?> <?php if (count($questions) == sfConfig::get('app_search_results_max')): ?> <div class="right"> <?php echo link_to('more results »', '@search_question?search='.$sf_params->get('search').'&page='.($sf_params->get('page', 1) + 1)) ?> </div> <?php endif ?> Ah, yes, this is the final surprise. We refactored a little the question templates to create a _question_block.php question block, as the code was reused in more than one place. Have a look at this fragment in the source repository, there is nothing new in it. But it helps us to keep the code clean. See you Tomorrow It took us about one hour to build a good search engine, perfectly adapted to our needs. It is light, fast and efficient. It returns pertinent results. Would you want to integrate an external library to do the same job without any possibility to tweak it? If not, you are probably getting to think the symfony way. If you understood this tutorial, you can probably add to the search engine the indexing of answers to a question. Questions and suggestions are welcome in the askeet forum. And most of all, don't create new questions on askeet if a similar question has already been asked: Now there is a search engine, you have no excuse!
https://symfony.com/legacy/doc/askeet/1_0/en/21
CC-MAIN-2020-16
refinedweb
2,348
52.9
Welcome! Got a question? Do you have -Ypartial-unification turned on? Other FAQs: IO[A] = () => A, which has the limitations outlined above def t: Awith val t: () => A) Idand in code using IO, and see how they differ (because the latter takes great care to satisfy various laws under a broad range of operational conditions, and the former doesn't). Here there are a few implementations of IO, the first one of which is essentially with () => A. But I do think that looking at the implementation is not the right way to understand IO at first Bracket IO[A]is a program. Option[A]is a program. These programs can be composed using certain operations. You build your code by building mini-programs, assembling bigger programs out of small ones, and translating programs from one "language" to another (eg. fs2.Streamto IO, or Optionto Either) for forprioritises brevity over clarity, and when trying to form a clear semantic mental model it's unhelpful Optionfirst?
https://gitter.im/typelevel/cats?at=5d9f9e91464b432fc1f58ccc
CC-MAIN-2021-39
refinedweb
164
54.12
Navigation and Search Navigate from Here This is a single shortcut for all your navigation needs. Navigate from Here Symbol The Go to Symbol feature (Ctrl+Shift+Alt+N) is the most far-reaching of the "Go to" family of search commands. This powerful feature searches by name, solution-wide, for any file member. All ReSharper's 'Go to' commands, including Go to Symbol, support CamelHumps. That is, you can find a member quicker by entering its initial character and subsequent upper case characters. Go to Type Press Ctrl+N to navigate to any type within your solution. Start typing in the input box, and a lookup list will appear with type names matching the entered substring. This feature also supports wildcards: '*' (asterisk) represents zero or more characters; '+' (plus) represents one or more characters; '?' (question mark) represents one or zero characters. In addition, you can type just capitalized symbols or use CamelHumps notation. For example, you can simply type ATB instead of AbstractTreeBuilder. >. In XAML files, you can quickly navigate to any named entity. at the method declaration on the left gutter of the editor window. Click the icon to navigate up the methods hierarchy. Go to Inheritor Similarly to Go to Base, this command lets you navigate down to a derived type or method by pressing Ctrl+Alt+B. Go to Declaration To navigate to the declaration of a symbol, position the caret at any symbol usage and press Ctrl+B, or hold Ctrl and left-click the symbol. ReSharper will position the caret on the declaration of the corresponding type, method, field, or local variable in the relevant source file (which opens automatically if necessary). For library symbols, the corresponding entity will be displayed in Visual Studio's Object Browser. Go to Type Declaration Press Ctrl+Shift+T to navigate to the declaration of a type that a variable, field, or parameter belongs to. ReSharper will switch to the declaration in source code or, for built-in types, in the Object Browser.. CamelHumps CamelHumps is a feature that identifies parts of compound names composed according to CamelCase, where each such part starts with a capital letter. By default, it works in all 'Go to' commands, namely Go To Type, Go To File, Go To File Member, and Go To Symbol, as well as in all Code Completion features. You can also apply CamelHumps to the Extend/Shrink Selection and Next/Previous Word commands. 4.0 Full Edition._5<<. Highlight Usages Highlight all the usages of a symbol within the current file. Just position the caret on any symbol usage and press Ctrl+Shift+F7. You can also highlight usages of namespace import directives and even expressions. ReSharper quickly finds and highlights usages of symbols within XAML markup as well as across languages. Find Referenced/Dependent Code ReSharper enables you to find pieces of code that depend on a project and outgoing references, with results displayed in the Find Results window. If a single usage is found, the caret moves to the corresponding location. To find dependent or referenced code, you only have to select a node in the Solution Explorer or position the caret at a container in the text editor, and choose choose Search | Find Dependent Code/Find Referenced Code on the ReSharper menu. _8<< File Structure With the File Structure window, you can see what methods, fields, classes, and regions your current C# or VB.NET code file contains, as well as navigate directly to their declarations — just press Ctrl+F11. In ASP.NET, File Structure lets you examine controls, methods, and other structural elements of a currently opened file, as well as navigate directly to their declarations. For build scripts, File Structure lets you see what properties and targets that the current script contains. Within the window, you can rearrange build script structural elements within the file with a simple drag-and-drop. File Structure also displays regions defined in the current file and allows you to arrange declarations within classes and regions according to your needs. Just drag the node to the new location. The File Structure window is fully synchronized with the editor. All changes made to a file are immediately reflected in the File Structure and vice-versa. View Recent Files Pressing Ctrl+E opens a pop-up window with the list of recently opened files, where you can select any item to navigate to. _10<<_11<<
http://www.jetbrains.com/resharper/features/features/navigation_search.html
CC-MAIN-2014-41
refinedweb
735
54.12
Editor's Note: The Following is a guest post by Visual Studio ALM MVP Jeff Bramwell For those of you familiar with Team Foundation Server (TFS), you are no doubt aware that it ships with a great deal of functionality right out of the box. From work item tracking, to version control, reporting and everything else in between, TFS can handle almost any software development lifecycle (SDLC) methodology. As extensive as TFS is, you will still, no doubt, run into scenarios that are not inherently covered. To address these unhandled scenarios, Microsoft has provided broad extensibility throughout the product. The extensibility points in TFS include the process templates, reports, build automation, and, at a more granular level, the TFS Object Model. It is the TFS Object Model that we will be digging into in this article. If you are new to the TFS object model, there are three basic steps that you must take to utilize the TFS object model: Let’s take a look at each of these steps in more detail. Before connecting to TFS, you must first decide if you need to interact with a specific TPC or with a TFS configuration server (which manages multiple TPCs). If, for example, you want to modify security settings for a TFS server instance, then you will need to connect to a TFS configuration server. If you want to retrieve a specific changeset from version control for a specific TPC, then you must first connect to the desired TPC. The TFS object model provides classes for handling both of these scenarios. In fact, the methods and functionality provided by these classes are very similar because of a common class hierarchy. The following diagram illustrates the classes typically used to connect to a TFS configuration server or TPC. The TfsConnection class provides common methods that apply to TFS configuration servers as well as TPCs such as the ability to get access to the various services provided by TFS. However, TfsConnection is an abstract class and therefore must be inherited from before it can be used. TfsConfigurationServer and TfsTeamProjectCollection both inherit from TfsConnection providing concrete classes which can be used to establish a connection to TFS. TfsConfigurationServer provides specific methods for connecting to a TFS configuration server (as the name implies) whereas TfsTeamProjectCollection provides methods for connecting to and managing a TPC. We will go into more detail in the examples below. Once you have made your initial connection to TFS, whether it’s to a TFS configuration server or a TPC, all interaction is handled via the many services provided by the TFS object model. Some of the services are specific to the type of connection you have whereas others will work with either. Here is a list of the services provided by TFS 2010 and the type of connection(s) that can be used with them: For example, if you want to query for a specific work item, you would need to utilize the WorkItemStore service. Notice that the WorkItemStore service is not available for an instance of TFS since work items are specific to a TPC. If you want to programmatically manage security, you can use either class since security can be applied at both the configuration server level as well as the TPC level. Now that you know about the different types of connections you can make to TFS and the types of services offered, let’s put it all together. The first step when creating any type of utility that is going to interact with the TFS object model is establishing a connection with TFS (whether it’s with a configuration server or TPC). With this being such an important step, there are myriad methods and helper classes that can be used to connect to TFS. A connection to TFS is typically established when creating a new instance of either TfsConfigurationServer or TfsTeamProjectCollection (there are alternatives which are not covered in this article). As such, the constructors for each of these classes have multiple overloads allowing for various ways to establish a connection. There are also various helper classes that provide alternative mechanisms for making a connection, some of which provide visual user interfaces. For example, you can: We won’t cover all of these approaches in this article. However, once you learn one variation it’s fairly simple to implement another variation. Before writing any code, you must first add the necessary references to our Visual Studio project. The references you add will directly depend upon the types of services you plan on interacting with. Most of the required assemblies that you will need to reference are located in the following folder: 32-bit à C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0 64-bit à C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ReferenceAssemblies\v2.0 To illustrate the process for setting up a connection, let’s create a simple application that will connect to a TFS configuration server as well as a specific TPC. Follow these steps to get started: using Microsoft.TeamFoundation.Client; 5. In the Click event handler, write the following code, replacing the provided URIs with ones specific to your TFS configuration: // Connect to an instance of TFS var tfs = new TfsConfigurationServer(new Uri("")); // Connect to a specific TPC var tpc = new TfsTeamProjectCollection(new Uri( "http:// tfsserver:8080/tfs/DefaultCollection")); In these two simple lines you have established a connection to your TFS configuration server as well as a specific TPC (in the example above, the default TPC is used). To obtain a reference to one of the many services provided by TFS, call the GetService<T> method provided by the TfsConnection base class where T is the data type for the type of service to retrieve. Let’s take the above example a step further and do something a little more useful such as querying the work item store. As you might have guessed, to query the work item store, you will need to make use of the WorkItemStore service. The following example illustrates the steps necessary to obtain a reference to the work item store reference and how to use that reference to query against the store. To query the work item store follow these steps: // Line 1: Get a reference to the work item store for the current TPC var workItemStore = tpc.GetService<WorkItemStore>(); // Line 2: Build our query var wiql = "SELECT [System.Id], [System.Title] FROM WorkItems WHERE ([System.TeamProject] = 'Demo') ORDER BY [System.Id]"; // Line 3: Query the work item store var workItems = workItemStore.Query(wiql); // Line 4: Display the results foreach (WorkItem workItem in workItems) { Console.WriteLine("{0} - {1}", workItem.Id, workItem.Title); } Let’s take a look at this example line-by-line. Line 1: Here, we are obtaining a reference to the work item store service provided by TFS. Specifically, this service only works with TPC references (see Table 1 above). Once you have obtained this reference, you can interact with the TPC’s work item store performing actions such as querying the stored work items, retrieving a specific work item, deleting work items, and more. Line 2: For our example to work you must provide a string containing the WIQL (work item query language) query that you wish to execute against the TPC’s work item store. WIQL is similar in concept to SQL queries that you might run against relational databases such as Microsoft SQL Server. You use WIQL to specify the work item fields you wish to return, the fields (and conditions) you wish to filter against, and the sort order. Our example above provides a simple WIQL string that returns two fields (Id and Title) for all work items belonging to the Team Project “Demo” ordering the results by Id. Line 3: This line is simply invoking the Query method of the WorkItemStore service to execute the provided WIQL query. This method will return an instance of WorkItemCollection which can be iterated through to retrieve the selected fields for each work item located. Line 4: This section of code is simply iterating through each of the work items in the results displaying the work item’s ID and Title. A more elaborate example would most likely be returning more fields and have a more complex filter. This article has only looked at one of the services provided by TFS and has exercised a fraction of that service’s capabilities. Covering all of the services and their respective features is out of the scope of this article so spend some time exploring the remaining services thinking about how they might apply to everyday scenarios in your development shop. Although the specifics for each of the services can differ greatly, the basic steps are the same – connect to TFS (a TFS configuration server or TPC), obtain references to the desired service(s), and write the code needed to solve the problem at hand. Keep in mind that Microsoft’s MSDN forums, documentation and various blogs are your key allies when writing code against any of the services provided by TFS. Check these resources out first when you start coding against a specificservice for the first time. With a little work, you can extend TFS to achieve results that may not have even been thought about when the product was first conceived or delivered. Happy coding!others.. I would like to thank you for the efforts you made in writing this post. I am hoping the same best work from you in the future as well. <a href="">garment retailing software</a>
http://blogs.msdn.com/b/mvpawardprogram/archive/2011/09/26/getting-up-and-running-with-the-tfs-2010-object-model.aspx
CC-MAIN-2014-15
refinedweb
1,598
57.61
Hi, I have to 2 namespaces in my database. One is very big with 3M records, and the other one is very small. I am using scans to read the data from the small namespace. On a cluster change event, the migration process takes about 2 minutes, because of the big namespace migration. The scans of the small namespace are critical, and must be precise, so doing them during a cluster change is not a valid option. Theoretically, I would want the migration of the small namespace to complete first, and then to scan it, but from what I see, only after the full migration process completes, the cluster is considered “stable”, and scans can work. Is there an alternative to waiting for the full migration process to complete just for the small namespace?
https://discuss.aerospike.com/t/migration-per-namespace/2258
CC-MAIN-2018-30
refinedweb
134
69.01
Set the system log priority mask #include <syslog.h> int setlogmask( int maskpri ); libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The setlogmask() function sets the log priority mask to maskpri and returns the previous mask. Calls to syslog() or vsyslog() with a priority that isn't set in maskpri are rejected. You can calculate the mask for an individual priority pri with the macro: LOG_MASK(pri); You can get the mask for all priorities up to and including toppri with the macro: LOG_UPTO(toppri); The default allows all priorities to be logged. See the syslog() function for a list of the priorities. The previous log mask level. See syslog(). POSIX 1003.1 XSI closelog(), openlog(), syslog(), vsyslog() logger, syslogd in the Utilities Reference
http://www.qnx.com/developers/docs/6.3.0SP3/neutrino/lib_ref/s/setlogmask.html
CC-MAIN-2020-45
refinedweb
135
56.86
Fundamentals of Cascades The Cascades framework lets you create UIs for the BlackBerry Application Platform with relative ease. Cascades is based on Qt 4.8, which is an application framework that uses C++. Many fundamental principles of Qt apply to Cascades as well, so it's important to understand a few key ideas to be able to work with Cascades effectively. For more information about the Qt framework, see qt-project.org/doc/qt-4.8/. Application lifecycle All Cascades applications have a similar lifecycle, which includes three possible states: running in the foreground, running in the background, and stopped. - An app is running in the foreground if it is currently visible and uses the entire screen. - An app is running in the background if it's visible and is running as an active frame, such as when a user swipes up from the bottom of the bezel to display a list of running apps. An app is also considered to be running in the background if it's not visible but has the appropriate permissions to run in the background (you'll learn about these permissions in the next section). - An app is stopped if it's not visible and doesn't have permission to run in the background. Allowing your app to run in the background Some apps that you develop interact directly with users while the app is running. For example, your app might display a UI and let a user interact with it. However, you can develop another app that doesn't require user input while the app is running. This type of app might listen for a particular event to occur on the device and then respond by notifying the user at that time. You might want this type of app to run in the background until it needs to alert the user that the event occurred. By default, your apps won't run if they're in the background and aren't visible.> When an app doesn't have permission to run in the background, the application lifecycle includes the Stopped state. An app enters this state when it's in the background and not visible. The app can't perform any operations in this state. When an app has permission to run in the background, there is no Stopped state. The app continues to run when it's in the background and not visible, and the app can continue to perform operations and process events in this state. Managing application states To help you keep track of which state your application is in, the Application class includes several signals that are emitted when the state changes. Here are a few of the most important signals for these state changes: This signal is emitted when the app is brought to the foreground and uses the entire screen. In this state, the app can use all of the resources that it requires (for example, the app isn't limited to a specific amount of memory or processor time). When your app is in this state, you can assume that the user is viewing your app and actively interacting with it. This signal is emitted when the app is sent to the background and becomes an active frame. By default, the active frame image (also called the cover) that's displayed is a scaled-down version of what the app's UI looked like when it was sent to the background. You can change the cover by using the AbstractCover class and its subclasses, along with the Application::setCover() function. When your app is in this state, it should stop any extraneous processing and use only the resources it needs to update the cover. Your app should stop other threads, such as networking and data access threads, that aren't required when running in the background. This signal is emitted when the app (and its active frame) are no longer visible. The app might enter this state if the device backlight is off or if another app is brought to the foreground. When your app is in this state and doesn't have permission to run in the background, it is stopped and won. Closing your application. This. This(). This. QML and controls. QML uses concepts such as objects, properties, and signals and slots to let objects communicate with each other. For more information about QML and how it's used in Qt, see qt-project.org/doc/qt-4.8/qdeclarativeintroduction.html. Cascades uses a modified version of QML to let you create UIs for your apps. You can start by using a set of core UI controls that's provided for you; this is the easiest and fastest way to create your first few Cascades apps. When you're more familiar with the framework, you can add functionality to create animations, handle touch events, apply text styles, and more. You can even create your own custom controls for the look and feel you want. Here's an example of a simple Cascades UI that's defined in QML. This app consists of several UI controls: a Page, Container, Button, and Label. To learn more about these controls and others that you can use, take a look at Creating User Interfaces. import bb.cascades 1.0 Page { Container { Button { text: "Click me!" } Label { text: "Here's a simple text label." } } } QML makes it easy to identify the relationships between the various components in an app. In the code sample above, the Button and Label both belong to the Container, which itself belongs to the Page. QML lets you quickly see how controls are related to each other and how they might be laid out visually in your app. The idea of one control belonging to another control (that is, being owned by another control) is important when object ownership is discussed later. Here's another important idea: almost anything you can do in QML, you can do in C++. Each Cascades control is represented by an underlying C++ class. For most properties of QML controls, such as the text property in the code sample above, there are associated C++ functions that you can use to retrieve or set the values of these properties. Here's the C++ code that's equivalent to the QML code sample above: // Create the root page and top-level container Page *root = new Page; Container *topContainer = new Container; // Create the button Button *myButton = new Button; myButton->setText("Click me!"); // Create the label Label *myLabel = new Label; myLabel->setText("Here's a simple text label."); // Add the button and label to the container topContainer->add(myButton); topContainer->add(myLabel); // Set the content of the page root->setContent(topContainer); To see an example of how to create an app using QML and C++, see Create your first app. So, when should I use QML and when should I use C++? You can use either QML or C++ to write your apps. You can even combine both languages in the same app. However, even if you choose to write your app entirely in QML, there's still some C++ code that you need to include to load the QML and get the app started. Don't worry, this C++ code is provided for you when you create a new Cascades project in the QNX Momentics IDE. To learn more about how to combine QML and C++ in your apps, see C++ and QML integration. In general, you should consider using QML to define the look and feel of your app. You can use predefined UI controls, such as buttons, text fields, labels, sliders, and drop-down menus, and you can respond to user interaction such as button clicks. Use different layouts to arrange these controls, or even create your own custom controls and add them to your layouts. With QML, you can create visual designs and test them quicker than with C++. You should consider using C++ for the business logic of your app. You can create your own C++ classes and use them to perform calculations, handle data storage operations, and so on. You can use the full capabilities of C++ to supplement the UI-related features that QML provides. By using QML for your UI and C++ for your business logic, you can change one aspect without affecting the other. For example, you can change the appearance of a list of items without worrying about how the data for the list is stored or accessed. Or, you can implement a new sorting algorithm in your app without affecting how the data is shown to users on the screen. QObject, the Qt base class All objects in Cascades are derived from the QObject class. This class is the base class of all Qt objects and provides several important features. Most notably, QObject provides support for signals and slots, which is a powerful mechanism that allows objects to communicate with each other. When something happens to an object in your app (for example, a user clicks a button), the object emits a signal. You can handle that signal and respond to the event by using a function called a slot. To learn more about signals and slots in Cascades, see Signals and slots. To learn more about QObject in Qt, see qt-project.org/doc/qt-4.8/qobject.html. This section provides information about the structure of a QObject subclass by examining parts of a C++ header file. This information is important if you want to understand the connection between QML elements (such as properties) and their C++ equivalents. This information is also important if you create your own components and want to use them with other QObject elements. You don't need to rely on C++ to create your own controls; you can create flexible, reusable UI controls using QML too. To learn how, see Custom QML components. To illustrate some of the features and requirements of a QObject in Cascades, consider the Button control. This control represents a clickable button that you can use in your apps. The header file (button.h) for this control is located in the folder where you installed the BlackBerry 10 Native SDK, in the target\qnx6\usr\include\bb\cascades\controls subfolder. Let's take a closer look at some of the code in this file and what the code means. Class declaration class QT_CASCADES_EXPORT Button : public AbstractButton { All Cascades controls inherit QObject, either directly or indirectly. The Button class inherits several intermediate classes, all of which eventually inherit QObject. Q_OBJECT macro private: Q_OBJECT To identify a class as a QObject, you need to use the Q_OBJECT macro in the private: section of the class definition. This macro is processed by the Qt meta-object compiler (MOC) and enables features such as properties, signals, and slots. To learn more about the Qt meta-object system and meta-object compiler, see qt-project.org/doc/qt-4.8/metaobjects.html. Property declaration Q_PROPERTY(QString text READ text WRITE setText RESET resetText NOTIFY textChanged FINAL) A property is a single piece of information about an object, and is declared by using the Q_PROPERTY macro. This macro allows the property to be accessible in QML. In the Q_PROPERTY, you specify the name and type of the property. You also use keywords (such as READ and WRITE) to specify the names of functions to manipulate the property value. Properties are declared in the private: section of the header file, along with the Q_OBJECT macro. As you can see above, the Button class includes the text property, which specifies the text that appears on the button. This property is a QString (the Qt representation of a text string) and has functions called text(), setText(), and resetText() to get, set, and reset the value of the property, respectively. These functions still need to be declared later; the Q_PROPERTY macro only associates them with the property. You can also specify a signal that's emitted when the value changes by using the keyword NOTIFY. To learn more about properties and the keywords you can use, see qt-project.org/doc/qt-4.8/properties.html. Function declaration public: Q_SLOT void setText(const QString & text); You can create functions for QObject classes just as you do for any other C++ classes. Notice, though, that the Q_SLOT macro is used before the function declaration here. This macro is another special element of Qt and indicates that this function is a slot. You can connect slots to signals so that when a signal is emitted, the connected slot function is called automatically. As an alternative to the Q_SLOT macro, you might see slot functions declared in a public slots: section in a header file. In Cascades, these approaches are identical. Another useful macro that you might see is Q_INVOKABLE. You can use this macro in front of a function declaration (in the same place as Q_SLOT above) to indicate that you want to be able to call the function from QML. This approach can be useful if you have a complicated operation (for example, a custom transition for your UI control) that you want to implement in C++. You can still keep the UI-related portion (calling the function at the appropriate time) in QML, but you can implement the operation in C++ any way you want. To learn more about Q_INVOKABLE, see C++ and QML integration. Signal declaration Q_SIGNALS: void textChanged(QString text); You can use the Q_SIGNALS: section to declare signals that a QObject emits when certain events occur. A Button emits the textChanged() signal when its text changes, and you can handle this event in your app if you need to. You might also see signals declared in a signals: section in a header file, which means the same thing in Cascades. Object ownership Every QObject can be related to other objects in parent/child relationships. An object can have one parent, as well as zero or more children. A parent object owns its child objects. When an object is destroyed, its children are also destroyed, so it's important to remember which objects are related to other objects in your apps. Scene graphs Cascades maintains the relationships between objects internally, and transfers ownership between objects automatically when you call functions that change object ownership. To make it easier to visualize the parent/child relationships in your app, you can use a hierarchichal structure called a scene graph. This graph shows the controls (also called nodes) in your app and how they're related to each other. You can't view the scene graph for your app in the QNX Momentics IDE or anywhere else; it's just a concept that makes it easier to visualize how Cascades keeps track of object relationships internally. A hierarchical structure (such as a scene graph) is commonly used in many types of applications, such as complex UI applications and games, and makes it easier to manage complex arrangements of components. Using a hierarchichal structure can also increase the performance of applications, which is a major reason why it was chosen as a feature for Cascades. Finally, the hierarchical nature of scene graphs fits nicely with the parent/child relationship structure of Qt objects. To learn more about this relationship structure, see qt-project.org/doc/qt-4.8/objecttrees.html. For example, consider a Container with two Button controls. Container { Button { text: "Button 1" } Button { text: "Button 2" } } Here's what the scene graph would look like for this arrangement: Scene graphs can help you keep track of how object ownership might affect various aspects of your app. For example, you can use a scene graph to visualize how touch events are delivered to different controls on the screen. To learn how scene graphs can help you handle touch events, see Touch propagation. Object ownership in QML In QML, object ownership is established automatically according to the structure of the QML code that you write. For example, consider the following code sample that creates two Button controls and adds them to a Container: Container { Button { text: "Button 1" } Button { text: "Button 2" } } The container is the parent of the buttons, and the buttons are children of the container. When the container is destroyed, both buttons are destroyed as well. Object ownership in C++ In C++, object ownership is a bit more complicated. Initial object ownership can be established either when controls are created or when they're added to other controls. Both approaches result in the same parent/child relationships, so you can choose which approach you prefer to use in your apps. For example, here's how to create the same container and buttons from the QML code sample above. This approach establishes object ownership when the buttons are created. The parent for each button is specified in the Button constructor, and each button becomes owned by the specified parent automatically when it's created. // Create the top-level container Container *topContainer = new Container; // Create the buttons, specifying the container as the parent. The container now // owns the buttons. Button *buttonOne = new Button(topContainer); Button *buttonTwo = new Button(topContainer); Here's a second approach that establishes object ownership by adding the buttons to the container explicitly. // Create the top-level container Container *topContainer = new Container; // Create the buttons Button *buttonOne = new Button; Button *buttonTwo = new Button; // Add the buttons to the container. The container now owns the buttons. topContainer->add(buttonOne); topContainer->add(buttonTwo); After object ownership is established, you can change the parent of an object by adding the object to a different parent. The object is removed from the first parent and added to the new parent, and the new parent then owns the object. Here's an example: // Create two containers Container *firstContainer = new Container; Container *secondContainer = new Container; // Create a button Button *myButton = new Button; // Add the button to the first container. The first container now owns the // button. firstContainer->add(myButton); // Add the button to the second container. The second container now owns the // button, and the first container no longer owns it. secondContainer->add(myButton); You can also remove an object from a container without specifying a new parent for the object. However, this is when things get tricky: even though the object was removed from the container, the container is still the object's parent and still owns the object. If the container is deleted, the object is deleted as well. This behavior can lead to errors in your application that might be difficult to recognize. For example, consider the following example of two buttons that are added to a container. The second button is then removed from the container, and after the button is removed, the container is deleted. Finally, the removed button's setText() function is called. // WARNING: This code will generate an error if you try to run it. // Create a container Container *myContainer = new Container; // Create two buttons and add them to the container Button *buttonOne = new Button; Button *buttonTwo = new Button; myContainer->add(buttonOne); myContainer->add(buttonTwo); // Remove the second button from the container myContainer->remove(buttonTwo); // Delete the container delete myContainer; // Attempt to set the text of the removed button buttonTwo->setText("Button Two"); Because the second button was removed from the container before the container was deleted, you might expect that when the container is deleted, the button isn't deleted and you can still access it. However, the container remains the parent of the button even after remove() is called. The second button is deleted when the container is deleted (along with the first button), so the call to setText() isn't valid because the button doesn't exist anymore. When an object is removed from its parent, or when an object is replaced by a new object (in the case of certain setter functions, such as Page::setContent()), it's removed from the visual hierarchy (that is, it's not displayed on the screen anymore). The object's parent still owns the object, but you can change the parent or delete the object at this point. If you don't change the object's parent, it's still deleted when the parent object is deleted. It's important to note that you can't change the parent of an object if the object is still part of the visual hierarchy of its parent. You need to remove it before you try to change its parent. All QObject instances include a function called setParent(), and you can use this function to change the parent of an object (when it's allowed, as described above). When you use setParent() to change an object's parent, the function doesn't add that object to the parent's visual hierarchy; you still need to add it explicitly (for example, by calling Container::add()). To prevent the error that occurred in the code sample above, you can add a call to setParent(0) after you remove an object from its parent. This way, the object isn't deleted when its former parent is deleted. ... // Remove the button from the container myContainer->remove(buttonTwo); // Reparent the button so that it's not deleted when the container is deleted buttonTwo->setParent(0); // Delete the container delete myContainer; // Attempt to set the text of the button. This time, this call will work as // expected because the button hasn't been deleted. You'd still need to add // the button to the visual hierarchy of another container (using add()) for // the button to appear on the screen. buttonTwo->setText("Button Two"); There's one important exception to the rules of object ownership. The top-level scene in your application, which is the AbstractPane object that you set as the root node using Application::setScene(), behaves differently. The application takes ownership of this AbstractPane only if the pane doesn't already have a parent. If the AbstractPane doesn't have a parent when setScene() is called, the application owns the pane and deletes it if a new scene is set. However, if the AbstractPane already has a parent, the application won't take ownership of the pane when setScene() is called. This behavior lets you switch between different scenes in your applications but ensures that for the most basic use case (an application with just a single scene), the old scene is deleted when appropriate. If you want to switch between two scenes, you should set the parents of the AbstractPane objects explicitly using setParent() before you call setScene(). Many other functions of Cascades classes change the ownership of objects. You should check the API reference for the classes and functions that you're working with to make sure that they don't change object ownership in unexpected ways. Thread support Qt provides support for threaded applications with the QThread class. The ability to create new threads is often necessary if your application contains resource-intensive processes that might otherwise block the UI thread. A QThread represents a separate thread of control in the application; it can share data with all the other threads within the application, but runs independently in the same way that a standalone application does. To facilitate communication between threads, signals and slots are fully supported. Previously, the standard method for creating a QThread was by subclassing it. Now, you should use QThread by creating a worker object that is derived from QObject and implementing a slot on that worker to handle the task. The worker should also specify a signal that is emitted when the task is finished, and an optional signal that is emitted when there's an error. class Worker : public QObject { Q_OBJECT public: Worker(); virtual ~Worker(); public slots: void process(); signals: void finished(); void error(QString err); }; After you create the worker class, you can give QThread ownership of the worker, connect the appropriate signals and slots, and start the thread. // Create a thread QThread* thread = new QThread; Worker* worker = new Worker(); // Give QThread ownership of Worker Object worker->moveToThread(thread); // Connect worker error signal to this errorHandler SLOT connect(worker, SIGNAL(error(QString)), this, SLOT(errorHandler(QString))); // Connects the thread's started() signal to the process() slot in the worker, // causing it to start connect(thread, SIGNAL(started()), worker, SLOT(process())); // Connect worker finished signal to trigger thread quit, then delete connect(worker, SIGNAL(finished()), thread, SLOT(quit())); connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater())); // Make sure the thread object is deleted after execution has finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); Using C APIs in your Cascades applications The BlackBerry 10 Native SDK includes all of the Cascades APIs, which you can use to create responsive UIs that follow the same visual style as the core BlackBerry 10 apps (such as the Calendar application and Contacts application). However, the SDK also includes many other native C APIs (also known as core native APIs) that you can use when you develop your apps. These core native APIs are designed to make it easier to port existing apps to the BlackBerry Application Platform, but you can use these APIs in your Cascades apps if you want. To learn the distinction between core native APIs and Cascades APIs, visit. The Cascades and C++ APIs provide most of the functionality that you need to create your apps. The Cascades APIs provide UI-related features, and the C++ APIs give you access to underlying device features and services, such as networking, sensors, Payment Service, and so on. However, there are some features that are available only by using core native APIs. You can learn more about these APIs and the features they provide by visiting the documentation page at. Here's a list of some of the features that are available only by using core native APIs: Audio Manager The Audio Manager APIs provide advanced audio features, such as automatic and manual routing, audio stream-type identification, concurrency policy management, and audio device monitoring. For more information, visit the multimedia documentation. Scoreloop The Scoreloop SDK contains APIs that let you integrate social gaming features into your apps. You can use Scoreloop APIs to provide features such as leaderboards, challenges, and awards and achievements. For more information, visit the Scoreloop documentation. Cryptography The BlackBerry 10 Native SDK includes C APIs that support cryptographic features, such as symmetric and asymmetric encryption, key agreement and transport, digital signatures, hash functions, and random number generation. For more information, visit the security documentation. Last modified: 2013-03-21
http://developer.blackberry.com/cascades/documentation/dev/fundamentals/index.html
CC-MAIN-2013-20
refinedweb
4,414
51.18
Hi Paul, Is there any change that the I2C bus will run on high speed at 3.4 MHz soon, for my projects it would be very nice to have! Thanks and best regards, Johan Hi Paul, Is there any change that the I2C bus will run on high speed at 3.4 MHz soon, for my projects it would be very nice to have! Thanks and best regards, Johan Two screens, a 5" with GSL1680 controller and a 7" with FT5206 controller both displays are awesome. Johan24493 Keith, please confirm if you have a E257834 display, because there are also 480x272 displays from Buydisplay. The font library is ILI9341_fonts-master and have the font Awesome. Best, Johan Hi Keith, do you have a 800x480 display? please look at the backside if it shows E257834 than you are good! Best, Johan Problem solved for this display on a Teensy4, works perfect. I made a mistake to let the display run on 5V instead of 3.3V. Best, Johan Dear group, My NHD-0420CW-Axx works perfect with a Teensy 3.2, now I changed it for a Teensy4.0 and the display is not working. Are the Teensy's not compatible. The NHD is a SPI device and... The RA8875 5" with GSL1680 controller is quite simple, build many projects with this RA8875 display. Best regards, Johan #include <SPI.h> #include <RA8875.h> #include <GSL1680.h> #define... Hereby the test sketch, know that the latest ILI9341_fonts-master must be installed. // test sketch for LolinD32 (ESP32) // Johan Holstein @2021 #include <SPI.h> #include <RA8875.h> #define... Dear group, The RA8875 can now be used also for the LolinD32(ESP32) and ESP8266 works out of the box it's not a Teensy but people must know. Works with the ILI9341 fonts as well I tried to... Hi Kurt, Wire and Wire2 works but Wire1 is failing...... I removed the Teensy from the board and connected directly with wires.... no differences. 2441324414 This was the error from Wire1.... 13:24:18.417 -> Scanning(Wire1)... 13:24:18.450 -> Unknown error at address 0x01MCR:1 MSR:2002001, MIER:0 MDER:0 MCFGR0:0 MDMR:0 MCCR0:1928373b 13:24:18.450... Hi Kurt, group, Tested the T4.1 with the scanner and Wire is ok, Wire1 not found, Wire2 is ok it seems that the T4.1 has a defect. I will order a new one. Thanks for helping! Best regards,... Hi group, The Teensy 4.1 second I2C SDA1/SCL1 bus is definitely not working , I connected several devices but nothing, however all the devices working on the first SDA0/SCL0. Did anyone... Hi Kurt, Thanks for that! I have the same problem for a display with I2C bus on a Teensy 4.1, while on SCL0 and SDA0 this works out of the box with the scanner and the device is found. On SCL1... Hi Kurt, group, Made the changes in the both files and YES now it works. Thanks a lot for helping this was really a quick solution! Best, Johan // This example demonstrates continuous... Hi all, I used here a Teensy 4.1 with a MAX31856 connected to SPI1 bus used MOSI1 pin 26, SCK1 pin 27, MISO1 pin 1 and CS1 pin 0. Also I did this as suggested by Kurt > ... Hi group, I noticed that the MAX31856 is not working on the SPI1 bus used MOSI1 pin 26, SCK1 pin 27, MISO1 pin 1 and CS1 pin 0, I need this pins because my RA8875 display is on SPI0. Is there a... Dear members, I have a problem with the awesome fonts, the #include "font_AwesomeF100.h" works perfect however when print some text then still the awesome fonts are actual. See attachment. Used... To complex for me :o Thanks anyway. Johan Hi Jurt, Thanks for the repley! I turn every char in the Liberation_mono.ttf and convert it to .c but this is very time consuming. I think there must be a easier way perhaps on pixel level... This is what I mean for curved text.21350 Hi all, For my newest power meter I like to print curved text on the display, so I like print the text in a curved position on my RA8875 display. I can change a liberation_mono.ttf say the... Hi all, There where two issues at my place first the level shifter was wrong and second I reversed TX and RX. Everything is working fine now. I feel a bit dumm and sorry for bothering the... Hi all, In my previous project with a Teensy 3.6 I used Serial port 4 at 2400 baud (Serial.begin(2400); Now I rewrite my program for a Teensy 4.1 and used Serial port 7, Serial7.begin(2400); This... Hi Paul, Thanks for coming back ... difficult to explain in a few words. My radioberry is mounted as a cape on a raspberry pi4, the rpi loads the FPGA firmware called radioberry.rbf ... Hi Paul, Kurt and Mike, I there any change that the Teensy4 can load my FPGA Cyclone CL025 ? Best, Johan Hi all, I like to start a new project for my Radioberry, the radioberry has a FPGA Cyclone CL025 and I am wondering if the Teensy4 can load the FPGA. Perhaps someone can give some... Mike, Kurt, That did the job many thanks! Was made for a small screen so some work to do for the RA8875 display. Take care, Best, Johan 19415 Hi Mike, Kurt, For me a bit difficult can you look at the code and is it possible to adjust my code with your function see below. Compile works but not the drawBitmap. Thanks. ... Hi Mile, This not that easy I suppose please read below, is it not possible to use AdafruitGFX for the drawBitmap ? // draw a button on the screen void button(but bx){ if (bx.draw ==... Hi all, For my hotplate controller and is made with a cheap RPI 9488 type display and a STM32 and works fine, I like to convert this to my fantastic RA8875 display but I use tft.drawBitmap but... @Kurt, Mike, All perfect with the new Awesome fonts, Thanks again. Best, Johan 19234 This works fine in a fresh sketch. I think I must look at my application. Thanks Mike! /* Explain the minimal setup and how to use instances... */ #include <SPI.h> #include <RA8875.h> /* @Mike, It looks like something is wrong at my site ... when running my application the Awesome fonts type font_AwesomeF100.h are scrolling over my RA8875 display. #include <font_AwesomeF100.h> No... Hi mjs, Kurt, I like to use the Awesome fonts for my RA8875 from buydisplay, I noticed that there are fonts for the ILI9341 display ... Font_Awesome_F000 and how I can use them? Thanks for helping,... Problems with the T4 and the second I2C bus, my RA8875 touchscreen works on 19/18 pins perfect. I use a FT5206 controller, but on pins 16/17 the touchscreen is not working. When I use the scanner it... Thanks guys for the new Library! Best, Johan For the Teensy 4 I saw on PRJC web page frequency input pin 22 and analog write on pin 23. I think this is not right.... on pin 8 and 9 this working, this a pity because I need pin 9 for something... Hi mjs513, Kurt, Why you not add the fonts to the RA8875/fonts dir. has that a reason? Best, Johan @Kurt, @mjs513, Best, Johan Hi Paul, Yes it compiles, now testing the stuff. Thank you like always. Best regards, Johan Perhaps nothing to do with the audio, there is something else that gives compile errors.. When compiling I get this info : /tmp/arduino_build_162599/sketch/CwDecoderLogic.h:210:42: note: in expansion of macro 'PSTR' *bp++ = MakeTableEntry(strcpy_P(fbuf, PSTR("........")), '\x7F');... The zip file with the project18460 Ok but it's a big file can I use a zip file? Hi all, I like to use my program for a Teensy 4.0 was used for a Teensy 3.2 and works. This is the code for the 3.2 but it gives compile errors on a T4 so what must be changed to get this working... Kurt, That's a pity because you design a nice board but the Teensy need also input.... the most important part is than not added. Please consider this because the new T4 has not decent A/D input. ... Hi Kurt, Can you add also one or two AD's 12 bit to the board? Best, Johan Hi Kurt, Looks great! Best, Johan
https://forum.pjrc.com/search.php?s=8c5f6b4629b4b592ddcf416b9a32fe15&searchid=6218728
CC-MAIN-2021-21
refinedweb
1,426
84.98
Hi, The API documentation for the Vector class explicitly mentions creating a Vector subclass:: "Note: To override this method in a subclass of Vector, use…" However, when I try to create a vector subclass, I encounter one of two problems: package com.ryanberdeen.soundtouch { public class FifoSampleBuffer extends Vector.<Number> { } } This compiles without error or warning using mxmlc 3.3.0. However, when loaded (in the debug player), I get the error "VerifyError: Error #1103: Class com.ryanberdeen.soundtouch::FifoSampleBuffer cannot extend final base class." Or, package com.ryanberdeen.soundtouch { public class FifoSampleBuffer extends Vector { } } This causes an error when compiling: src/com/ryanberdeen/soundtouch/FifoSampleBuffer.as(2): col: 43 Error: Base class is final. public class FifoSampleBuffer extends Vector { ^ Which are wrong? Thanks Is your project to target Flash Player 10? Project-Properties-Flex Compiler Require Flash Player version 10.0 That is likely the problem. If this post answers your question or helps, please mark it as such. I am targeting Flash 10.0. I'm only using mxmlc, not Flex Builder and I have "<target-player>10.0.0</target-player>" in my flex-config.xml. If I wasn't targeting Flash 10, I believe I would get the message "The definition of base class Vector was not found." instead of any of the error messages I described. It's a bug somewhere in Adobe-land, so file a bug and we'll figure it out. Just for yucks, try Array and see if you get the same errors. Vector should probably do what Array does Alex Harui Flex SDK Developer Adobe Systems Inc. You create a Vector subclass by doing something like: var v:Vector.<String> = new Vector.<String>(); The AsDoc should have been more clear and it looks like Vector should have been marked final, which is a bug. I filed it:
https://forums.adobe.com/thread/471443
CC-MAIN-2018-30
refinedweb
307
60.51
Installing James 3.0 With SPF Verification In this article, we will cover the installation of James Server 3.0 with Docker. We will use the cassandra-guice flavor, which ships a James server storing mailboxes in a Cassandra database and indexing them into an Elasticsearch service. The main purpose of this guide is not to replace the documentation but to show people how easily and quickly James can be installed, up and running. Installation With Docker We will directly use a Docker image from Linagora’s repository. Here is the Docker Compose file we use for this setup: We use Docker links so that James can communicate with the Cassandra and Elasticsearch containers. We also use Docker DNS helpers to ensure our container can use our DNS server, which is running on the host machine and whose configuration will be detailed in the next section. We also mount volumes in which we will place James configuration files and potential extensions jars. Traditional SMTP and IMAP ports are mapped to unprivileged and unused ports on the host. Before using docker-compose up -d to launch our James Server, we have some prior configuration work to do. How to Configure DNS Records to Use James As we are going to configure a server, we need a domain name. Moreover, as it is a mail server and because we want it to be reachable by other mail servers and by mail clients, we need DNS resolution. In particular, we need A records in order to translate domain names into IP addresses as well as an MX record, which will be used by other mail servers to reach our James instance when they have emails to relay to our users. We also need reverse DNS resolutions for our infrastructure to be trusted on the Internet. One way to manage all this is by using the BIND9 nameserver. If you do not know how to set up Bind9, please take a look at the Debian documentation. We need to add a new zone thus we will create a /etc/bind/db.test-domain.com zone configuration file to create a test-domain.com domain. The fact that this domain is only “local” (we did not register it) and already exists will require us to be even more careful during our setup. In the following snippets, we use A.B.C.D as the IP address of our host server. The above configuration is rather traditional. Apart from the A and MX records we have already mentioned, we add the classical NS record to identify our nameserver. However, this was only for forward resolution. For reverse resolution, we create another zone configuration file: As usual with reverse DNS resolution, the IP address in the PTR record needs to be written in reverse byte order. Then we need to add both zone files to our DNS configuration file which tells our DNS server that it should control and serve requests for these new domain zones. For that, add the following to /etc/bind/named.conf.local: Then, restart the bind9 daemon in order to reload the new configuration files. Also, be sure that Bind listens on your public interface (and not just on localhost for instance) and that it forwards queries it cannot answer, for instance to Google’s revolvers. Configuring James Entering our James container to modify it is not a good practice and that is not how one should use Docker. We use bind mounts instead. All James configuration files reside in the /root/conf directory of the container. With our bind mounts, we thus have to add our configuration files in $PWD/conf when we want to override the default configuration from Linagora. We will now detail a minimalist configuration of James to have it up and running. For each configuration file we need to edit, we will point out the changes made from the default configuration files you can find here. Edit domainlist.xml to change domain The domainname entry identifies the DNS namespace served by this instance of James. These domain names are used for both matcher/mailet processing and SMTP authentication to determine when an email is intended for local delivery. We thus replace james.linagora.com with james-thibaut.test-domain.com. We also remove the following lines which are causing interferences with existing deployments on our test server, especially automatic DNS resolutions of some IP addresses. <autodetect>true</autodetect> <autodetectIP>true</autodetectIP> Edit dnsservice.xml to add our DNS server We replace 62.210.16.6 by the IP address of our DNS server and remove the second entry with 8.8.8.8. Indeed, this entry is not needed since our nameserver is supposed to forward DNS queries it is unable to answer to upper-level nameservers. This also ensures that our DNS answers queries related to our test-domain.com domain name as it is only a local and non-registered one. Edit mailetcontainer.xml to change postmaster For now, we just need to edit the postmaster mail address. However, the true purpose of this file is to configure mailets. A mailet is an email processing agent. Actually, this file describes a pipeline arranged into processors, which in turn are lists of mailet/matcher pairs allowing better logical organisation. A matcher is used to implement a condition for executing a mailet. The default configuration is sufficient to obtain a basic working setup of James. We will edit it later when we configure SPF. Edit imapserver.xml, smtpserver.xml, pop3server.xml and jmap.properties We need to provide the keys we will use for TLS, through the use of a keystore. Basically, a keystore is a repository of security certificates, that can hold your keys and certificates and encrypt them all with a password. James expects a keystore to be composed of a single-element certificate chain and the corresponding private key. The password protecting the keystore is used in our imapserver.xml, smtpserver.xml, pop3server.xml and jmap.properties configuration files. In the default configuration, the password is set to “james72laBalle” and no default keystore file is shipped for obvious security reasons. In this guide, we will use a self-signed certificate but you can also install one provided by a Certificate Authority (see here for more information on how to do this). You can generate your keystore using the following command: # keytool -genkeypair -alias james -keyalg RSA -keystore $PWD/conf/keystore Warning: Do not set a different alias, i.e. keep “james” as this is hardcoded in James code. After executing this command, you will first be prompted for the keystore password. Next you will be prompted for general information about this Certificate, such as company, contact name and so on. This information may be displayed to users when importing into the certificate store of the client, therefore make sure that the information provided here matches what they will expect. Moreover, it is important that you set the Common Name (CN) to the DNS name of your James server (the one you will use to access it from your mail client, i.e. james-thibaut.test-domain.com in our case). Finally, you will be prompted for the key password, which is the password to specifically protect this newly generated private key (as opposed to any other Certificates stored in the same keystore file). Please directly type “Enter” to automatically use the same password as for the keystore, because that is what James is expecting. If everything was successful, you now have a keystore file with a Certificate that can be used by your server. Warning: You MUST have only one certificate in the keystore file used by James. You can finally replace “james72laBalle” by the password you entered for the keystore and you might also need to change the path to the keystore depending on what you did. The affected configuration files are imapserver.xml, smtpserver.xml, pop3server.xml and jmap.properties. In jmap.properties, we will also comment out the following line: jwt.publickeypem.url= Indeed, this is only required if you wish to use OAuth-like authentication (JWT stands for JSON Web Tokens) like we do with OpenPaaS. Obviously, if you need this, you should generate your own JWT public key. Do not use the one from our repository! Import elasticsearch.properties and cassandra.properties Those files are needed in order for James to be able to communicate with our Elasticsearch and Cassandra instances. There is no need to edit them thanks to the Docker links we used in our Compose file. Import mailrepositorystore.xml This file declares the file:// protocol used for storing anything other than emails. We need it because this protocol is for instance the one that was used above to define the path to our keystore. Import jmx.properties This file is needed for management of the James Server (see below). Miscellaneous logback.xmlis a place to configure the logging based on your needs. We do not deal with that in this article. - tika: Apache Tika is a powerful content-analysis toolkit which James leverages to handle attachment text extraction before indexing in Elasticsearch. This makes attachments searchable. We do not deal with that in this article. - By default, POP3 is disabled in the pop3server.xmlconfiguration file. You can of course enable it by editing the enabledattribute of the pop3serverelement. One should also notice that contrarily to the SMTP and IMAP configuration files, only one socket is declared for POP3. You can declare other ones. By default, the present one has TLS disabled. You can change this behavior to obtain a TLS or STARTTLS socket by editing the socketTLSand startTLSattributes of the TLSelement. Obviously, you cannot have both on the same socket thus you should instantiate other sockets if you want to offer your users with different choices. Take the IMAP or SMTP configuration files as examples to do so. It is now time to launch our James Server instance: # pwd && ls /home/tsautereau/james-root-docker conf docker-compose.yml extensions-jars # docker-compose up -d If you edit some configuration files after having already run the Docker instance of James, you can run docker-compose restart james and Docker Compose will restart your James Server instance. This way, you will not lose users, mailboxes or anything else stored and indexed in your Cassandra and Elasticsearch instances. Nevertheless, if you really need to start fresh and get rid of all data, you can use docker-compose down to stop and remove the three containers. Finally, if you really want to enter your James container out of curiosity, the following command can be used: # docker exec -i -t james-thibaut /bin/bash Managing James Server James Server is managed using the james-cli command-line client. The -p option in the following commands corresponds to the JMX agent port number and this is why we needed to import the jmx.properties file before. Let’s now create a James domain corresponding to the one we previously set up in our nameserver as well as a user: # alias james-thibaut-cli="docker exec james-thibaut \ > java -jar /root/james-cli.jar \ > -h 127.0.0.1 -p 9999" # james-thibaut-cli AddDomain test-domain.com AddDomain command executed successfully in 159 ms. # james-thibaut-cli AddUser tsautereau@test-domain.com tototo AddUser command executed successfully in 160 ms. Consequently, the username to use in our email client will be tsautereau@test-domain.com and the password will be tototo. A comprehensive list of all available management commands is available here. Verifying a TLS-enabled James Server Ensuring that our TLS setup is working is obviously a good practice in terms of security. Both of the following commands should establish a connection (meaning that you should obtain a prompt with the James server greeting) because they use non-TLS ports: # telnet 127.0.0.1 3025 # telnet 127.0.0.1 3587 However, as port 465 (mapped to port 3465 on our host) corresponds to SMTPS and TLS is thus expected, telnet 127.0.0.1 3465 should hang and eventually timeout. We can verify that TLS is working fine using the following command, which should print our certificate information and establish a connection: # openssl s_client -quiet -connect localhost:3465 Finally, in the case of STARTTLS on port 3587, you can check with the following command: # openssl s_client -quiet -connect localhost:3587 -starttls smtp Configuration of the Mail User Agent (Thunderbird) First, you should add your nameserver’s IP address in the /etc/resolv.conf file of your test machine (the one you will launch Thunderbird on), before any other nameserver directive to ensure correct DNS resolution. In this guide, we use Thunderbird 52.3.0. After launching it, go to Accounts -> Create a new account: Email -> Skip this and use my existing email. Enter your name (it will be used as the From: header in emails you send), email address (tsautereau@test-domain.com in our case) and password (tototo in our case) and then click on Continue. Thunderbird usually detects other parameters automatically, especially IMAP and SMTP port numbers. However, since we used different ones due to our container setup, we need to click on Manual config. For instance, to use STARTTLS, set the IMAP port to 3143 and the SMTP port to 3587. As Thunderbird does not know about the self-signed certificate you generated from your email server, you will be asked to add a security exception. Thunderbird will then try to authenticate and connect to your James instance. You can try creating another user and send emails between these two accounts. Thunderbird will probably ask you for a second Security Exception when connecting to the SMTP server to send the first email. The sending will fail before you have the time to click to validate the Security Exception. But just do it then and retry sending the email, it should work. You can try creating folders (i.e. mailboxes) from within Thunderbird and check that they were created on the James server (and inversely): # james-thibaut-cli ListUserMailboxes tsautereau@test-domain.com INBOX INBOX.Test Sent Trash ListUserMailboxes command executed successfully in 144 ms. How To Set Up The Sender Policy Framework (SPF) The Sender Policy Framework (SPF) is an open standard specifying a technical method to prevent sender address forgery. More precisely, SPF protects the envelope sender address, which is used for the delivery of messages. It allows the owner of a domain to specify their mail sending policy, e.g. which mail servers they use to send emails from their domain. To correctly configure SPF for your domain, you need to answer the following questions: - From what server or servers will email from my domain originate? In our case, we only want our James Server to be able to send emails from our domain. - How do you want illegitimate email to be handled? As a reminder, -allis an SPF fail and usually means dropping such emails, whereas ~allis an SPF softfail and traditionally means accepting but marking them. Therefore, we add the following DNS records to our db.test-domain.com zone file: @ IN TXT “v=spf1 +a:james-thibaut.test-domain.com -all” @ IN SPF “v=spf1 +a:james-thibaut.test-domain.com -all” In James, we use jSPF. It is a Java implementation of the SPF standard. This only requires setting up a new mailet in the mailetcontainer.xml configuration file because jSPF is already included in the James Server project. However, we are also going to create a new processor called SPFProcessor. It will handle emails after the root processor but before the transport processor. Moreover, we do not need to perform an SPF check or take a decision if the sender is authenticated or is a local user, because we already trust him. In all other cases, we add a SPF header using the SPF mailet. Then we need to take a decision about incoming emails. We use the HasMailAttributeWithValue matcher which has seven possible values to handle in the case of SPF: permerror, temperror, none, pass, neutral, fail and softfail. What action you choose for each of these values depends on what you want to do. In our case, we redirect SPF errors and fails to the error processor, whereas all other cases lead directly to the transport processor for further normal processing. We are rather tolerant since we authorize softfails. Here is the resulting processor: Notice that we edited the root processor to have it redirect to the SPFProcessor processor instead of the transport processor. Although every single email should match one of the seven cases, the SPF mailet could change some day and for instance introduce new attributes. Therefore, we also added a matcher at the end of the SPFProcessor which will catch unmatching emails and use the LogMessage mailet to log the fact that something went wrong with our SPF configuration. You can now send e-mails between your local email accounts and check that no SPF header has been added since you are both an authenticated and local user. You can also check that no Unknown SPF result log was generated in the output of the docker-compose logs james command. Conclusion In this article, we explained how to obtain a basic but fully operational installation of James Server 3.0. We managed to send and receive emails between local users and we set up SPF verification. The next step could be to setup DKIM using the jDKIM Java library, which is also part of the James Project but in a different way, making it a bit harder to use. You can also dive more into the mailetcontainer.xml configuration file to customize your processors, mailets and matchers, depending on your objectives such as whether you want to use James as a Mail Transfer Agent (i.e. an MX server) or as a Mail Delivery Agent (e.g. an IMAP server). Finally, now that you are running your own James Server, you can learn more about the James Project on our website. Also, feel free to join our community on GitHub and start contributing!
https://medium.com/linagora-engineering/installing-james-3-0-with-spf-verification-421b26b92f11
CC-MAIN-2018-09
refinedweb
3,030
63.59
Re: Looking for Design Input - From: "Edward Stow" <ed.stow@xxxxxxxxx> - Date: 7 Mar 2007 02:19:08 -0800 On Mar 7, 9:50 am, "Malbs" <ssefl...@xxxxxxxxxxxxx> wrote: I have a probelm I'm trying to solve. I was trying to thing of the same problem in a different domain to discover if maybe there is some sort of pattern I can apply... I was struggling to come up with the same design problem in a different domain when it hit me. The common mailing list. think of a simple mailing list system design. Sorry to make people think in text, but here we go. MailingList addMember: aMember - adds a member removeMember: aMember - removes a member includesMember: aMember - tests for membership. selectMembers: aBlock MailingList class repository ^Repository ifNil: [ Repository := OrderedCollection new ] Member username - gets and sets username ivar password - gets and sets password ivar subscriptions - returns a list of all the subscribed mailing lists. ^MailingList repository select: [ :ea | ea includesMember: self ] The design problem is, that for each subscription a Member may have different preferences. In one mailing list they may want a digest mode, however in another mailing list they may prefer a threaded or per-message mode. So I started thinking.. is it a decorator pattern I wanted to use. Wrap up the Member object in a new object which also contains the Options for the member, and delegated all of the Member protocols to its internal Member object... I didn't really feel like that was the correct pattern to apply here.. so this is what I came up with and I'm wondering what other people think of it from an OO/Smalltalk/Eww Yuck point of view Created a new class: MailingListOptions initializeWithMember: aMember mailinglist: aMailingList - Private, sets the two ivars member - returns the member this is for mailinglist - returns the mailing list its for beDigest beStandard isDigest isStandard then we modify the add and remove methods of MailingList addMember: aMember (self includesMember: aMember) ifTrue: [ ^aMember ] memberOptions at: aMember put: (MailingListOptions member: aMember mailinglist: self) members add: aMember. removeMember: aMember (self includesMember: aMember) ifFalse: [ ^aMember ] memberOptions removeKey: aMember. members remove: aMember. and introduce a new method to get the options: optionsForMember: aMember ^memberOptions at: aMember so now a person can go to their subscription of PHP-Dev, and: (mailinglist optionsForMember: me) beDigest. then when it comes time to generate the digest email: mailinglist selectMembers: [ :ea | (mailinglist optionsForMember: ea) isDigest ]. gets me a list of members who have set their preference to digest mode. Now I realise this doesn't cover such things as tracking when digest mode was turned on, so as to not send messages the user has already received in standard mode, but thats beyond the scope of this :P So what I'm interested in? Has anyone else had to implement a similar design summarised with: A Member can belong to many MailingLists, and that person may have different MailingListOptions for each MailingList. And how did you do it? Am I on the right track, wrong track? I don't know any Smalltalkers IRL that I can talk to about this. Hell I don't know anyone who really knows OO that I can talk to about this. Everyone I work with uses classes as a way to have c code with namespaces. This seems a lot of work to only records member options: Why not: MailingList ivar memberOptions a Dictionary key - member value - #digest || #normal Appropiate methods to set and retrieve the member state would need to be added. I would make the Repository a class even if you only need a singleton. To further elaboration the design you need to consider how you handle the message forwarding operations. -- . - References: - Looking for Design Input - From: Malbs - Prev by Date: Re: D6 Visual Designer align commands are unintuitive - Next by Date: Re: Looking for Design Input - Previous by thread: Looking for Design Input - Next by thread: Re: Looking for Design Input - Index(es):
http://newsgroups.derkeiler.com/Archive/Comp/comp.lang.smalltalk.dolphin/2007-03/msg00055.html
crawl-002
refinedweb
662
60.14
Hi, I have a "simple" problem with mpl, but didn't find a way to solve it so far. Let's say I have a set of three 2Darrays I would like to : - load using imshow - then connect to the mouse click event and add all X and Y coordinates obtained when clicking (so each time I click, I'll get xc += event.x for example) and PAUSE the program until I get a click on the right button of the mouse - when I click on the right button of the mouse, I want the program to go on and load the second data array - ... and continue until all data arrays have been looked at in that way. So in principle it would look like the script below. But of course this DOES NOT WORK!!! So I would welcome any suggestion of how to solve this problem.... Eric ··· import numpy as num class offset: def __init__(self) : self.xc = 0. self.yc = 0. self.stay = 1 def on_click(self, event) : if event.button == 1: if event.inaxes is not None: self.xc += event.xdata self.yc += event.ydata elif event.button == 3: self.stay = 0 data1 = num.random.rand(10,10) data2 = num.random.rand(10,10) data3 = num.random.rand(10,10) alldata = [data1, data2, data3] for i in range(len(alldata)) : imshow(alldata[i]) newoffset = offset() binding = connect('button_press_event', newoffset.on_click) while newoffset.stay : pass disconnect(binding) print newoffset.xc, newoffset.yc
https://discourse.matplotlib.org/t/how-to-pause-a-program-while-button-is-not-3/7745
CC-MAIN-2022-21
refinedweb
244
68.97
reason being, I've needed pointer simulation for address verification for quite a while now... heh so what methods would I need and how would I need to build the __init__() method?? here's what I have so far: (originally started as a file class) - Code: Select all from array import array as _arr #private class MEM: def __init__(this): this.data = _arr('B',[]) #fastest possible safe array for data management this.size = 0 this.offset = 0 def preread(this,length=this.size): return this.data[this.offset:this.offset+length] def read(this,length=this.size): return this.data[this.offset:this.offset+length]; this.offset+=length def alloc(this,size): pass #save up some memory before writing (speed things up a bit) def write(this,char=''): pass why the array module? aside from it being fastest array I've used yet (including NumPy), I find it better to parse both types of file-data as 8bit ints the only faster thing I know of is a dictionary, but that's unsafe as it eats a massive amount of memory for a large amount of data anyways, if there's anything I don't know, please tell me (if I already know it, tell me anyways) if anyone knows of any previous topics here, or other information on something similar to this, please post a link. OT: /new idea >.> I should build a script that tests each type of array with [].append(v) and []+=[v] (who's not to say my previous tests havn't changed over time as Py27 evolved)
http://www.python-forum.org/viewtopic.php?p=13505
CC-MAIN-2017-13
refinedweb
262
72.36
Paul D. Smith wrote: %% Dan Kegel <address@hidden> writes: Martin> Hi, When I type make clean, make rebuilds the dependency Martin> files before executing the commands in the clean target. Martin> I follow the methodology described at the paulandlesley Martin> site. >>> ifneq ($(MAKECMDGOALS),clean) >>> -include $(deps) >>> endif >> And it works very well for my situation. Thanks a lot! dk> Ooh, ooh, ooh. Thanks! Not to be a whiner or anything, but this _exact_ example is in the GNU make manual... :). It's hard to find, though. It ought to be linked to from the section "Rules for Cleaning the Directory". - Dan
http://lists.gnu.org/archive/html/help-make/2003-10/msg00025.html
CC-MAIN-2017-17
refinedweb
101
75.91
chrishkchris opened a new pull request #500: SINGA-478 (Python 3 uses __itruediv__ instead of __idiv__) URL: We need to add `__itruediv__` for python 3 in tensor.py because the original `__idiv__` is not supported by python 3 anymore. To understand the problem, let's study the following code first: ``` from singa import tensor from singa import device import numpy as np Y = np.ones(shape=[10],dtype=np.float32) * 10.0 y = tensor.from_numpy(Y) y.to_device(device.get_default_device()) def divide(y): y /= 10 divide(y) print(tensor.to_numpy(y)) ``` Without adding the `__itruediv__` function, the result is as follows, which means that the /= operation is not in place operation: `[10. 10. 10. 10. 10. 10. 10. 10. 10. 10.]` After adding the _itruediv_ function, the result is as follows, which means that the /= operation is in place operation: `[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]` This is because the `__idiv__` operation is for python 2, while `__itruediv__` is for python 3. Therefore, if we do not add the `__itruediv__` operator in tensor.py, it just uses a default operation which is not in place operation. Meanwhile, I am not sure if I also need to add `__truediv__` for python 3 to acts as `__div__` for python
http://mail-archives.apache.org/mod_mbox/singa-dev/201908.mbox/%3C156525759052.23615.16884239318598379913.gitbox@gitbox.apache.org%3E
CC-MAIN-2021-31
refinedweb
211
62.38
#include <sys/ps.h> int w_getpsent(int processPos, struct w_psproc *bufferArea, size_t bufferLength); w_getpsent gets information about all processes for which the caller is authorized. The arguments to the w_getpsent function are: processPos 0representing the first process. You should call w_getpsentfrom within a loop. On the first call, pass a 0as the processPosargument, and w_getpsentwill return the position value of the next process that the calling process has access to. This value is then used as the processPosargument for the next call. Continue to loop until a 0is returned. bufferArea bufferLength The information about a process is stored in a w_psproc structure, which is declared in <sys/ps.h> . You may access the following elements of this structure to obtain process information: unsigned int ps_state pid_t ps_pid pid_t ps_ppid pid_t ps_sid pid_t ps_pgpid pid_t ps_fgpid uid_t ps_euid uid_t ps_ruid uid_t ps_suid gid_t ps_egid gid_t ps_rgid gid_t ps_sgid long ps_size time_t ps_starttime clock_t ps_usertime clock_t ps_systime int ps_conttylen char *ps_conttyptr int ps_pathlen char *ps_pathptr int ps_cmdlen char *ps_cmdptr If successful, w_getpsent returns an integer that identifies the next process that the calling process has access to. A 0 is returned to indicate that there are no more accessible processes. A -1 is returned if the call to w_getpsent is unsuccessful. The w_getpsent function may be useful in USS applications; however, it is not defined by the POSIX.1 standard and should not be used in portable applications. The following example illustrates the use of w_getpsent to obtain process information: #include <sys/types.h> #include <sys/ps.h> #include <stdio.h> #include <stdlib.h> #define MAX_CHAR 256 main() { int processNum = 0; W_PSPROC workArea; /* Initialize work area. */ memset(&workArea, 0, sizeof(workArea)); /* Allocate memory for character strings. */ if ((workArea.ps_conttyptr = (char *) malloc(MAX_CHAR)) == NULL) { perror("ps_conttyptr memory allocation error"); abort(); } else workArea.ps_conttylen = MAX_CHAR; if ((workArea.ps_pathptr = (char *) malloc(MAX_CHAR)) == NULL) { perror("ps_pathptr memory allocation error"); abort(); } else workArea.ps_pathlen = MAX_CHAR; if ((workArea.ps_cmdptr = (char *) malloc(MAX_CHAR)) == NULL) { perror("ps_cmdptr memory allocation error"); abort(); } else workArea.ps_cmdlen = MAX_CHAR; /* Get process information. */ do { processNum = w_getpsent(processNum, &workArea, sizeof(workArea)); if (processNum == -1) perror("error in w_getpsent"); else { printf("process number = %dn", processNum); printf("process ID = %10dn", workArea.ps_pid); printf("User ID = %8unn", workArea.ps_ruid); } } while (processNum != 0 && processNum != 1); } Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.
http://support.sas.com/documentation/onlinedoc/sasc/doc750/html/lr2/zid-9987.htm
crawl-003
refinedweb
387
51.04
Even the basics of the Stack and Heap, types of variables and why some variables work as they do. There are two places the .NET framework stores items in memory as your code executes. If you are not yet familiar with them, let me introduce you to the Stack and the Heap. Both the Stack and Heap help us run our code. They reside in the operating memory on our machine and contain the pieces of information we need to make it all happen. Stack vs. Heap: What's the difference? The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called"). The Heap is more or less responsible for keeping track of our objects (our data, well... most of it; we'll get to that later).. The picture above, while not really a true representation of what's happening in memory, helps us distinguish a Stack from a Heap. The Stack is self-maintaining, meaning that it basically takes care of its own memory management. When the top box is no longer used, it's thrown out. The Heap, on the other hand, must worry about Garbage collection (GC), which deals with how to keep the Heap clean (no one wants dirty laundry laying around, it stinks!). What goes on the Stack and Heap? We have four main types of things we'll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions. Value Types: In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType): Reference Types: All the "things" declared with the types in this list are Reference types (and inherit from System.Object, except, of course, for object which is the System.Object object): Pointers: The third type of "thing" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type, it means we access it through a Pointer. A Pointer is a chunk of space in memory that points to another space in memory. A Pointer takes up space just like any other thing that we're putting in the Stack and Heap and its value is either a memory address or null. Instructions: You'll see how the "Instructions" work later in this article... How is it decided what goes where? (Huh?) Ok, one last thing and we'll get to the fun stuff. Here are our two golden rules: The Stack, as we mentioned earlier, is responsible for keeping track of where each thread is during the execution of our code (or what's been called). You can think of it as a thread "state" and each thread has its own Stack. When our code makes a call to execute a method the thread starts executing the instructions that have been JIT compiled and live on the method table, it also puts the method's parameters on the thread Stack. Then, as we go through the code and run into variables within the method, they are placed on top of the Stack. This will be easiest to understand with an example. Take the following method: public int AddFive(int pValue) { int result; result = pValue + 5; return result; } Here's what happens at the very top of the Stack. Keep in mind that what we are looking at is placed on top of many other items already living in the Stack: Once we start executing the method, the method's parameters are placed on the Stack (we'll talk more about passing parameters later). NOTE : the method does not live on the stack and is illustrated just for reference. is returned. And all memory allocated on the Stack is cleaned up by moving a pointer to the available memory address where AddFive() started and we go down to the previous method on the stack (not seen here). In this example, our "result" variable is placed on the stack. As a matter of fact, every time a Value Type is declared within the body of a method, it will be placed on the stack. Now, Value Types are also sometimes placed on the Heap. Remember the rule, Value Types always go where they were declared? Well, if a Value Type is declared outside of a method, but inside a Reference Type then it will be placed within the Reference Type on the Heap. Here's another example. If we have the following MyInt class (which is a Reference Type because it is a class): public class MyInt { public int MyValue; } and the following method is executing: public MyInt AddFive(int pValue) { MyInt result = new MyInt(); result.MyValue = pValue + 5; return result; } Then just as before, the thread starts executing the method and its parameters are placed on sthe thread's stack. Now is when it gets interesting. Because MyInt is a Reference Type, it is placed on the Heap and referenced by a Pointer on the Stack. After AddFive() is finished executing (like in the first example), and we are cleaning up... we're left with an orphaned MyInt in the Heap (there is no longer anyone in the Stack standing around pointing to MyInt)! This is where the Garbage Collection (GC) comes into play. Once our program reaches a certain memory threshold and we need more Heap space, our GC will kick off. The GC will stop all running threads (a FULL STOP), find all objects in the Heap that are not being accessed by the main program and delete them. The GC will then reorganize all the objects left in the Heap to make space and adjust all the Pointers to these objects in both the Stack and the Heap. As you can imagine, this can be quite expensive in terms of performance, so now you can see why it can be important to pay attention to what's in the Stack and Heap when trying to write high-performance code. Ok, that's great, but how does it really affect me? Good question. When we are using Reference Types, we're dealing with Pointers to the type, not the thing itself. When we're using Value Types, we're using the thing itself. Clear as mud, right? Again, this is best described by example. If we execute the following method: public int ReturnValue() { int x = new int(); x = 3; int y = new int(); y = x; y = 4; return x; } We'll get the value 3. Simple enough, right? However, if we are using the MyInt class from before: public class MyInt { public int MyValue; } and we are executing the following method: public int ReturnValue2() { MyInt x = new MyInt(); x.MyValue = 3; MyInt y = new MyInt(); y = x; y.MyValue = 4; return x.MyValue; } What do we get? 4! Why?... How does x.MyValue get to be 4? Take a look at what we're doing and see if it makes sense: In the first example everything goes as planned: public int ReturnValue() { int x = 3; int y = x; y = 4; return x; } In the next example, we don't get "3" because both variables "x" and "y" point to the same object in the Heap. public int ReturnValue2() { MyInt x; x.MyValue = 3; MyInt y; y = x; y.MyValue = 4; return x.MyValue; } Hopefully this gives you a better understanding of a basic difference between Value Type and Reference Type variables in C# and a basic understanding of what a Pointer is and when it is used. In the next part of this series, we'll get further into memory management and specifically talk about method parameters. For now... Happy coding. Part I | Part II | Part III | Part IV ©2014 C# Corner. All contents are copyright of their authors.
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_memory01122006130034PM/csharp_memory.aspx?ArticleID=9adb0e3c-b3f6-40b5-98b5-413b6d348b91
CC-MAIN-2014-42
refinedweb
1,345
70.73
Story of Blind SQL with a typo error. This is one of my findings back in last year when I was testing a back-office application of a big company. As the application was on the old code base and equipped with fewer security features, I found a lot of bugs in my first sprint. Which I duly submitted to the company. Seeing the volume of issues from sqli to RCE company decided to update their framework with a newer code base and asked me to pause my testing on that. As the application was wide they worked on a modular basis and asked me to carry my test the same before deployment. In this article, I would just like to highlight one of the bugs regarding the SQL-injection, where the developer goofed up in the implementation of secure code and left the application vulnerable. Though I cant highlight the domain name or paste a screenshot of the original application due to privacy policy. One more time I have come up with a similar application(coded for this writeup) only. In one of the page application was taking input from user and was giving the output to the user back. Minus CSS/few more output application was more or less like the screenshot above Whenever a user used to supply a product ID, it would give relevant information about the same. so if you have seen the video you can see that on supplying quotes or SQL injection statements it was blocking our request.so I thought that they have patched the endpoints against SQL.nothing to test. Since I was nothing to report anything new to the company on this module I thought to check the defense in depth. I took the application to burp and started fiddling since I had a background of my last test and I had kept the data from my last test. I thought to build up from there. I tried encoding , double encoding, and , or ,time-based everything nothing worked Even some weird stuff I also tried like converting the decimal to ASCII as application built on PHP so took a chance but nothing Till now you just saw everything I tried to exploit the scenarios but nothing I got now before I was just wrapping up my thing just had a typo error and I got a result of my desire. “AND” keyword was not filtred proper and was left to case-sensitive attack, though the same has been well implemented in other keywords and I found my blind SQL injection time-based. I quickly bring that in the notice to the company they quickly rectified the same. Now just using my old data in hand all I needed to craft and check the same with query id=2 AND (select sleep(2) from {injection_word_list _for tables}) &submit=product_listing Which can be done using intruder or any script easily. import requests def deciding_table(injected): url='' headers={'Host': 'localhost:8181',\ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0',\ 'Cookie': 'PHPSESSID=ifpp57n3m4q943qmf6j2i23bq0',\ 'Content-Type': 'application/x-www-form-urlencoded' } data={'id':'2 anD (select sleep(2) from '+injected+')','submit':'product_listing'} print data r=requests.post(url=url,headers=headers,data=data) if (r.elapsed.total_seconds()>2): print "valid table name :" +injected exit() def readtablename(): path=r'D:\wordlist\databaselist.txt' with open(path) as fh: for line in fh: line=line.strip() deciding_table(str(line)) readtablename() P.S: I have changed the name of the table and various other parameters in order to hide the actual. Takeaway from here: Never take anything as granted some time little typo in code can make your day as a hunter. if you like the article don't forget to share and clap.
https://medium.com/@amyrahm786/story-of-blind-sql-with-a-typo-error-43a21913c8d
CC-MAIN-2021-21
refinedweb
637
62.17
Q-learning with Neural Networks Learning Gridworld with Q-learning¶ Introduction¶ We've finally made it. We've made it to what we've all been waiting for, Q-learning with neural networks. Since I'm sure a lot of people didn't follow parts 1 and 2 because they were kind of boring, I will attempt to make this post relatively (but not completely) self-contained. In this post, we will dive into using Q-learning to train an agent (player) how to play Gridworld. Gridworld is a simple text based game in which there is a 4x4 grid of tiles and 4 objects placed therein: a player, pit, goal, and a wall. The player can move up/down/left/right ($a \in A \{up,down,left,right\}$) and the point of the game is to get to the goal where the player will receive a numerical reward. Unfortunately, we have to avoid a pit, because if we land on the pit we are penalized with a negative 'reward'. As if our task wasn't difficult enough, there's also a wall that can block the player's path (but it offers no reward or penalty). Quick Review of Terms and Concepts (skip if you followed parts 1 & 2)¶ A state is all the information necessary (e.g. pixel data in a game) to make a decision that you expect will take you to a new (higher value) state. The high level function of reinforcement learning is to learn the values of states or state-action pairs (the value of taking action $a$ given we're in state $s$). The value is some notion of how "good" that state or action is. Generally this is a function of rewards received now or in the future as a result of taking some action or being in some state. A policy, denoted $\pi$, is the specific strategy we take in order to get into high value states or take high value actions to maximize our rewards over time. For example, a policy in blackjack might be to always hit until we have 19. We denote a function, $\pi(s)$ that accepts a state $s$ and returns the action to be taken. Generally $\pi(s)$ as a function just evaluates the value of all possible actions given the state $s$ and returns the highest value action. This will result in a specific policy $\pi$ that may change over time as we improve our value estimates. We call the function that accepts a state $s$ and returns the value of that state $v_{\pi}(s)$. This is the value function. Similarly, there is an action-value function $Q(s, a)$ that accepts a state $s$ and an action $a$ and returns the value of taking that action given that state. Some RL algorithms or implementations will use one or the other. Importantly, if we base our algorithm on learning state-values (as opposed to action-values), we must keep in mind that the value of a state depends completely on our policy $\pi$. Using blackjack as an example, if we're in the state of having a card total of 20, and have two possible actions, hit or stay, the value of this state is only high if our policy says to stay when we have 20. If our policy said to hit when we have 20, we would probably bust and lose the game, thus the value of that state would be low. More formally, the value of a state is equivalent to the value of the highest action taken in that state. What is Q-learning?¶ Q-learning, like virtually all RL methods, is one type of algorithm used to calculate state-action values. It falls under the class of temporal difference (TD) algorithms, which suggests that time differences between actions taken and rewards received are involved. In part 2 where we used a Monte Carlo method to learn to play blackjack, we had to wait until the end of a game (episode) to update our state-action values. With TD algorithms, we make updates after every action taken. In most cases, that makes more sense. We make a prediction (based on previous experience), take an action based on that prediction, receive a reward and then update our prediction. (Btw: Don't confuse the "Q" in Q-learning with the $Q$ function we've discussed in the previous parts. The $Q$ function is always the name of the function that accepts states and actions and spits out the value of that state-action pair. RL methods involve a $Q$ function but aren't necessarily Q-learning algorithms.) Here's the tabular Q-learning update rule: $$Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha[R_{t+1} + \gamma maxQ(S_{t+1}, a_{t+1}) - Q(S_t, A_t)]$$ So, like Monte Carlo, we could have a table that stores the Q-value for every possible state-action pair and iteratively update this table as we play games. Our policy $\pi$ would be based on choosing the action with the highest Q value for that given state. But we're done with tables. This is 2015, we have GPUs and stuff. Well, as I alluded to in part 2, our $Q(s,a)$ function doesn't have to just be a lookup table. In fact, in most interesting problems, our state-action space is much too large to store in a table. Imagine a very simplified game of Pacman. If we implement it as a graphics-based game, the state would be the raw pixel data. In a tabular method, if the pixel data changes by just a single pixel, we have to store that as a completely separate entry in the table. Obviously that's silly and wasteful. What we need is some way to generalize and pattern match between states. We need our algorithm to say "the value of these kind of states is X" rather than "the value of this exact, super specific state is X." That's where neural networks come in. Or any other type of function approximator, even a simple linear model. We can use a neural network, instead of a lookup table, as our $Q(s,a)$ function. Just like before, it will accept a state and an action and spit out the value of that state-action. Importantly, however, unlike a lookup table, a neural network also has a bunch of parameters associated with it. These are the weights. So our $Q$ function actually looks like this: $Q(s, a, \theta)$ where $\theta$ is a vector of parameters. And instead of iteratively updating values in a table, we will iteratively update the $\theta$ parameters of our neural network so that it learns to provide us with better estimates of state-action values. Of course we can use gradient descent (backpropagation) to train our $Q$ neural network just like any other neural network. But what's our target y vector (expected output vector)? Since the net is not a table, we don't use the formula shown above, our target is simply: $r_{t+1} + \gamma * maxQ(s', a')$ for the state-action that just happened. $\gamma$ is a parameter $0\rightarrow1$ that is called the discount factor. Basically it determines how much each future reward is taken into consideration for updating our Q-value. If $\gamma$ is close to 0, we heavily discount future rewards and thus mostly care about immediate rewards. $s'$ refers to the new state after having taken action $a$ and $a'$ refers to the next actions possible in this new state. So $maxQ(s', a')$ means we calculate all the Q-values for each state-action pair in the new state, and take the maximium value to use in our new value update. (Note I may use $s' \text{ and } a'$ interchangeably with $s_{t+1} \text{ and } a_{t+1}$.) One important note: our reward update for every state-action pair is $r_{t+1} + \gamma*maxQ(s_{t+1}, a)$ except when the state $s'$ is a terminal state. When we've reached a terminal state, the reward update is simply $r_{t+1}$. A terminal state is the last state in an episode. In our case, there are 2 terminal states: the state where the player fell into the pit (and receives -10) and the state where the player has reached the goal (and receives +10). Any other state is non-terminal and the game is still in progress. There are two keywords I need to mention as well: on-policy and off-policy methods. In on-policy methods we iteratively learn about state values at the same time that we improve our policy. In other words, the updates to our state values depend on the policy. In contrast, off-policy methods do not depend on the policy to update the value function. Q-learning is an off-policy method. It's advantageous because with off-policy methods, we can follow one policy while learning about another. For example, with Q-learning, we could always take completely random actions and yet we would still learn about another policy function of taking the best actions in every state. If there's ever a $\pi$ referenced in the value update part of the algorithm then it's an on-policy method. Gridworld Details¶ Before we get too deep into the neural network Q-learning stuff, let's discuss the Gridworld game implementation that we're using as our toy problem. We're going to implement 3 variants of the game in order of increasing difficulty. The first version will initialize a grid in exactly the same way each time. That is, every new game starts with the player (P), goal (+), pit (-), and wall (W) in exactly the same positions. Thus the algorithm just needs to learn how to take the player from a known starting position to a known end position without hitting the pit, which gives out negative rewards. The second implementation is slightly more difficult. The goal, pit and wall will always be initialized in the same positions, but the player will be placed randomly on the grid on each new game. The third implementation is the most difficult to learn, and that's where all elements are randomly placed on the grid each game. Let's get to coding. import numpy as np def randPair(s,e): return np.random.randint(s,e), np.random.randint(s,e) #finds an array in the "depth" dimension of the grid def findLoc(state, obj): for i in range(0,4): for j in range(0,4): if (state[i,j] == obj).all(): return i,j #Initialize stationary grid, all items are placed deterministically def initGrid(): state = np.zeros((4,4,4)) #place player state[0,1] = np.array([0,0,0,1]) #place wall state[2,2] = np.array([0,0,1,0]) #place pit state[1,1] = np.array([0,1,0,0]) #place goal state[3,3] = np.array([1,0,0,0]) return state #Initialize player in random location, but keep wall, goal and pit stationary def initGridPlayer(): state = np.zeros((4,4,4)) #place player state[randPair(0,4)] = np.array([0,0,0,1]) #place wall state[2,2] = np.array([0,0,1,0]) #place pit state[1,1] = np.array([0,1,0,0]) #place goal state[1,2] = np.array([1,0,0,0]) a = findLoc(state, np.array([0,0,0,1])) #find grid position of player (agent) w = findLoc(state, np.array([0,0,1,0])) #find wall g = findLoc(state, np.array([1,0,0,0])) #find goal p = findLoc(state, np.array([0,1,0,0])) #find pit if (not a or not w or not g or not p): #print('Invalid grid. Rebuilding..') return initGridPlayer() return state #Initialize grid so that goal, pit, wall, player are all randomly placed def initGridRand(): state = np.zeros((4,4,4)) #place player state[randPair(0,4)] = np.array([0,0,0,1]) #place wall state[randPair(0,4)] = np.array([0,0,1,0]) #place pit state[randPair(0,4)] = np.array([0,1,0,0]) #place goal state[randPair(0,4)] = np.array([1,0,0,0]) a = findLoc(state, np.array([0,0,0,1])) w = findLoc(state, np.array([0,0,1,0])) g = findLoc(state, np.array([1,0,0,0])) p = findLoc(state, np.array([0,1,0,0])) #If any of the "objects" are superimposed, just call the function again to re-place if (not a or not w or not g or not p): #print('Invalid grid. Rebuilding..') return initGridRand() return state The state is a 3-dimensional numpy array (4x4x4). You can think of the first two dimensions as the positions on the board; e.g. row 1, column 2 is the position (1,2) [zero indexed] on the board. The 3rd dimension encodes the object/element at that position. Since there are 4 different possible objects, the 3rd dimension of the state contains vectors of length 4. We're using a one-hot encoding for the elements except that the empty position is just a vector of all zeros. So with a 4 length vector we're encoding 5 possible options at each grid position: empty, player, goal, pit, or wall. You can also think of the 3rd dimension as being divided into 4 separate grid planes, where each plane represents the position of each element. So below is an example where the player is at grid position (3,0), the wall is at (0,0), the pit is at (0,1) and the goal is at (1,0). [All other elements are 0s] In our simple implementation it's possible for the board to be initialized such that some of the objects contain a 1 at the same "x,y" position (but different "z" positions), which indicates they're at the same position on the grid. Obviously we don't want to initialize the board in this way, so for the last 2 variants of the game that involve some element of random initialization, we check if we can find "clean" arrays (only one "1" in the 'Z' dimension of a particular grid position) of the various element types on the grid and if not, we just recursively call the initialize grid function until we get a state where elements are not superimposed. When the player successfully plays the game and lands on the goal, the player and goal positions will be superimposed and that is how we know the player has won (likewise if the player hits the pit and loses). The wall is supposed to block the movement of the player so we prevent the player from taking an action that would place them at the same position as the wall. Additionally, the grid is "enclosed" so that player cannot walk through the edges of the grid. Now we will implement the movement function. def makeMove(state, action): #need to locate player in grid #need to determine what object (if any) is in the new grid spot the player is moving to player_loc = findLoc(state, np.array([0,0,0,1])) wall = findLoc(state, np.array([0,0,1,0])) goal = findLoc(state, np.array([1,0,0,0])) pit = findLoc(state, np.array([0,1,0,0])) state = np.zeros((4,4,4)) actions = [[-1,0],[1,0],[0,-1],[0,1]] #e.g. up => (player row - 1, player column + 0) new_loc = (player_loc[0] + actions[action][0], player_loc[1] + actions[action][1]) if (new_loc != wall): if ((np.array(new_loc) <= (3,3)).all() and (np.array(new_loc) >= (0,0)).all()): state[new_loc][3] = 1 new_player_loc = findLoc(state, np.array([0,0,0,1])) if (not new_player_loc): state[player_loc] = np.array([0,0,0,1]) #re-place pit state[pit][1] = 1 #re-place wall state[wall][2] = 1 #re-place goal state[goal][0] = 1 return state The first thing we do is try to find the positions of each element on the grid (state). Then it's just a few simple if-conditions. We need to make sure the player isn't trying to step on the wall and make sure that the player isn't stepping outside the bounds of the grid. Now we implement getLoc which is similar to findLoc but can identify superimposed elements, whereas findLoc would miss it (intentionally) if there was superimposition. Additionally, we'll implement our reward function, which will award +10 if the player steps onto the goal, -10 if the player steps into the pit, and -1 for any other move. These rewards are pretty arbitrary, as long as the goal has a significantly higher reward than the pit, the algorithm should do fine. Lastly, I've implemented a function that will display our grid as a text array so we can see what's going on. def getLoc(state, level): for i in range(0,4): for j in range(0,4): if (state[i,j][level] == 1): return i,j def getReward(state): player_loc = getLoc(state, 3) pit = getLoc(state, 1) goal = getLoc(state, 0) if (player_loc == pit): return -10 elif (player_loc == goal): return 10 else: return -1 def dispGrid(state): grid = np.zeros((4,4), dtype=' ) player_loc = findLoc(state, np.array([0,0,0,1])) wall = findLoc(state, np.array([0,0,1,0])) goal = findLoc(state, np.array([1,0,0,0])) pit = findLoc(state, np.array([0,1,0,0])) for i in range(0,4): for j in range(0,4): grid[i,j] = ' ' if player_loc: grid[player_loc] = 'P' #player if wall: grid[wall] = 'W' #wall if goal: grid[goal] = '+' #goal if pit: grid[pit] = '-' #pit return grid And that's it. That's the entire gridworld game implementation. Not too bad right? As with my part 2 blackjack implementation, this game is not using OOP-style and implemented in a functional style where we just pass around states. Let's demonstrate some gameplay. I'll be using the initGridRand() variant so that all items are placed randomly. state = initGridRand() dispGrid(state) array([['P', '-', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', 'W', ' '], [' ', '+', ' ', ' ']], dtype=' As you can see, I clearly need to move 3 spaces down, and 1 space to the right to land on the goal. Remember, our action encoding is: 0 = up, 1 = down, 2 = left, 3 = right. state = makeMove(state, 1) state = makeMove(state, 1) state = makeMove(state, 1) state = makeMove(state, 3) print('Reward: %s' % (getReward(state),)) dispGrid(state) Reward: 10 array([[' ', '-', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', 'W', ' '], [' ', ' ', ' ', ' ']], dtype=' We haven't implemented a display for when the player is on the goal or pit so the player and goal just disappear when that happens. Neural Network as our Q function¶ Now for the fun part. Let's build our neural network that will serve as our $Q$ function. Since this is a post about Q-learning, I'm not going to code a neural network from scratch. I'm going to use the fairly popular Theano-based library Keras. You can of course use whatever library you want, or roll your own. Important Note: Up until now, I've been talking about how the neural network can serve the role of $Q(s, a)$, and that's absolutely true. However, I will be implementing our neural network in the same way that Google DeepMind did for its Atari playing algorithm. Instead of a neural network architecture that accepts a state and an action as inputs and outputs the value of that single state-action pair, DeepMind built a network that just accepts a state and outputs separate Q-values for each possible action in its output layer. This is pretty clever because in Q-learning we need to get the $maxQ(s', a')$ [max of the Q values for every possible action in the new state s']. Rather than having to run our network forward for every action, we just need to run it forward once. The result is the same, however, it's just more efficient. from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation from keras.optimizers import RMSprop model = Sequential() model.add(Dense(164, init='lecun_uniform', input_shape=(64,))) model.add(Activation('relu')) #model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try? model.add(Dense(150, init='lecun_uniform')) model.add(Activation('relu')) #model.add(Dropout(0.2)) model.add(Dense(4, init='lecun_uniform')) model.add(Activation('linear')) #linear output so we can have range of real-valued outputs rms = RMSprop() model.compile(loss='mse', optimizer=rms) model.predict(state.reshape(1,64), batch_size=1) #just to show an example output; read outputs left to right: up/down/left/right array([[-0.02812552, -0.04649779, -0.08819015, -0.00723661]]) So that's the network I've designed. An input layer of 64 units (because our state has a total of 64 elements, remember its a 4x4x4 numpy array), 2 hidden layers of 164 and 150 units, and an output layer of 4, one for each of our possible actions (up, down, left, right) [in that order]. Why did I make the network like this? Honestly, I have no good answer for that. I just messed around with different hidden layer architectures and this one seemed to work fairly well. Feel free to change it up. There's probably a better configuration. (If you discover or know of a much better network architecture for this, let me know). Online Training¶ Below is the implementation for the main loop of the algorithm. In broad strokes: - Setup a for-loop to number of epochs - In the loop, setup while loop (while game is in progress) - Run Q network forward. - We're using an epsilon greedy implementation, so at time t with probability $\epsilon$ we will choose a random action. With probability $1-\epsilon$ we will choose the action associated with the highest Q value from our neural network. - Take action $a$ as determined in (4), observe new state $s'$ and reward $r_{t+1}$ - Run the network forward using $s'$. Store the highest Q value ( maxQ). - Our target value to train the network is reward + (gamma * maxQ)where gammais a parameter ($0 <= \gamma <= 1$). - Given that we have 4 outputs and we only want to update/train the output associated with the action we just took, our target output vector is the same as the output vector from the first run, except we change the one output associated with our action to: reward + (gamma * maxQ) - Train the model on this 1 sample. Repeat process 2-9 Just to be clear, when we first run our neural network and get an output of action-values like this array([[-0.02812552, -0.04649779, -0.08819015, -0.00723661]]) our target vector for one iteration may look like this: array([[-0.02812552, -0.04649779, 10, -0.00723661]]) Also note, I initialize epsilon (for the $\epsilon$-greedy action selection) to be 1. It decrements by a small amount on every iteration and will eventually reach 0.1 where it stays. Google DeepMind also used an $\epsilon$-greedy action selection and also initialized epsilon to be 1 and decremented during the game play. if taking action 2 one step (left) resulted in reaching the goal. So we just keep all other outputs the same as before and just change the one for the action we took. Okay, so let's go ahead and train our algorithm to learn the easiest variant of the game, where all elements are placed deterministically at the same positions every time. from IPython.display import clear_output import random epochs = 1000 gamma = 0.9 #since it may take several moves to goal, making gamma high epsilon = 1 for i in range(epochs): state = initGrid()) #Get max_Q(S',a) newQ = model.predict(new_state.reshape(1,64), batch_size=1) maxQ = np.max(newQ) y = np.zeros((1,4)) y[:] = qval[:] if reward == -1: #non-terminal state update = (reward + (gamma * maxQ)) else: #terminal state update = reward y[0][action] = update #target output print("Game #: %s" % (i,)) model.fit(state.reshape(1,64), y, batch_size=1, nb_epoch=1, verbose=1) state = new_state if reward != -1: status = 0 clear_output(wait=True) if epsilon > 0.1: epsilon -= (1/epochs) Game #: 999 Epoch 1/1 1/1 [==============================] - 0s - loss: 0.0265 Alright, so I've empirically tested this and it trains on the easy variant with just 1000 epochs (keep in mind every epoch is a full game played to completion). Below I've implemented a function we can use to test our trained algorithm to see if it has properly learned how to play the game. It basically just uses the neural network model to calculate action-values for the current state and selects the action with the highest Q-value. It just repeats this forever until the game is won or lost. I've made it break out of this loop if it is making more than 10 moves because this probably means it hasn't learned how to win and we don't want an infinite loop running. def testAlgo(init=0): i = 0 if init==0: state = initGrid() elif init==1: state = initGridPlayer() elif init==2: state = initGridRand() print("Initial State:") print(dispGrid(state)) status = 1 #while game still in progress while(status == 1): qval = model.predict(state.reshape(1,64), batch_size=1) action = (np.argmax(qval)) #take action with highest Q-value print('Move #: %s; Taking action: %s' % (i, action)) state = makeMove(state, action) print(dispGrid(state)) reward = getReward(state) if reward != -1: status = 0 print("Reward: %s" % (reward,)) i += 1 #If we're taking more than 10 actions, just stop, we probably can't win this game if (i > 10): print("Game lost; too many moves.") break testAlgo(init=0) Initial State: [[' ' 'P' ' ' ' '] [' ' '-' ' ' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' '+']] Move #: 0; Taking action: 3 [[' ' ' ' 'P' ' '] [' ' '-' ' ' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' '+']] Move #: 1; Taking action: 3 [[' ' ' ' ' ' 'P'] [' ' '-' ' ' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' '+']] Move #: 2; Taking action: 1 [[' ' ' ' ' ' ' '] [' ' '-' ' ' 'P'] [' ' ' ' 'W' ' '] [' ' ' ' ' ' '+']] Move #: 3; Taking action: 1 [[' ' ' ' ' ' ' '] [' ' '-' ' ' ' '] [' ' ' ' 'W' 'P'] [' ' ' ' ' ' '+']] Move #: 4; Taking action: 1 [[' ' ' ' ' ' ' '] [' ' '-' ' ' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Reward: 10 Can we get a round of applause for our gridworld player here? Clearly it knows what its doing; it went straight for the prize! Playing the the harder variant, catastrophic forgetting, and experience replay¶ We're slowly building up our chops and we want our algorithm to train on the harder variant of the game where every new game the player is randomly placed on the grid. It can't just memorize a sequence of steps to take as before, it needs to be able to take the shortest path to the goal (without stepping into the pit) from wherever it starts on the grid. It needs to develop a slightly more sophisticated representation of its environment. Unfortunately, there is a problem we may need to deal with as our problem becomes increasingly more difficult. There is a known problem called catastrophic forgetting that is associated with gradient descent based training methods in online training. Imagine that in game #1 that our algorithm is training on (learning Q-values for) the player is placed in between the pit and the goal such that the goal is on the right and the pit is on the left. Using epsilon-greedy strategy, the player takes a random move and by chance takes a step to the right and hits the goal. Great, the algorithm will try to learn that this state-action pair is associated with a high reward by updating its weights in such a way that the output will more closely match the target value (i.e backpropagation). Now, the second game gets initialized and the player is again in between the goal and pit but this time the goal is on the left and the pit is on the right. Perhaps to our naive algorithm, the state seems very similar to the last game. Let's say that again, the player chooses to make one step to the right, but this time it ends up in the pit and gets -10 reward. The player is thinking "what the hell I thought going to the right was the best decision based on my previous experience." So now it may do backpropagation again to update its state-action value but because this state-action is very similar to the last learned state-action it may mess up its previously learned weights. This is the essence of catastrophic forgetting. There's a push-pull between very similar state-actions (but with divergent targets) that results in this inability to properly learn anything. We generally don't have this problem in the supervised learning realm because we do randomized batch learning, where we don't update our weights until we've iterated through some random subset of our training data. Catastrophic forgetting is probably not something we have to worry about with the first variant of our game because the targets are always stationary; but with the harder variants, it's something we should consider, and that is why I'm implementing something called experience replay. Experience replay basically gives us minibatch updating in an online learning scheme. It's actually not a huge deal to implement; here's how it works. Experience replay: - In state $s$, take action $a$, observe new state $s_{t+1}$ and reward $r_{t+1}$ - Store this as a tuple $(s, a, s_{t+1}, r_{t+1})$ in a list. - Continue to store each experience in this list until we have filled the list to a specific length (up to you to define) - Once the experience replay memory is filled, randomly select a subset (e.g. 40) - Iterate through this subset and calculate value updates for each; store these in a target array (e.g. y_train) and store the state $s$ of each memory in X_train - Use X_trainand y_trainas a minibatch for batch training. For subsequent epochs where the array is full, just overwrite old values in our experience replay memory array. Thus, in addition to learning the action-value for the action we just took, we're also going to use a random sample of our past experiences to train on to prevent catastrophic forgetting. So here's the same training algorithm from above except with experience replay added. Remember, this time we're training it on the harder variant of the game where the player is randomly placed on the grid. model.compile(loss='mse', optimizer=rms)#reset weights of neural network epochs = 3000 gamma = 0.975 epsilon = 1 batchSize = 40 buffer = 80 replay = [] #stores tuples of (S, A, R, S') h = 0 for i in range(epochs): state = initGridPlayer() #using the harder state initialization function) #Experience replay storage if (len(replay) < buffer): #if buffer not filled, add to it replay.append((state, action, reward, new_state)) else: #if buffer full, overwrite old values if (h < (buffer-1)): h += 1 else: h = 0 replay[h] = (state, action, reward, new_state) #randomly sample our experience replay memory minibatch = random.sample(replay, batchSize) X_train = [] y_train = [] for memory in minibatch: #Get max_Q(S',a) old_state, action, reward, new_state = memory old_qval = model.predict(old_state.reshape(1,64), batch_size=1) newQ = model.predict(new_state.reshape(1,64), batch_size=1) maxQ = np.max(newQ) y = np.zeros((1,4)) y[:] = old_qval[:] if reward == -1: #non-terminal state update = (reward + (gamma * maxQ)) else: #terminal state update = reward y[0][action] = update X_train.append(old_state.reshape(64,)) y_train.append(y.reshape(4,)) X_train = np.array(X_train) y_train = np.array(y_train) print("Game #: %s" % (i,)) model.fit(X_train, y_train, batch_size=batchSize, nb_epoch=1, verbose=1) state = new_state if reward != -1: #if reached terminal state, update game status status = 0 clear_output(wait=True) if epsilon > 0.1: #decrement epsilon over time epsilon -= (1/epochs) Game #: 2999 Epoch 1/1 40/40 [==============================] - 0s - loss: 0.0018 I've increased the training epochs to 3000 just based on empiric testing. So let's see how it does, we'll run our testAlgo() function a couple times to see how it handles randomly initialized player scenarios. testAlgo(1) #run testAlgo using random player placement => initGridPlayer() Initial State: [[' ' ' ' ' ' ' '] [' ' '-' '+' ' '] [' ' ' ' 'W' ' '] [' ' ' ' 'P' ' ']] Move #: 0; Taking action: 3 [[' ' ' ' ' ' ' '] [' ' '-' '+' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' 'P']] Move #: 1; Taking action: 0 [[' ' ' ' ' ' ' '] [' ' '-' '+' ' '] [' ' ' ' 'W' 'P'] [' ' ' ' ' ' ' ']] Move #: 2; Taking action: 0 [[' ' ' ' ' ' ' '] [' ' '-' '+' 'P'] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 3; Taking action: 2 [[' ' ' ' ' ' ' '] [' ' '-' ' ' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Reward: 10 Fantastic. Let's run the testAlgo() one more time just to prove it has generalized. testAlgo(init=1) #Of course, I ran it many times more than I'm showing here Initial State: [[' ' ' ' ' ' ' '] [' ' '-' '+' ' '] [' ' 'P' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 0; Taking action: 2 [[' ' ' ' ' ' ' '] [' ' '-' '+' ' '] ['P' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 1; Taking action: 0 [[' ' ' ' ' ' ' '] ['P' '-' '+' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 2; Taking action: 0 [['P' ' ' ' ' ' '] [' ' '-' '+' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 3; Taking action: 3 [[' ' 'P' ' ' ' '] [' ' '-' '+' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 4; Taking action: 3 [[' ' ' ' 'P' ' '] [' ' '-' '+' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Move #: 5; Taking action: 1 [[' ' ' ' ' ' ' '] [' ' '-' ' ' ' '] [' ' ' ' 'W' ' '] [' ' ' ' ' ' ' ']] Reward: 10 I'll be darned. It seems to have learned to play the game from any starting position! Pretty neat. The Hardest Variant¶ Okay, I lied. I will not be showing you the algorithm learning the hardest variant of the game (where all 4 elements are randomly placed on the grid each game). I'm leaving that up to you to attempt and let me know how it goes via email (outlacedev@gmail.com). The reason is, I'm doing all this on a Macbook Air (read: no CUDA gpu) and thus I cannot train the algorithm to a sufficiently large number of epochs for it to learn the problem. I suspect it may require significantly more epochs, perhaps more than 50,000. So if you have an nVIDIA GPU and can train it that long, let me know if it works. I could have used Lua/Torch7 since there is an OpenCL version but no one would read this if it wasn't in Python =P. Conclusion¶ There you have it, basic Q-learning using neural networks. That was a lot to go through, hopefully I didn't make too many mistakes (as always, email if you spot any so I can post corrections). I'm hoping you have success training Q-learning algorithms on more interesting problems than the gridworld game. I'd say this is definitely the climax of the series on reinforcement learning. I plan to release a part 4 that will be about other temporal difference learnings algorithms that use eligibility traces. Since that's a relatively minor new concept, I will likely use it on another toy problem like gridworld. However, I do, at some point, want to release a post about setting up and using the Arcade Learning Environment (ALE) [fmr. Atari Learning Environment] and training an alogorithm to play Atari games, however, that will likely be a long while from now so don't hold your breath. Cheers Download this IPython Notebook¶ Download the Gridworld Game¶ References¶ - - -;=true&disableCoverPage;=true&origin;=publication_detail - "Reinforcement Learning An Introduction" Sutton & Barto, 1996 - "Human-level control through deep reinforcement learning" Mnih et al, 2015 (Google DeepMind Atari paper)
http://outlace.com/rlpart3.html
CC-MAIN-2018-17
refinedweb
5,826
62.07
#include <memory> #include <vector> #include <swfntcch.hxx> Go to the source code of this file. Definition at line 21 of file atrhndl.hxx. Attribute to Stack Mapping. Attributes applied to a text are pushed on different stacks. For each stack, the top most attribute on the stack is valid. Because some kinds of attributes have to be pushed to the same stacks we map their ids to stack ids Attention: The first NUM_DEFAULT_VALUES ( defined in swfntcch.hxx ) are stored in the defaultitem-cache, if you add one, you have to increase NUM_DEFAULT_VALUES. Also adjust NUM_ATTRIBUTE_STACKS in atrhndl.hxx. Definition at line 68 of file atrstck.cxx.
https://docs.libreoffice.org/sw/html/atrhndl_8hxx.html
CC-MAIN-2021-43
refinedweb
106
69.79
What’s it do When you spot something in your app that needs reporting just shake your phone/device. A screenshot of the current screen will popup, draw on it to highlight areas and then send it on in an email. Installation Spot is available through CocoaPods. To install it, simply add the following line to your Podfile: pod "Spot" Getting started Once you’ve installed the pod, go to your application delegate and add the following… Swift: import Spot Then in application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool Spot.start() Objective C: @import Spot; Then in (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions [Spot start]; Providing more information for the reporting email Implement the SpotDelegate protocol to provide more information to be included in the report email. This allows you to provide a default email address and a file attachement (useful for log files!). Example To run the example project, clone the repo, and open the project file in the "Example" folder Author Daniel Leivers, [email protected] License Spot is available under the MIT license. See the LICENSE file for more info. Latest podspec { "name": "Spot", "version": "0.1.6", "summary": "A super simple pod for reporting UI issues.", "description": "A super simple pod for reporting UI issues.nnWhen you spot something in your app that needs reporting just shake your phone/device. A screenshot of the current screen will popup, draw on it to highlight areas and then send it on in an email.", "homepage": "", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Daniel Leivers": "[email protected]" }, "source": { "git": "", "tag": "0.1.6" }, "social_media_url": "", "platforms": { "ios": "9.0" }, "source_files": "Spot/*.swift", "resource_bundles": { "Spot": [ "Spot/Spot.storyboard" ] }, "frameworks": [ "UIKit", "MessageUI" ], "pushed_with_swift_version": "3.0" } Fri, 11 May 2018 23:40:10 +0000
https://tryexcept.com/articles/cocoapod/spot
CC-MAIN-2019-09
refinedweb
290
57.06
CodeGuru Forums > .NET Programming > C-Sharp Programming > Classes that Generate Fluent and Nonsensical Poetry. PDA Click to See Complete Forum and Search --> : Classes that Generate Fluent and Nonsensical Poetry. Guidosoft March 28th, 2010, 07:06 PM I've managed to write a simple set of classes that facilitate generating verse in iambic patameter. All the the output will flow perfectly, but unfortunately none of it will either make sense or be grammatically correct. If anyone would be kind enough, I'm asking you to take a look at my code and tell me what you think of it. I'm 18 and have been here and there learning and experimenting with programming since I was much younger. My dream has been for a long time to become a professional programmer. I know the code I've written is trivial, but hopefully I'm able (especially by the grace of God) to work for a company one day. So can anyone please assess my code and my ability according to the code I've written, and tell me what I need to do to achieve my dream. I'm already in college, and hopefully I will soon be taking computer programming courses. Nevertheless, programming for me is not just something I wait to do until I've been educated. I enjoy programming, so I do it now, even when it sometimes pulls my mind off of the prerequisite work I should be doing. That's not good though. I know I need to focus more on my work. But I still love to program. I'd like to hear your feedback on this, and on my code and abilities. I'll accept criticism, but I'm hoping you'll correct me kindly Mutant_Fruit March 28th, 2010, 07:32 PM Your "PartOfSpeech TranslatePart(string part)" method can be reduced to a much more simple method: PartOfSpeech TranslatePart(string part) { if (Enum.IsDefined (typeof (PartOfSpeed), part)) return (PartOfSpeed) Enum.Parse (typeof (PartOfSpeed), part, true); return PartOfSpeech.Unknown; } That will do a case insensitive parse of your string and give you the corresponding enum type. If the string is not part of the enum, you'll get Unknown. You do a few funny things like calling ElementAt instead of directly accessing the element at the index: Word currentWord = this.ElementAt(i); // should be Word currentWord = this [i]; The difference being that you're invoking Linq extension methods which operate on IEnumerable. This means that to get the element at position [i], the LINQ method might do something like: public T ElementAt (int index) { int count = 0; foreach (var v in this) { if (count == index) return v; count ++; } } Similarly for your usage of the LINQ method "Count ()" instead of directly using the List<T> property 'Count'. Most of your 'MatchesXXX' methods can be rewritten to be like this: public bool MatchesText(string[] texts) { return Array.Contains<string> (texts, Text); } Alternatively if 'texts' were a List<string> instead of a string[] you could just directly call: "texts.Contains (Text)" and remove that method entirely. Or just change your method signature to accept an IList<string>. Both string[] and List<string> implement IList<string>, so you can access your string[] through the IList<string> interface and gain easy access to methods like IndexOf and Contains. For example it's perfectly legal to declare your method like this and pass a string[] as the parameter: public WordList ThoseWithStress(IList<string> stresses) { WordList newList = new WordList(); for (int i = 0; i < this.Count; i++) { if (stresses.Contains (this [i])) newList.Add(new Word(this [i])); } return newList; } ... ... ThoseWithStresses (new string[] { "u" }); You use turnary when you don't have to in a few places, for example: return NumberOfSyllables > 0 ? true : false; can be simply: return NumberOfSyllables > 0; The UpdateRandomizer function is completely unnecessary ;) You can't make things *more* random by creating a new Random object. The only thing you'd be likely to do would be to make things *less* random :) Just remove that code and your app will instantly become better and shorter! Other than that, things look more pretty decent. I'd have no major complaint about it, most of the issues I have are just minor ones. codeguru.com
http://forums.codeguru.com/archive/index.php/t-494908.html
crawl-003
refinedweb
704
62.38
IntelliSense If you’re using almost any of the Visual Studio keyboard mappings, typing Ctrl+J will bring up IntelliSense. In Visual Studio 2012, IntelliSense should appear automatically in C++. In Visual Studio 2010 and earlier, you need to invoke it manually. Code Snippets Code snippets are a new feature for C++ in Visual Studio 2012. They did not exist in earlier versions. If you’ve never used them in any language, then in a C# project, start typing “for” to begin a for loop; once IntelliSense has chosen the for snippet, press the Tab key twice and watch as a for loop appears complete with automatic fields you can edit. Use the Tab key to switch between fields. When you’re done editing the fields, press Enter. The cursor will be transported within the loop body with the field edits you made appearing as normal text. Code snippets are particularly nice for switch statements that switch on an enum, since they will automatically populate the switch statement with all of the enum’s members. Including Libraries In C++, it's usually not enough to just include a header file. Normally you need to tell the linker to link against a library that implements the code declared in the header file. To do this, you need to edit the project's properties, accessible in the Project menu as ProjectName Properties... In the properties, under Configuration Properties > Linker > Input, one of the fields is Additional Dependencies. This is a semicolon-separated list of the .LIB files you need to link against. It should end with %(AdditionalDependencies) so that any additional libraries linked via MS Build will be added. For a typical DirectX 11 Metro-style game, for example, you might see the following: d2d1.lib; d3d11.lib; dxgi.lib; ole32.lib; windowscodecs.lib; dwrite.lib; xaudio2.lib; xinput.lib; mfcore.lib; mfplat.lib; mfreadwrite.lib; mfuuid.lib; %(AdditionalDependencies) If you receive a linker error telling you it cannot find a definition of something you are using, find the function or class on MSDN; the documentation will tell you both the header file and the library file you need. Generating Assembly Code Files If you want to view a very close approximation of the assembly code that your code is compiled into, in your project’s properties, under Configuration Properties > C/C++ > Output Files, set the Assembler Output option to something other than No Listing. I’d recommend either Assembly-Only Listing (/FA) or Assembly with Source Code (/FAs). Assembly-Only Listing sprinkles enough line-number comments that you can usually cross-reference with your source code files to see what C++ code corresponds with the assembly code. That can be helpful if you want one place to see everything rather than flipping back and forth between whatever you’ve opened the .ASM file in (I use Notepad++) and Visual Studio. Note that the generated assembly uses MASM macros (find them on MSDN). If you don’t know what a particular assembly instruction means (e.g., LEA), you can search the internet for it or download the appropriate programming manual from Intel’s site (assuming x86/Itanium), AMD’s site (assuming x64) or ARM Holding’s site (assuming ARM). If you’ve never learned any assembly, I definitely recommend doing so (try creating a simple Windows Console app). Understanding assembly gives you a better understanding of how computers really work internally. Combine that with the knowledge that computers are all hardwired to begin executing the same code every time they are powered on (traditionally the BIOS on PCs, though that is now being replaced by UEFI), and the mystery of how and why computers work quickly begins to fade. Terrifying Build Errors If you come across a build error that looks completely horrible, chances are it’s from the linker. You’ll see messages like this, for instance: Error 2 error LNK2019: unresolved external symbol &quot;public: __thiscall SomeClass::SomeClass(wchar_t const *)&quot; (??0SomeClass@@QAE@PB_W@Z) referenced in function &quot;void __cdecl DoSomething(void)&quot; (?DoSomething@@YAXXZ) D:\VS2010Proj\CppSandbox\CppSandbox\CppSandbox.obj CppSandbox All that’s saying is it cannot find a function you said it should be able to find. In this case, I added the inline keyword to a constructor function definition in the CPP file without remembering to relocate that definition to the header file. Any inline functions need to be in the header so the linker won’t hate you. All those ??s and @@ands are just how C++ mangles names when it has compiled code into object files. Name mangling is internally consistent for the compiler in question, but the ISO/IEC standard doesn’t mandate any particular schema for name mangling. Different compilers can, and often will, mangle things differently. Normally, if you see a horrifying build error message, chances are it’s from the linker, and it’s an unresolved symbol error. If it’s saying it can’t find something you wrote, then check to make sure your declaration in the header file matches the definition, usually in the code file but maybe in the header, or maybe you forgot to write it, or maybe you declared it inline but still have it in the code file. An example of this is in the previous case: my SomeClass::SomeClass(wchar_t const *) constructor function (I always write const type not type const, so even that bit is reconstructed). If it’s someone else’s function or other symbol, then chances are you didn’t tell the linker about the .LIB file that contains it. In .NET, you just add a reference to an assembly to get both the declaration bits and the actual definition all in one. In C++, the declaration is the header file, while the definition code—excluding inline code, which needs to be in the header file too—is in a separate library. Search the MSDN library for the missing symbol and find the name of the library file you need to add. C++ build errors can look pretty scary, especially when you receive a build error involving a template. Those can make you want to quit. But don’t. Never let the horrible error messages win. First, figure out if it’s coming from the compiler (it’ll have a C#### error number format) or the linker (LNK#### error number format). If from the compiler, it usually means a syntax error. Check things like whether you forgot the #pragma once at the top of your header file. Another problem could be where you used something from the Standard Library (e.g., endl) but forgot to have a #using namespace std; or to prefix it with std:: (i.e. std::endl). You can do either or both, but you must do at least one. Some things might be in a different namespace. In Visual Studio 2010, some functionality is in the stdext namespace, for example. The same goes for any namespaces in your own code. If you aren’t having any luck on your own, go to MSDN and type the first part of the error message. You’ll probably find some helpful links to discussions on the MSDN forums, on StackOverflow, perhaps an MSDN article or an MSDN blog post—maybe even just the error code’s page itself will have the hint you need. If all else fails, post a question on a forums site: MSDN, the appropriate StackExchange site, or App Hub. A linker error is typically an unresolved symbol, which usually means you have a mismatch in declaration and definition, have an inline outside of its header, or don’t have the right library added to the project’s extra dependencies in the project’s linker options. If it’s something else, try the strategies from the previous paragraph; they apply just as well to linker errors as to compiler errors. Conclusion If you're doing a lot of C++ development, then Visual Studio is certainly an IDE (Integrated Development Environment) worth considering. It has a lot more to offer than what's covered in this article, so I encourage you to give it a try and explore it's wide range of features. This lesson represents a chapter from C++ Succinctly, a free eBook from the team at Syncfusion. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/articles/c-succinctly-visual-studio-and-c--mobile-22074
CC-MAIN-2018-22
refinedweb
1,404
60.55
This post is part of a series of mine on building web applications from the ground up. It covers everything you need to know to completely finish a web application. If you haven’t been following the series, please go back and read part 1. In this part, I’ll show you how to start building an API using the Django REST Framework. Furthermore, this section will cover proper project setup as well as structure. The GitHub repository for this example API project can be found here. Setting Up the API Environement To start working on your API, you’ll want to make sure you have the following: - Git - A command-line environment that you’re comfortable using. I prefer using Git Bash, as I prefer a Unix-like environment over windows. It’s stable, it’s small, and it’s simple. - A good text editor or IDE. I like to use Sublime Text 3 for projects like this. I know many people who prefer other environments such as Atom or PyCharm. However, I like the speed and features of Sublime 3 the best. - The latest (stable) distribution of Python 3. - Postman, a chrome app for easily testing HTTP requests. Setting Up Your Web App Project The first thing you should do to setup your project is create your repository. I typically will create a free repository on GitHub. However, if you do have private repositories, you may want to consider the trade-offs between having an open or closed source project. However, having some kind of source control is crucial for development. If you’re not already familiar with the benefits of using source control, swing on over to this blog post. Setting up a GitHub Repo If you don’t already have a GitHub account, sign up for one first. If you’re currently a student, I highly recommend signing up for the student developer pack. After you’ve logged in, locate the button to create a new repository. This will bring you to a short form as shown below. Fill this out with some basic information for your project. Now, If you have private repositories and want this project to be private, go ahead and click the Private option. Check the box to initialize the project with a ReadMe, select the Python .gitignore file, and select the license you’d like your project to have (if you need help choosing a license, see ChooseALicense.com). Once you’re done on this page, click Create Repository. Now, go to your repository page and click the clone or download button. Click the button to “clone with ssh”. If you don’t have a SSH key setup on your laptop, check out this tutorial for creating one. Then, open your command line environment in the folder where you want to store your projects. I typically make a folder named “dev” for all of my programming work. First, open your command line environment in the folder you wish to clone the repository into. After that, clone the repository onto your machine by typing the following in your command line (filling in the URL with the link copied from GitHub). git clone URL Creating a Python Virtual Environment Using virtual environments in Python allows you to keep packages needed to run this project separate from your system’s Python environment. This may not be a big deal if you’re only using your computer to run one Python project, but as you install different requirements for various projects you could run into issues. It’s considered the best practice to use a separate virtual environment for each project you’re working on. And it’s easy to do in Python. To create a new virtual environment, first install the virtualenv Python package: pip install virtualenv Next, run the following in the command line within the project folder: virtualenv venv This will generate a virtual environment directory which is essentially a sandboxed Python environment. Any python packages you install when this virtual environment is activated will only be installed into this folder. Likewise, you will need to use this virtual environment to run your application. Note that the “venv/” directory should already be added to your .gitignore file; virtual environments should never be committed to version control. While we’re on the subject of the .gitignore though, you should also add db.sqlite3 at the top of your .gitignore file. This will make it so the development database is not committed to the repository. Anyways, you can use the virtual environment like so: # activate the virtual environment (windows) .\venv\Scripts\activate # activate the virtual environment (emulated linux cmd line on windows, e.g. Git Bash) source ./venv/Scripts/activate # activate the virtual environment (linux) source ./venv/bin/activate # install python packages into this virtual environment pip install django # run python scripts using this environment python my-script.py # deactivate the environment when you're finished deactivate Initialize this Project as a Python Package Making your project a pip installable Python Package has many benefits. The two that sell me on it are that you can use absolute module paths within your application and that you can package you can leverage a package manager like PIP as a means to manage your app’s versions and dependencies. To make your Python project a fully-fledged package, you’ll need to create a setup.py file. At the root level of your repository, add a setup.py file like below: from distutils.core import setup setup( name='todo_api', version='0.1', description='A ToDo List API built with Django REST Framework', author='Michael Washburn Jr', author_email='michael@michaelwashburnjr.com', url=' packages=find_packages(), install_requires=[] ) Once we initialize the Django project, you can do install the package by running the following from the command line in the root folder of your repository: pip install -e . Initialize the Django Project Now that the basic package structure is there, we can initialize our API project. I like using Django for projects like this. Specifically, I prefer the Django REST Framework for API development. It leverages the Django Models that are super simple to work with and enhances the views in Django to make building RESTful APIs super simple. To initialize the Django project, we first have to install some dependencies (remember to activate your virtual environment): pip install django djangorestframework Remember to keep the install_requires section of your setup.py file up-to-date with the latest installed dependencies. You can do this by running the following: > pip freeze Django==1.11.4 djangorestframework==3.6.3 pytz==2017.2 Then, you can put the output into your setup.py file like so: # setup.py setup( # ...other settings install_requires = [ 'Django==1.11.4', 'djangorestframework==3.6.3', 'pytz==2017.2', ] ) Now, make a new Django app. django-admin.py startproject todo_api This will generate a folder with your project name in the directory you executed the command in. Within this folder is a manage.py file (used for development), and the package for your program. At this point, I usually rename the topmost folder generated to src/. You don’t have to, but I do this to reduce the duplicate names in the folder structure. Furthermore, this helps to clearly distinguish where the source of the application is. Now that we have a Django project, we have to enable the Django REST Framework by adding it to the settings.py file. # settings.py INSTALLED_APPS = ( ... 'rest_framework', ) The project itself is now setup. You can start the development server by running: python src/manage.py runserver To see it running, go to localhost:8000 in your browser. However, our project is missing models for storing data, serializers for converting data to JSON, and views for getting and returning the data. Inside src/todo_api, create 3 new folders named models/, serializers/, and views/. Inside each folder put an empty file named __init__.py. This is how Python denotes a folder as a module. Create a Test View Inside your views/ folder create a new file named test.py. In this file, we’re going to make a quick endpoint to make sure everything is functioning correctly. # todo_api/views/test.py from django.http import HttpResponse def test_view(request): html = "<html><body>Hello, World!</body></html>" return HttpResponse(html) Now, add the view in your urls.py file. # todo_api/urls.py from django.conf.urls import url from django.contrib import admin # notice you can use absolute module paths (which you should) from todo_api.views.test import test_view urlpatterns = [ url(r'^, test_view), url(r'^admin/', admin.site.urls), ] After the URL has been added, run your development server and navigate to localhost:8000. You should see the “Hello, World!” text we added. That’s it! Our project is now all set up. Woohoo! In the next section, I’ll be covering Django API development and testing. But, if you’re too excited to stop working now, take a look at the Django REST Framework Quickstart guide. Stuck? Let me know if you have any questions.
https://michaelwashburnjr.com/blog/building-webapp-tutorial-part-2
CC-MAIN-2022-21
refinedweb
1,512
57.67
- Observer Pattern syntactic sugar Tue, 2008-12-23, 13:27 I have been looking for an easy way to add a observer pattern to standard setters without typing too much. Groovy will probably add support like described here in the BoundProperty: However the groovy approach (not even final) would not allow me easily to use the eventbus from I have been thinking for scala there would be cooler, more flexible way to do this. I propose a trait: trait Observable{ def publish(field_name : String, oldValue : Any, newValue : Any) : Unit } On compile time if it finds such a trait, it compiles setters to (setter for field name) to publish that change: def name_$eq(newname : String) = {publish("name",this.name,newname); name = s} The groovy example could then be implemented with another trait: trait ObservableBean extends Observable{ import java.beans._ val pcs = new PropertyChangeSupport(this) def publish(field_name : String, oldValue : Any, newValue : Any) : Unit { pcs.firePropertyChange(new PropertyChangeEvent(this, field_name, oldValue, newValue)) } } you then just mix that in. Probably vetoable support could also be done like this... Currently creating simple beans is so clean and short in scala, but if you want to fire property changes you cant use any of the syntactic sugar. For one because I can not manually define the setter. I also would try doing it with aspectj, but I failed to recreate this example class Observed[T](v:T,name:String) extends Observable { var _v=v def value_=(v:T)= { publish(name, _v,v); _v=v} def value = _v def publish(field_name : String, oldValue : Any, newValue : Any) : Unit= { println("Publish change in "+field_name+" from: "+oldValue+" to "+newValue)} } But in my case I'm implementing undoability. In the classes you define your var as: var obs=new Observed[Int](10,"field1") obs: Observed[Int] = Observed@12eceb scala> obs.value=15 Publish change in field1 from: 10 to 15 This makes it easier to instance the Observed objects. One question I have is if there is a way to make this transparent: obs=15 instead of obs.value=15 In my cases I have a transaction space so I use implicits to pass to the transaction. def value_=(v:T)(implicit trans:Transaction) = ... //Store old value in transaction This brings me to another point I'd like to do which is have the commit of the transaction publish the changes: class Undoable[T](v:T,val f:Undoable[T]=>Any) In this code f is the publish function. This constructor works for: val u1=new Undoable(10, x=>publish("field",x.value)) or non observer: val u2=new Undoable(10,null) on the end of transaction I go through the list calling u2.f(u2). This published the events. I would like to have a way to make set of changes that are sent out as one single change, sent only once. So that I some method changes u1 and u2, I only get one message. class MyStuff { val u1=new Undoable(10, x=>publish("mystuff", this.whatyousee)) val u2=new Undoable(10, x=>publish("mystuff", this.whatyousee)) } Still woking on this. On Tue, Dec 23, 2008 at 10:27 AM, Stefan Ackermann-4 <stivo [dot] scala [at] gmail [dot] com> wrote:
http://www.scala-lang.org/old/node/439
CC-MAIN-2014-10
refinedweb
535
61.36
This article demonstrates how to remove unwanted white characters from ASP.NET output. I present how to use HttpResponse.Filter property to achieve this effect. During my work on an ASP.NET site, I realized that pages sent to the browser by the server contained many white characters at the beginning of each line. I browsed MSDN for something to fix this, and I found HttpResponse.Filter property. HttpResponse works in an easy way - all ASP.NET output goes through it. So my task looked easy - create my own Stream implementation and trim each written line in Write() function. First version was very simple: public class TrimStream : Stream { private Stream stream; private StreamWriter streamWriter; public TrimStream(Stream stm) { stream = stm; streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8); } public override void Write(byte[] buffer, int offset, int count) { MemoryStream ms = new MemoryStream(buffer, offset, count, false); StreamReader sr = new StreamReader(ms, System.Text.Encoding.UTF8); bool bNewLine = false; string s; while ((s = sr.ReadLine()) != null) { s = s.Trim(); if (s != "") { if (bNewLine) { streamWriter.WriteLine(); bNewLine = false; } streamWriter.Write(s); //new line chars should be emitted //only when line doesn't end with '>' if (s[s.Length-1] != '>') bNewLine = true; } } streamWriter.Flush(); } /* other overrided Stream functions and properties goes here */ } This code reads lines from the input stream, trims them, and writes to output stream only if the line is not empty. New line characters were written only when a line doesn't end with '>' char. Unfortunately, I quickly realized that larger pages (> 30K or something like that) are written to output stream by multiple calls to Write() - on one of my pages, I found a text input box instead of a checkbox (my code replaced <input type="checkbox"> with <input type="\ncheckbox">). So I decided to completely rewrite my code, and manually handle each character in order to correctly handle this situation. In the current version, I read all characters from the input stream, and manually analyze them line-by-line. Special handling is needed for the first and the last line: I also changed the logic that controls when a new line character is written - now it's emitted when neither previous line ends with '>' nor next line begins with '<'. I check this after trimming white chars and removing empty lines. This approach is safe for scripts embedded in a page - their lines are only trimmed, and empty lines are removed. If you insert this script in an HTML page: <script language="javascript"> <!-- function test() { alert('test'); } //--> </script> My code changes it as follows: <script language="javascript"><!-- function test() { alert('test'); } //--></script> bNewLine and bLastCharGT variables are used for deciding when to write a new line character before the next line. In arBlanks array are stored white chars between calls to Write(), if any was found on end of last line. This array can be zero-sized too - in this case, last char in line was non-blank, and that doesn't end with '\n'. This is important information - in this case, a new line char shouldn't be emitted if in first line (on next call to Write are non-blank chars). This code analyzes chars looking for '\n' char (it splits lines). When this char is found, you can find the following situations: arBlanksis not null, its contents are written, and all white chars to the beginning of the current line should be written to the output stream too; arBlanksarray for next call to Write(). public class TrimStream : Stream { private Stream stream; private StreamWriter streamWriter; private Decoder dec; public TrimStream(Stream stm) { stream = stm; streamWriter = new StreamWriter(stream, System.Text.Encoding.UTF8); dec = Encoding.UTF8.GetDecoder(); } /// <summary> /// Flag - write '\n' before next line /// </summary> private bool bNewLine = false; /// <summary> /// Flag - lash non-blank char in line was '>' /// </summary> private bool bLastCharGT = false; /// <summary> /// Array holding white chars from end of last line between Write() calls /// </summary> private char[] arBlanks = null; public override void Write(byte[] buffer, int offset, int count) { int nCharCnt = dec.GetCharCount(buffer, offset, count); char[] result = new char[nCharCnt]; int nDecoded = dec.GetChars(buffer, offset, count, result, 0); if (nDecoded <= 0) return; int nFirstNonBlank = -1; //position of first non-black line char int nLastNonBlank = -1; //position of last non-black line char int nFirstLineChar = 0; //position of first line char (any) bool bFirstLine = true; for (int nPos=0; nPos<=nDecoded; ++nPos) { bool bLastLine = nPos == nDecoded; char c = (nPos < nDecoded) ? result[nPos] : '\n'; if (c == '\n') //handle new line { //first line, and we have important //white chars from previous Write() call if (bFirstLine && (arBlanks != null)) { //current line contains non-blank chars //- write white chars from previous call if (nFirstNonBlank >=0) { if (arBlanks.Length > 0) streamWriter.Write(arBlanks, 0, arBlanks.Length); arBlanks = null; nFirstNonBlank = 0; bNewLine = false; } } bFirstLine = false; //current line contains any non-white chars - write them if (nFirstNonBlank >= 0) { if (bNewLine && (result[nFirstNonBlank] != '<')) //write new line char ? streamWriter.WriteLine(); //write current line (trimmed) streamWriter.Write(result, nFirstNonBlank, nLastNonBlank - nFirstNonBlank + 1); //setting variables... if (!bLastLine) { nFirstNonBlank = -1; nLastNonBlank = -1; nFirstLineChar = nPos + 1; } bNewLine = !bLastCharGT; bLastCharGT = false; } if (bLastLine) //last line - optionally remember white chars from its end { if ((arBlanks == null) && (nFirstNonBlank < 0)) { //empty line and we don't have any //white chars from previous call - nothing to do } else if (nLastNonBlank < nDecoded-1) //there was white chars at end of this line { int nNumBlanks, nFirstBlank; if (nLastNonBlank < 0) { nNumBlanks = nDecoded - nFirstLineChar; nFirstBlank = nFirstLineChar; } else { nNumBlanks = nDecoded - nLastNonBlank - 1; nFirstBlank = nLastNonBlank + 1; } if ((arBlanks == null) || (arBlanks.Length <= 0)) //create new array? { arBlanks = new char[nNumBlanks]; Array.Copy(result, nFirstBlank, arBlanks, 0, nNumBlanks); } else //append at end of existsing array { char[] ar = new char[arBlanks.Length + nNumBlanks]; arBlanks.CopyTo(ar, 0); Array.Copy(result, nFirstBlank, ar, arBlanks.Length, nNumBlanks); arBlanks = ar; } } else //line without white-chars at end //- mark this using zero-sized array { arBlanks = new char[0]; } //set variable... bNewLine = false; } } else if (!Char.IsWhiteSpace(c)) //handle non-white chars { if (nFirstNonBlank < 0) nFirstNonBlank = nPos; nLastNonBlank = nPos; bLastCharGT = (c == '>'); } } streamWriter.Flush(); } /* other overrided Stream functions and properties goes here */ } An instance of this class must be created on each request and assigned to the current Request.Filter property. You can do it in almost any event generated by the HttpApplication class. But if you have pages that renders something different than html code ( text/html MIME type), you should take care of this. In this case, you should test the current MIME type and create (or not) this filter in HttpApplication.PostRequestHandlerExecute event handler: private void Global_PostRequestHandlerExecute(object sender, System.EventArgs e) { if (Response.ContentType == "text/html") Response.Filter = new TrimStream(Response.Filter); } HttpResponse.Filter property gives us an entry point to connect our output filters to an ASP.NET output stream. This property can be used to connect any combination of filters, e.g., my filter and compression filter: Response.Filter = new TrimStream(new CompressStream(Response.Filter)); Also, this is an interesting alternative to IHttpModule-based filters. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/aspnet/RemovingWhiteSpacesAspNet.aspx
crawl-002
refinedweb
1,159
56.86
Tap User Interests with Curated Feeds in Rails Often, when signing up for a new platform, you are asked to select from a list of items in order to see posts that relate to your interests. Some of the sites employing this technique are Quora, Medium and pinterest just to name a few. This is a screenshot from quora right after signing up. In this tutorial, we are going to implement this feature on a normal blog. In the first part, we will create posts and tag them. Later on, we will add user authentication and let users select their interests. Here is a working demo. The complete code can be found on github. Let’s start by creating a new rails app. I am using rails 4.2 in this tutorial: rails new curated-feed The Blog Now let’s create a Posts controller and a post model, respectively: rails g controller Posts index feed new edit show rails g model Posts title:string description:text rake db:migrate The posts we’ll be creating are pretty basic, having just a title and a description. Let’s add a posts resource so we can get all the routes to perform CRUD operations on posts. We’ll also change our root_path to point to the index action of the PostsController: config/routes.rb Rails.application.routes.draw do #create routes for performing all CRUD operations on posts resources :posts #make the homepage the index action of the posts controller root 'posts#index' end Now, add the following code to the controller actions: app/controllers/posts_controller.rb class PostsController < ApplicationController before_action :find_post, only: [:show, :edit, :update, :destroy] def index @posts = Post.all end def feed end def new @post = Post.new end def create @post = Post.new post_params if @post.save flash[:success] = "Post was created successfully" redirect_to @post else render :new end end def show end def edit end def update if @post.update post_params flash[:success] = "The post was updated successfully" redirect_to @post else flash.now[:danger] = "Error while submitting post" render :edit end end def destroy @post.destroy redirect_to root_url end private def post_params params.require(:post).permit(:title, :description, tag_ids: []) end def find_post @post = Post.find(params[:id]) end end The index, create, update, and destroy actions are normal for a typical Rails CRUD application. We’ve declared a before_action to find a post for the show and edit actions. We’ll add code for the feed method later. On to creating the views. We will use bootstrap since it makes styling quite easy: Gemfile gem 'bootstrap-sass' [...] Then run bundle install We need to update our app/files/css/application.scss file so that bootstrap styles can take effect: @import "bootstrap"; @import "bootstrap-sprockets"; First, here is the code for our layout: app/views/layouts/application.html.erb <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <%= link_to 'Curated-feed', root_path, class: 'navbar-brand' %> </div> <div id="navbar"> <ul class="nav navbar-nav pull-right"> <li> </ul> </div> </div> </nav> <div class="container"> <% flash.each do |key, value| %> <div class="alert alert- <%= value %> </div> <% end %> <%= yield %> </div> Always a good idea to make a partial for a form: app/views/posts/_form.html.erb <div class="form-group"> <%= form_for @post do |f| %> <div class="form-group"> <%= f.label :title %> <%= f.text_field :title, class: "form-control" %> </div> <div class="form-group"> <%= f.label :description %> <%= f.text_area :description, class: "form-control" %> </div> <div class="form-group"> <%= f.submit class: "btn btn-primary" %> </div> <% end %> </div> Finally, here’s the new, edit, show, and index views for a post: app/views/posts/new.html.erb <div class="col-md-6 col-md-offset-3"> <h1>Create a new post</h1> <%= render 'form' %> </div> app/views/posts/edit.html.erb <div class="col-md-6 col-md-offset-3"> <h1>Create a new post</h1> <%= render 'form' %> </div> app/views/posts/show.html.erb <div class="col-md-8 col-md-offset-2"> <h1><%= @post.title %></h1> <p><%= @post.description %></p> </div> app/views/posts/index.html.erb <div class="col-md-8 col-md-offset-2"> <h1>All posts</h1> <% @posts.each do |post| %> <ul> <li> <h3><%= post.title %></h3> <p><%= post.description %></p> </li> </ul> <% end %> </div> So, up until now, we’ve stayed within the bounds of Rails’ RESTful approach. Here is a feed view, which is non-standard. app/views/posts/feed.html.erb <div class="col-md-8 col-md-offset-2"> <h1>Feed</h1> </div> Eventually, the feed view will only have posts that are tagged with the user interests. Actually, the code in the feed and index views won’t be different. The only difference is the logic loading the posts in the index and feed actions. Now that we have our views setup, we can seed our database so that we can see the general layout. I am going to seed the database with 15 posts using the faker gem, so add this to the Gemfile: [...] gem 'faker', '~> 1.6', '>= 1.6.6' [...] Run bundle install to install the gem. With the faker gem in our toolbox, the seed file looks like: app/db/seeds.rb 15.times do title = Faker::Lorem.sentence # all options available below description = Faker::Lorem.paragraph Post.create!(title: title, description: description) end Run rake db:seed to populate our database with fake data. If you visit in your browser you should see the random posts. This was boring, though, I am sure you are past the create a blog with Rails level. In the next section, we will talk about adding tags to posts. Tagging Posts Tags and posts, you likely realize a many-to-many relationship, meaning, a tag can be associated with many posts and vice versa. To do this, we need a pivot table. A pivot table is an intermediate table with relationships between two other tables. It links the two tables together by using two foreign keys to define the rows from the other tables. The diagram below will help you understand this better: To begin, generate the Tag model: rails g model Tag title rake db:migrate And the pivot model. Let’s call it post_tag: rails g model Post_tag title post:references tag:references rake db:migrate Update our models to take note of the relationships: app/models/tag.rb [...] has_many :post_tags, dependent: :destroy has_many :posts, through: :post_tags [...] app/models/post.rb [...] has_many :post_tags, dependent: :destroy has_many :tags, through: :post_tags [...] Now that we’ve declared our relationships, it’s time to add the ability to tag posts when they are created or edited. We have to change the line that specifies the permitted params for posts, allowing tag_ids as part of those params: app/controllers/posts_controller.rb def post_params params.require(:post).permit(:title, :description, tag_ids: []) end Note, tag_ids are stored as an array since a post can be tagged with more than one tag. We won’t be creating a tags controller, as all tags are created in the console for this tutorial. However, we will create a tag partial, enabling us to render tags below posts: mkdir app/views/tags touch app/views/tags/_tag.html.erb app/views/tags/tag.html.erb <span class="quiet"><small><%= link_to tag.title, "#" %> </small></span> Let’s create a few tags through the console. Five will do: $ rails c Tag.create!(title: "technology") Tag.create!(title: "politics") Tag.create!(title: "science") Tag.create!(title: "entrepreneurship") Tag.create!(title: "programming") We could have used checkboxes to tag posts, but checkboxes can be limiting. Let’s say we had hundreds of tags, that means hundreds of checkboxes. Messy right? In this tutorial, we will require the chosen-rails gem for this. Chosen is a jQuery plugin that makes long, unwieldy select boxes much more user-friendly. It also makes it possible to filter through tags just by typing in the tag name. Add this to your Gemfile then do a bundle install: Gemfile [...] gem 'compass-rails' gem 'chosen-rails' [...] Update the following files to make chosen effective: app/assets/javascripts/application.js [...] //Make sure you require chosen after jquery. In my case I have it after the turbolinks line //= require chosen-jquery [...]This is for those using jQuery. There's documentation for those of you using prototype on the chosen-rails github repo. app/assets/css/application.scss [...] *= require chosen [...] Then, in your app/assets/javascripts folder, add this CoffeeScript file: app/assets/javascripts/tag-select.js.coffee $ -> # enable chosen js $('.chosen-select').chosen allow_single_deselect: true no_results_text: 'No results matched' width: '450px' Add this snippet inside the form so that users can choose tags: app/views/posts/_form.html.erb <div class="form-group"> <%= f.collection_select :tag_ids, Tag.order(:title), :id, :title, {}, { multiple: true, class: "chosen-select" } %> </div> </code></pre> <p>This is how your form should look like now:</p> <pre><code> <div class="form-group"> <%= form_for @post do |f| %> <div class="form-group"> <%= f.label :title %> <%= f.text_field :title, class: "form-control" %> </div> <div class="form-group"> <%= f.label :description %> <%= f.text_area :description, class: "form-control" %> </div> <div class="form-group"> <%= f.collection_select :tag_ids, Tag.order(:title), :id, :title, {}, { multiple: true, class: "chosen-select" } %> </div> <div class="form-group"> <%= f.submit class: "btn btn-primary" %> </div> <% end %> </div> Try creating a new post. You should be able to add and remove tags similar to how you do it on Stack Overflow. It’s possible to let users create tags if they don’t exist in the list of available options, but that is beyond the scope of this tutorial. We also want to list tags belonging to a post below the post. Update the posts index view as follows: app/views/posts/index.html.erb <div class="col-md-8 col-md-offset-2"> <h1>All posts</h1> <% @posts.each do |post| %> <ul> <li> <h3><%= post.title %></h3> <p><%= post.description %></p> <% if post.tags.any? %> <p>Tags: <%= render post.tags %></p> <% end %> </li> </ul> <% end %> </div> Modelling Users Let’s allow people to sign up on our platform. We will use the devise gem for this: Gemfile [...] gem 'devise', '~> 4.2' [...] Then do a bundle install. Run the devise generator. rails generate devise:install After you run this command, you’ll see a couple of instructions in the console. You can safely ignore these instructions, since we have most of the things set up and won’t be sending any emails today. Let’s generate the User model: rails g devise User rake db:migrate At this point, users are able to sign up and sign in. Update the navigation so that users are able to see sign up, sign in, and logout links: app/views/layouts/application.html.erb <nav class="navbar navbar-default"> <div class="container"> <div class="navbar-header"> <%= link<em>to 'Curated-feed', root</em>path, class: 'navbar-brand' %> </div> <div id="navbar"> <ul class="nav navbar-nav pull-right"> <% unless user_signed_in? %> <li><%= link_to "Sign in", new_user_session_path %></li> <li><%= link_to "Sign up", new_user_registration_path %></li> <% else %> <li><%= link_to "Sign out", destroy_user_session_path, method: :delete %></li> <% end %> </ul> </div> </div> </nav> <div class="container"> <% flash.each do |key, value| %> <div class="alert alert-<%= key %>"> <%= value %> </div> <% end %> <%= yield %> </div> Back to our relationships. A user can subscribe to more than one tag and a tag can have more than one person subscribed to it. This is a many to many relationship. We will need another pivot table for this, so generate the model: rails g model user_tag user:references tag:references rake db:migrate Update the Tag and User models. They should now look like this: app/models/tag.rb class Tag < ActiveRecord::Base has_many :post_tags, dependent: :destroy has_many :posts, through: :post_tags has_many :user_tags, dependent: :destroy has_many :users, through: :user_tags end app/models/user.rb class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :user_tags, dependent: :destroy has_many :tags, through: :user_tags end Generate a users controller: rails g controller users edit update Note that the new and create actions are taken care of by Devise. Devise also provides a method to update a user object without providing a password, so long as you are editing the attributes inside of a UsersController. In our case, we will pass in tag_ids as a part of the params we want to update: app/controllers/users_controller.rb class UsersController < ApplicationController before_action :find_user def edit end def update if @user.update(user_params) flash[:success] = "Interests updated" redirect_to root_path else flash[:alert] = "Interests could not be updated." render :edit end end private def find_user @user = current_user end def user_params params.require(:user).permit(tag_ids: []) end end Now, we can assign tag_ids to a user through the console. Let’s update our routes file to accommodate the edit and update actions of a user. We will also create the view for updating user interests and add the link to update interests in the navigation: config/routes.rb [...] resources :users, only: [:edit, :update] [...] app/views/users/edit.html.erb <div class="col-md-8 col-md-offset-2"> <h1>Please check your interests</h1> <%= form_for (@user) do |f| %> <strong>Interests:</strong> <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :title do |cb| %> <%= cb.label(class: "checkbox-inline input_checkbox") {cb.check_box(class: "checkbox") + cb.text} %> <% end %> <br><br> <div class="form-group"> <%= f.submit class: "button button_flat button_block" %> </div> <% end %> </div> app/views/layouts/application.html.erb [...] <% unless user_signed_in? %> <li><%= link_to "Sign in", new_user_session_path %></li> <li><%= link_to "Sign up", new_user_registration_path %></li> <% else %> <li><%= link_to "Update interests", edit_user_path(current_user) %></li> <li><%= link_to "Sign out", destroy_user_session_path, method: :delete %></li> <% end %> [...] Visit and you will see a list of interests with checkboxes next to them. In the edit view, we are using the named interests when referring to tags. In most cases, however, users are supposed to choose their interests right after signing up before accessing the available content. Let’s make a new controller called registrations_controller and add the code to redirect users to the edit view after signing up: touch app/controllers/registrations_controller.rb app/controllers/registrations_controller.rb class RegistrationsController < Devise::RegistrationsController protected def after_sign_up_path_for(resource) edit_user_path(current_user) end end Modify the routes to use the new controller. We will be updating the devise_for line to look like this: config/routes.rb [...] devise_for :users, controllers: { registrations: "registrations" } [...] After signing up, users will be taken to the edit page where they will update their interests before proceeding. We haven’t yet updated the code in the feed method inside the posts_controller. In the meantime, users will just be redirected to the root_path. Let’s update our feed method now: app/controllers/posts_controller.rb def feed @my_interests = current_user.tag_ids @posts = Post.select { |p| (p.tag_ids & @my_interests).any? } end On the first line, we are getting all the tag_ids belonging to the authenticated user – remember we stored tag_ids as an array. In Ruby we can look for the intersection between two arrays using the & symbol. Fire up our console so you can see what I mean: rails c irb(main):001:0> [1,2,3,4] & [3, 1] => [1, 3] #what is returned irb(main):002:0> [7,3,4,5] & [3, 1] => [3] irb(main):003:0> [2,3,4,5] & [6, 7] => [] If there’s an intersection between two arrays, an array containing the elements common to the two arrays is returned, otherwise an empty array is returned. Let’s go back to the code inside the feed method. Once we get the tag_ids belonging to the authenticated user, we can compare these tag_ids to the tag_ids belonging to a post, if there’s an intersection, the post will be selected and added to the @posts variable. We are now able to load all the posts tagged with any of the interests belonging to the logged in user. Let’s update the feed view: app/views/posts/feed.html.erb <div class="col-md-8 col-md-offset-2"> <h1>Your feed</h1> <% @posts.each do |post| %> <ul> <li> <h3><%= post.title %></h3> <p><%= post.description %></p> <% if post.tags.any? %> <p>Tags: <%= render post.tags %></p> <% end %> </li> </ul> <% end %> </div> Still, visiting the homepage shows all posts, regardless of whether they are tagged with any of the users interests or not. This is because the root_path is mapped to posts#index. Authenticated users should only see relevant posts, not all posts. Devise comes with a handful of methods, including one that makes it possible to define the root_path for authenticated users. In config/routes.rb add this: config/routes.rb [...] authenticated :user do root 'posts#feed', as: "authenticated_root" end root 'posts#index' [...] Now, when we visit, only posts tagged with our interests will show up. Then there’s the problem of the authenticated user not having selected any interests. Does this mean that their feed will be empty? Let’s revisit the feed method inside posts_controller and update it: def feed @my_interests = current_user.tag_ids #check if the authenticated user has any interests if @my_interests.any? @posts = Post.select { |p| (p.tag_ids & @my_interests).any? } else #load all the posts if the authenticated user has not specified any interests @posts = Post.all end end Conclusion This is a simple approach on how to do this. I wanted to talk about many-to-many relationships and how one checks for intersections between different models. You can build on top of this by adding images to tags then displaying the images next to the checkboxes in the view. This is how most sites do it. You can also let users click on the images instead of checkboxes, making AJAX calls to update the user object. There are so many ways to make this fancy. I am learning Rails and enjoy sharing what I have learned, so I hope this tutorial was helpful.
https://www.sitepoint.com/build-curated-interest-feeds-in-rails/
CC-MAIN-2018-09
refinedweb
2,976
58.69
Note: This is part 3 of four-parts Learning GatsbyJs series. This learning post is still in active development and updated regularly. In the previous part 2 of the four-parts series, step-by-step procedures to extend & modify the ‘hello world‘ site components to add new pages, styling site, adding global shared components like <Layout /> with header, footer and other components were discussed. In this series, installing & configuring Gatsby plugins to extend the site to get content data & transform functionality will be over-viewed with a working case example. Part 1: Learning GatsbyJS – Setup & Installation Part 2: Understanding GatsbyJS Building Blocks Part 3: An Overview of Gatsby Plugins & GraphQL (this post) Part 4: Learning to Programmatically Create Pages in Gatsby The objective of this learning-note post series is to explore GatsbyJs to build an simple SPA blog site and document step-by-step procedures to install & setup Gatsby and overview of its data layer. Goal The main goal of this learning-note post is to get an overview of Gatsby data layer. How data in React components from local or external APIs are fetched is described in a previous post. But in Gatsby it makes use of GraphQL a query language to fetch data from local & external APIs together with Gatsby plugins. To quote Gatsby tutorial doc “Gatsby uses GraphQL to enable components to declare the data they need.” GraphQL Use in Gatsby GraphQL, a data query language, was developed by facebook to solve their need to fetch the only the needed data from the external APIs. Gatsby uses this GraphQL, a popular & powerful technology to load desired data into its React component. Send a GraphQL query to your API and get exactly what you need, nothing more and nothing less. GraphQL queries always return predictable results. Apps using GraphQL are fast and stable because they control the data they get, not the server. Source: GraphQL In Gatsby, GraphQL is used to query data using a special syntax from its internal files as well as from external third party APIs. The GraphQL serves as a interface between Gatsby and its data sources. To quote from Gatsby docs “GraphiQL is the GraphQL integrated development environment (IDE). It’s a powerful (and all-around awesome) tool you’ll use often while building Gatsby websites.” In the next section, some use case examples of GraphQL is discussed while using few Gatsby plugins. Note: More detail discussion on GraphQL use in Gatsby will be discussed in a separate post Deep Diving into GraphQL use in Gatsby (in preparation). Gatsby Plugins Gatsby plugins are Node.js packages and are install using NPM. Gatsby utilizes JAMstack (JavaScript, APIs & Markup) to build projects. Gatsby plugins library is robust to extend & modify functionality of GatsbyJs core. There are three categories of plugins: - Source Plugins: Data in Gatsby sites can be from internal local files and/or external databases, APIs, CMSs, etc. The source plugins fetch data from their sources. This plugin adds nodesin Gatsby data system and thus permits data transformation with transformer plugins into usable format. For example, if we would like to fetch data from local files, the gatsby-source-filesystem plugin knows how to fetch data from file system. Similarly, the gatsby-source-wordpress plugin fetch data from WordPress API. - Transformer Plugins: The data fetched from source plugin are in various file format. The transformer plugins transform the fetched raw data by the source plugins into usable format to build Gatsby sites. For example, gatsby-tranformer-remark plugin transforms data in markdown files into HTML to display in a browser. - Functional Plugins: These groups of plugin extend functionality of Gatsby. For example, gatysby-plugin-react-helmet enhances Gatsby functionality with react-helmet to manipulate head of Gatsby document (eg, to add SEO etc.,). In Gatsby sites, most contents are created with markdown, GraphQL to query markdown files (eg. API) and delivery using React components. In this learning-note posts, the following two Gatsby source and Gatsby transformer plugins will be installed and explored to extend the Gatsby site project. To get started, the following two plugins will be install with npm in project folder: #! install plugin in project folder npm install --save gatsby-transformer-remark gatsby-source-filesystem Gatsby transformer remark: This plugin uses Remark library & ecosystem to parse markdown files in .md format into HTML. Gatsby source filesystem: This Gatsby source plugin parses files within a directory for further parsing by other plugins & help to read the markdown files. Configuring Plugins Most plugins have their default configuration but can be customized by overwriting with options. Installing Working Example Site To start fresh, a new site named ‘hello-plugin‘ was setup with the Gatsby default starter hello-world as described previously. Starting Point As a starting point, the site was setup similar to described in the previous post with a shared <Layout /> component and three page components. The commonly use section of the sites (header, main navigation, footer) and global styles included in layout.js component as shown below: layout.js(middle) and header.jscomponents as described in the previous post. The <Layout /> & <Header /> Components To refresh, the <Layout /> and refactored <Header /> components from the previous posts are shown in the middle-panel & right-panel, respectively (above). A browser display of starting point of the project site is shown below: header.js, footer.jsand layout.jscomponents with basic styling. Extending With Plugins & GraphQL Query Some common site data like site title, description, author etc., can be added as siteMetadata object at one location at gatsby-config.js located at the root of Gatsby site project. These data can be accessed from other components by referencing that location. 1: Editing gatsby-config.js File Some basic site data like title (for entire site), pagetitle (for page), description are added in gatsby-config.js file as shown below. // gatsby-config.js module.exports = { siteMetadata: { title: 'Hello siteMetadata', pagetitle: `Title from siteMetadata`, description: 'Gatsby - Learning by Doing!', }, plugin: [ ], } After restarting development server, the above information stored in siteMetadata object is available for refrence from Gatsby page components with GraphQL query. 2: Using Page Query In the example below, pagetitle data stored at siteMetadata object in gatsby-config.js is available for reference using GraphQL query and the query results can be mapped in a page (eg., about.js) component. // page query example import React from "react" import { graphql } from "gatsby" import Layout from "../components/layout" export default ( {data} ) => ( <Layout> <h1>This {data.site.siteMetadata.pagetitle}</h1> <p>Content for about page. A react way!</p> <img src="" alt="" /> </Layout> ) // page query export const query = graphql` query { site { siteMetadata { pagetitle } } }` In the example above, pagetitle data location in siteMetadata is referenced (line: 9) in a page component (eg., about.js). The GraphQL is imported to the page component (line 4) then the graphql query for pagetitle is appended in the component (lines: 15-22). Its output in the browser is shown in the figure below. Additional Information: Use a page query | Gatsby Tutorial 3: Using StaticQuery The Gatsby’s StaticQuery was introduced as new API in Gatsby V2 to allow non-page component to retrieve data with GraphQL query. In the example below, its hook version – useStaticQuery is used to reference site title data stored at siteMetadata object by referencing in src/components/header.js component, as described in the Gatsby tutorial. //src/components/header.js import React from "react" import { useStaticQuery, Link, graphql } from "gatsby" import "../styles/header.css" export default ( ) => { const data = useStaticQuery( graphql` query { site { siteMetadata { title } } } ` ) return ( <section className="header"> <div className="site-title wrapper"> <Link to="/"> <h3>{data.site.siteMetadata.title}</h3> </Link> <ul className="menu"> <Link to="/">Home</Link> <Link to="/about/">About</Link> <Link to="/contact/">Contact</Link> </ul> </div> </section> ) } In the example above, the useStaticQuery was imported from Gatsby (line 3). Then using GraphQL, site title graphql query was defined in header.js component (lines: 7-16) and the title data from siteMetadata was referenced in line 23. Its output displayed in the browser is shown in the figure below. Additional Information: Use a StaticQuery | Gatsby Tutorial 4: Viewing in a Browser Restart the development server and open up the browser at localhost:8000 and view output from above queries. gatsby-config.jssiteMetadata. Extending with Source Plugins In this section, we will explore using gatsby-source-filesystem plugin & GraphQL to full data from a Gatsby site. Step 1: Plugin Installation Install source plugin gatsby-source-filesystem at the root of the project with npm or yarn, as shown below: #! install with plugin sudo npm install --save gatsby-source-filesystem #! install with yarn sudo yarn add gatsby-source-filesystem Depending on the privacy setting of the machine, use of sudo might not be necessary. Step 2: Add & Configure the Plugin Add the gatsby-source-filesystem plugin into the gatsby-config.js file and configure it as shown below: // gatsby-config.js module.exports = { siteMetadata: { // .. }, plugins: [ //add source plugin { resolve: `gatsby-source-filesystem`, options: { name: `src`, path: `${__dirname}/src/`, }, }, // add other plugins ], } Step 3: Explore GraphQL Query in the Browser Restart the development server and open up the browser and explore GraphQL at localhost:8000/___graphql . allFileadded by the gatsby-source-filesystemplugin & basic GraphQl query (left panel) & queried data output (right panel). In the screenshot above, the allFile in the left panel was available through gatsby-source-filesystem plugin. Next, play around and make a simple query as shown above and run the query which shows available data from from /src folder on the right panel. The Gatsby source plugins bring data into Gatsby’s site from various external sources. Next we will use the above GraphlQL query to build a simple page to list all the project files from /src folder in a browser, as demonstrated in the Gatsby tutorial. Step 4: Build Page Using GraphlQL query Using the GraphlQL query from the previous section, a React page component was built src/pages/my-files.js as described in the Gatsby tutorial. my-file.jscomponent with appended GraphQL query (left panel) and displayed list of site’s file in the browser (right panel). The above my-files.js the GraphlQL query created in previous section were appended in src/pages/my-files.js react page component (lines: 37-50, left panel) to print list of files in a browser (right panel). In the example above, the gatsby-source-filesystem plugin was demonstrated to fetch data stored in project’s /src folder. However, there are many other Gatsby source plugins to fetch data from external APIs like the WordPress, Drupal, instagram, shopify, google sheets and many others. Extending with Transformer Plugins In the previous section, it was discussed how Gatsby source plugins can fetch data local and external resources.The data fetched by Gatsby source plugins come in different file formats and the Gatsby transformer plugins transform those raw data into Gatsby’s data system to be able use in Gatsby sites. For example, file written in popular markdown format to create posts in Gatsby can be transformed with gatsby-transformer-remark plugin which transforms yaml markdown files into HTML suitable to display in a browser. Likewise, gatsby-source-wordpress plugin fetch data from WordPress REST API and make available to use in Gatsby sites. In this section, we will discuss how gatsby-transformer-remark plugin & GraphQL is used to transform markdown files from /src folder into HTML to display posts in our Gatsby site as explained in Gatsby tutorial. Step 1: Create Posts with Markdown syntax Few dummy posts are created in src/posts/ folder in markdown format as shown below. --- title: Hello World From Gatsby date: "2019-7-11" author: Mary Jones --- This is is my second test gatsby post. It should be written in mark Link from Unsplash <img src="" alt="" /> Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Additional information on markdown files: Basic Syntax | Markdown Guide Step 2:Add gatsby-transforer-remark plugin Add gatsby-transforer-remark plugin and configure in gatsby-config.js file at the root of the project folder. #! install plugin npm npm install --save gatsby-transformer-remark #! install with yarn yarn add gatsby-transformer-remark Next add the plugin to gatsby-config.js file, just below (lines: 15-23) and configure as as shown below. // gatsby-config.js module.exports = { siteMetadata: { // .. }, plugins: [ //add source plugin { resolve: `gatsby-source-filesystem`, options: { name: `src`, path: `${__dirname}/src/`, }, }, // add transformer plugins `gatsby-transformer-remark`, { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/src/posts/`, }, }, ], } In the examples above, the resolve & options section (lines: 17-23) can be omitted too. Step 3: View GraphQL Query in the Browser Start the development server and open up the browser and explore GraphQL at l ocalhost:8000/___graphql . allMardownRemark, frontmatter& nodes object added by gatsby-transformer-remarkplugin (left-panel), an example query of allMarkdownRemarknode (middle-panel) and queried data output (right-panel). In the example above, the allMarkdownremark (left panel, above) and markdownRemark (not visible) are added by the gatsby-tranformer-remark plugin and available for markdownRemark node query. As done previously with source plugin (above) some basic query were made (middle panel) to display title, date, author from markdownRemark node (right panel). Step 4: Create a list of Markdown files in src/posts/ folder For creating a list of posts (in mardown format) and displaying them in the front (home) page of our site, the codes in src/pages/index.js component requires refactoring (as shown below) by mapping markdownRemark nodes (line 13, left panel) followed by listing content below (lines: 14-19). The component is then appended with the Graphql query (lines: 26-42). The list of three markdown posts is listed, as expected, in the home page (right panel, below). The above list of markdown posts in the front (home) page of project site looks great with title, date and excerpt display but there is further work to do. This does not allow to view the entire post content nor there is link to individual post. To view separate pages for each blog post, we need to create new post components to query each post individually. That’s is a hassle! but new pages can be created programmatically with Gatsby’s Node createPages API. Wrapping Up In this learning-note post, we only scratched the use of Gatsby source & transformer plugins together with GraphQL query to create simple page components. In the next learning-note post, how Gatsby could programmatically create pages from Gatsby data by mapping GraphQL query results using Node createPages API will be discussed. Next: Learning to Programmatically Create Pages in Gatsby Useful resources While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.
https://tinjurewp.com/jsblog/an-overview-of-gatsby-plugins-graphql/
CC-MAIN-2022-05
refinedweb
2,462
53.71
Copy selected songs to a new folder Okay, so you play with MDC you select a bunch of songs out of your source directory and now you want to burn them. Liat preferred to have all the selected songs in a dedicated folder so she can rename songs, rearrange them and examine previous CDs. With MDC 1.0 it was a grueling manual process. Liat fired up an explorer window next to MDC, selected all the files she selected previously in MDC, create a new folder and copy the files there. In MDC 2.0 this task can be done directly. I added a "Make CD..." button (see Figure 4) that opens a folder selection dialog that allows you to browse to an existing folder or create a new one. Once you select a folder, the selected items are copied to the target folder. As usual XAML makes it easy to add a button. The button is docked to the right side of the bottom panel, it has a tooltip and it is disabled initially (can't make a CD before some songs are selected). The Click event is hooked up to the MakeCD_Click() event handler: <Button Name="makeCD" DockPanel. Make CD... </Button> There button is enabled/disabled based on the selection state of the files list. This can be done with data binding, but I opted in this case to use imperative code in the files_SelectionChanged() event handler that's being called whenever the selection changes. It is just one line and I handle in the same place enabling/disabling also the 'Select All' and 'Unselect All' buttons. The 'Select All' button is enabled if not all the items are selected. The 'Unselect All' and 'Make CD...' buttons are enabled if at least one item is selected. selectAll.IsEnabled = files.SelectedItems.Count < files.Items.Count; unselectAll.IsEnabled = files.SelectedItems.Count > 0; makeCD.IsEnabled = files.SelectedItems.Count > 0; The MakeCD_Click() event handler implements two requested features: copying selected files to a folder and also exporting the song list to a CSV file. The first step is to select the target folder. I reuse here there _folderBrowserDialog I use for selecting the source folder. In order to remember the source folder I save it in a temporary variable and restore it after the user selected a target folder. If the user selects the the same folder as the source folder MDC displays a message box and takes no action (no point in copying the files to the same folder, there are already there. private void MakeCD_Click(object sender, RoutedEventArgs e) { string savedPath = _folderBrowserDialog.SelectedPath; _folderBrowserDialog.ShowNewFolderButton = true; DialogResult r = _folderBrowserDialog.ShowDialog(); if (r == System.Windows.Forms.DialogResult.OK) { string path = _folderBrowserDialog.SelectedPath; // check that the target folder is different than the source folder if (path == savedPath) { System.Windows.MessageBox.Show( "Target folder is the same as source folder. no action taken"); return; } // restore selected path _folderBrowserDialog.SelectedPath = savedPath; Now, it's time to actually copy all the selected files to the target folder. The .NET Framework provides in the System.IO namespace several classes to help with path manipulation and file operations. Many of these operations are implemented as static methods, which makes a lot of sense for operations like Path.Combine or File.Copy that don't have any state worth remembering for future operations: // copy selected songs to target folder foreach (TrackInfo t in files.SelectedItems) { var src = System.IO.Path.Combine(savedPath, t.Name); var dst = System.IO.Path.Combine(path, t.Name); System.IO.File.Copy(src, dst); } Exporting the song list to a CSV file This is another feature Liat requested and it is also implemented in the MakeCD_Click() event handler immediately after copying the selected songs. The format is very simple. It is just a two-column list of Name, Duration for each selected item (see Figure 5). Liat can edit it later in Excel and add her class program next to the songs. It goes something like: go fast for 5 minutes, then accelerate for 8 more minutes and when you can't go any faster increase the resistance until you start crying. The Excel native file format is very complicated because it supports a lot of functionality. But, just for importing tabular data into Excel you can use a CSV (Comma-separated values) file. It is very simple to create such a file. You have to be careful to make sure your values don't contain a comma (I don't do it here). The filename is track_list.csv and it is stored in the target folder together with all the songs. I utilize the 'using' statement that ensures correct use of IDisposable objects. These object have a Dispose() method that should be called to ensure proper cleanup and the using statement does it at the end of the block even if an exception is thrown. I like to think of it as the C# equivalent of the C++ RAII design pattern (). The using statement creates the track_list.csv text file, which is guarantied to be closed properly at the end of the block. Inside the using block the code writes a header "Name", "Duration" to the sw StreamWriter object and then iterates over the selected TrackInfo items and writes each item's name and duration with some formatting to make it look nicer. // Create CSV file with track list var filename = System.IO.Path.Combine(path, "track_list.csv"); using (var sw = File.CreateText(filename)) { sw.WriteLine("Name,Duration"); foreach (TrackInfo t in files.SelectedItems) { var d = new DateTime(t.Duration.Ticks); var name = System.IO.Path.GetFileNameWithoutExtension(t.Name); sw.WriteLine(name + "," + d.ToString("mm:ss")); } }
http://www.drdobbs.com/architecture-and-design/your-own-mp3-duration-calculator-part-2/223101349?pgno=4
CC-MAIN-2016-30
refinedweb
944
57.37
rxi/vec - a simple C vector library C provides arrays, but these do less than most other languages’ array structures. For instance, if you want to push a new element onto the end of your array, you must go through the work of resizing it with realloc to make room for the new element. For this, you need to keep track of the array length separately. Then to avoid constant reallocation you keep a separate length and capacity. Soon you’ve written a vector library. Instead, you can use someone else’s vector library. I like rxi/vec. Here’s an example of using it. Installation: $ brew install clib $ clib install rxi/vec $ find . . ./deps ./deps/vec ./deps/vec/package.json ./deps/vec/vec.c ./deps/vec/vec.h Example program: #include <stdio.h> #include "./deps/vec/vec.h" typedef vec_t(char*) vec_string_t; void print_vec(vec_string_t * strings) { size_t i; char * string; vec_foreach(strings, string, i) { printf("strings[%zu] = \"%s\"\n", i, string); } } int main() { vec_string_t strings; vec_init(&strings); // memset(&strings, 0, sizeof(strings)); vec_push(&strings, "hello"); vec_push(&strings, "world"); print_vec(&strings); char* world = vec_pop(&strings); printf("popped %s\n", world); print_vec(&strings); vec_deinit(&strings); return 0; } Running it gives: $ clang main.c deps/vec/vec.c $ ./a.out strings[0] = "hello" strings[1] = "world" popped world strings[0] = "hello" In a future post, I’ll show how rxi/vec is implemented..
https://jameshfisher.com/2017/04/06/rxi-vec.html
CC-MAIN-2019-09
refinedweb
231
64.41
.\" FORM 1" .TH PERLFORM 1 "2004-11-05" "perl v5.8.6" "Perl Programmers Reference Guide" .SH "NAME" perlform \- Perl formats .SH "DESCRIPTION" .IX Header \s-1FORTRAN:\s0 \fIformat()\fR to declare and \fIwrite()\fR to execute; see their entries in perlfunc. Fortunately, the layout is much more legible, more like \s-1BASIC\s0's \s-1PRINT\s0 \s-1USING\s0 statement. Think of it as a poor man's \fInroff\fR\|(1). .PP Formats, like packages and subroutines, are declared rather than executed, so they may occur at any point in your program. (Usually it's best to keep them all together though.) They have their own namespace apart from all the other \*(L"types\*(R" in Perl. This means that if you have a function named \*(L"Foo\*(R", it is not the same thing as having a format named \&\*(L"Foo\*(R". However, the default name for the format associated with a given filehandle is the same as the name of the filehandle. Thus, the default format for \s-1STDOUT\s0 is named \*(L"\s-1STDOUT\s0\*(R", and the default format for filehandle \&\s-1TEMP\s0 is named \*(L"\s-1TEMP\s0\*(R". They just look the same. They aren't. .PP Output record formats are declared as follows: .PP .Vb 3 \& format NAME = \& FORMLIST \& . .Ve .PP If the name is omitted, format \*(L"\s-1STDOUT\s0\*(R" is defined. A single \*(L".\*(R" in column 1 is used to terminate a format. \s-1FORMLIST\s0 consists of a sequence of lines, each of which may be one of three types: .IP "1." 4 A comment, indicated by putting a '#' in the first column. .IP "2." 4 A \*(L"picture\*(R" line giving the format for one output line. .IP "3." 4 An argument line supplying values to plug into the previous picture line. .PP: .PP .Vb 13 \& @ start of regular field \& ^ start of special field \& < pad character for left adjustification \& | pad character for centering \& > pad character for right adjustificat \& # .Ve .PP Each field in a picture line starts with either \*(L"@\*(R" (at) or \*(L"^\*(R" (caret), indicating what we'll call, respectively, a \*(L"regular\*(R" or \*(L"special\*(R" field. The choice of pad characters determines whether a field is textual or numeric. The tilde operators are not part of a field. Let's look at the various possibilities in detail. .Sh "Text Fields" .IX Subsection "Text Fields" The length of the field is supplied by padding out the field with multiple "<\*(L", \*(R">\*(L", or \*(R"|\*(L" characters to specify a non-numeric field with, respectively, left justification, right justification, or centering. For a regular field, the value (up to the first newline) is taken and printed according to the selected justification, truncating excess characters. If you terminate a text field with \*(R"...", three dots will be shown if the value is truncated. A special text field may be used to do rudimentary multi-line text block filling; see \*(L"Using Fill Mode\*(R" for details. .PP .Vb 7 \& Example: \& format STDOUT = \& @<<<<<< @|||||| @>>>>>> \& "left", "middle", "right" \& . \& Output: \& left middle right .Ve .Sh "Numeric Fields" .IX Subsection "Numeric Fields" Using \*(L"#\*(R" as a padding character specifies a numeric field, with right justification. An optional \*(L".\*(R" defines the position of the decimal point. With a \*(L"0\*(R" (zero) instead of the first \*(L"#\*(R", the formatted number will be padded with leading zeroes if necessary. A special numeric field is blanked out if the value is undefined. If the resulting value would exceed the width specified the field is filled with \*(L"#\*(R" as overflow evidence. .PP .Vb 7 \& Example: \& format STDOUT = \& @### @.### @##.### @### @### ^#### \& 42, 3.1415, undef, 0, 10000, undef \& . \& Output: \& 42 3.142 0.000 0 #### .Ve .Sh "The Field @* for Variable Width Multi-Line Text" .IX Subsection "The Field @* for Variable Width Multi-Line Text" The field \*(L"@*\*(R" can be used for printing multi\-line, nontruncated values; it should (but need not) appear by itself on a line. A final line feed is chomped off, but all other characters are emitted verbatim. .Sh "The Field ^* for Variable Width One-line-at-a-time Text" .IX Subsection "The Field ^* for Variable Width One-line-at-a-time Text" Like \*(L"@*\*(R", this is a variable width field. The value supplied must be a scalar variable. Perl puts the first line (up to the first \*(L"\en\*(R") of the text into the field, and then chops off the front of the string so that the next time the variable is referenced, more of the text can be printed. The variable will \fInot\fR be restored. .PP .Vb 12 \& Example: \& $text = "line 1\enline 2\enline 3"; \& format STDOUT = \& Text: ^* \& $text \& ~~ ^* \& $text \& . \& Output: \& Text: line 1 \& line 2 \& line 3 .Ve .Sh "Specifying Values" .IX Subsection "Specifying Values" \*(L"#\*(R" characters \fBwithout\fR an embedded \*(L".\*(R"), the character used for the decimal point is \fBalways\fR determined by the current \s-1LC_NUMERIC\s0 locale. This means that, if, for example, the run-time environment happens to specify a German locale, \*(L",\*(R" will be used instead of the default \*(L".\*(R". See perllocale and \*(L"\s-1WARNINGS\s0\*(R" for more information. .Sh "Using Fill Mode" .IX Subsection "Using Fill Mode" \fIwrite()\fR call, and is not restored.) The next portion of text is determined by a crude line breaking algorithm. You may use the carriage return character (\f(CW\*(C`\er\*(C'\fR) to force a line break. You can change which characters are legal to break on by changing the variable \f(CW$:\fR (that's \&\f(CW$FORMAT_LINE_BREAK_CHARACTERS\fR if you're using the English module) to a list of the desired characters. .PP Normally you would use a sequence of fields in a vertical stack associated with the same scalar variable to print out a block of text. You might wish to end the final field with the text \*(L"...\*(R", which will appear in the output if the text was too long to appear in its entirety. .Sh "Suppressing Lines Where All Fields Are Void" .IX Subsection "Suppressing Lines Where All Fields Are Void" Using caret fields can produce lines where all fields are blank. You can suppress such lines by putting a \*(L"~\*(R" (tilde) character anywhere in the line. The tilde will be translated to a space upon output. .Sh "Repeating Format Lines" .IX Subsection "Repeating Format Lines" If you put two contiguous tilde characters \*(L"~~\*(R"! (\f(CW\*(C`shift(@f)\*(C'\fR is a simple example that would work.) Don't use a regular (at) numeric field in such lines, because it will never go blank. .Sh "Top of Form Processing" .IX Subsection "Top of Form Processing" Top-of-form processing is by default handled by a format with the same name as the current filehandle with \*(L"_TOP\*(R" concatenated to it. It's triggered at the top of each page. See \*(L"write\*(R" in perlfunc. .PP Examples: .PP .Vb 10 \& # a report on the /etc/passwd file \& format STDOUT_TOP = \& Passwd File \& Name Login Office Uid Gid Home \& ------------------------------------------------------------------ \& . \& format STDOUT = \& @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<< \& $name, $login, $office,$uid,$gid, $home \& . .Ve .PP .Vb 29 \& # a report from a bug report form \& format STDOUT_TOP = \& Bug Reports \& @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>> \& $system, $%, $date \& ------------------------------------------------------------------ \& . \& format STDOUT = \& Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $subject \& Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $index, $description \& Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $priority, $date, $description \& From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $from, $description \& Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $programmer, $description \& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $description \& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $description \& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $description \& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $description \& ~ ^<<<<<<<<<<<<<<<<<<<<<<<... \& $description \& . .Ve .PP It is possible to intermix \fIprint()\fRs with \fIwrite()\fRs on the same output channel, but you'll have to handle \f(CW\*(C`$\-\*(C'\fR (\f(CW$FORMAT_LINES_LEFT\fR) yourself. .Sh "Format Variables" .IX Subsection "Format Variables" The current format name is stored in the variable \f(CW$~\fR (\f(CW$FORMAT_NAME\fR), and the current top of form format name is in \f(CW$^\fR (\f(CW$FORMAT_TOP_NAME\fR). The current output page number is stored in \f(CW$%\fR (\f(CW$FORMAT_PAGE_NUMBER\fR), and the number of lines on the page is in \f(CW$=\fR (\f(CW$FORMAT_LINES_PER_PAGE\fR). Whether to autoflush output on this handle is stored in \f(CW$|\fR (\f(CW$OUTPUT_AUTOFLUSH\fR). The string output before each top of page (except the first) is stored in \f(CW$^L\fR (\f(CW$FORMAT_FORMFEED\fR). These variables are set on a per-filehandle basis, so you'll need to \fIselect()\fR into a different one to affect them: .PP .Vb 4 \& select((select(OUTF), \& $~ = "My_Other_Format", \& $^ = "My_Top_Format" \& )[0]); .Ve .PP): .PP .Vb 4 \& $ofh = select(OUTF); \& $~ = "My_Other_Format"; \& $^ = "My_Top_Format"; \& select($ofh); .Ve .PP If you use the English module, you can even read the variable names: .PP .Vb 5 \& use English '-no_match_vars'; \& $ofh = select(OUTF); \& $FORMAT_NAME = "My_Other_Format"; \& $FORMAT_TOP_NAME = "My_Top_Format"; \& select($ofh); .Ve .PP But you still have those funny \fIselect()\fRs. So just use the FileHandle module. Now, you can access these special variables using lowercase method names instead: .PP .Vb 3 \& use FileHandle; \& format_name OUTF "My_Other_Format"; \& format_top_name OUTF "My_Top_Format"; .Ve .PP Much better! .SH "NOTES" .IX Header "NOTES" Because the values line may contain arbitrary expressions (for at fields, not caret fields), you can farm out more sophisticated processing to other functions, like \fIsprintf()\fR or one of your own. For example: .PP .Vb 4 \& format Ident = \& @<<<<<<<<<<<<<<< \& &commify($n) \& . .Ve .PP To get a real at or caret into the field, do this: .PP .Vb 4 \& format Ident = \& I have an @ here. \& "@" \& . .Ve .PP To center a whole line of text, do something like this: .PP .Vb 4 \& format Ident = \& @||||||||||||||||||||||||||||||||||||||||||||||| \& "Some text line" \& . .Ve .PP There is no builtin way to say \*(L"float this to the right hand side of the page, however wide it is.\*(R" You have to specify where it goes. The truly desperate can generate their own format on the fly, based on the current number of columns, and then \fIeval()\fR it: .PP .Vb 9 \& $format = "format STDOUT = \en" \& . '^' . '<' x $cols . "\en" \& . '$entry' . "\en" \& . "\et^" . "<" x ($cols-8) . "~~\en" \& . '$entry' . "\en" \& . ".\en"; \& print $format if $Debugging; \& eval $format; \& die $@ if $@; .Ve .PP Which would generate a format looking something like this: .PP .Vb 6 \& format STDOUT = \& ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \& $entry \& ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~ \& $entry \& . .Ve .PP Here's a little program that's somewhat like \fIfmt\fR\|(1): .PP .Vb 3 \& format = \& ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~ \& $_ .Ve .PP .Vb 1 \& . .Ve .PP .Vb 5 \& $/ = ''; \& while (<>) { \& s/\es*\en\es*/ /g; \& write; \& } .Ve .Sh "Footers" .IX Subsection "Footers" While \f(CW$FORMAT_TOP_NAME\fR contains the name of the current header format, there is no corresponding mechanism to automatically do the same thing for a footer. Not knowing how big a format is going to be until you evaluate it is one of the major problems. It's on the \s-1TODO\s0 list. .PP Here's one strategy: If you have a fixed-size footer, you can get footers by checking \f(CW$FORMAT_LINES_LEFT\fR before each \fIwrite()\fR and print the footer yourself if necessary. .PP Here's another strategy: Open a pipe to yourself, using \f(CW\*(C`open(MYSELF, "|\-")\*(C'\fR (see \*(L"\fIopen()\fR\*(R" in perlfunc) and always \fIwrite()\fR to \s-1MYSELF\s0 instead of \s-1STDOUT\s0. Have your child process massage its \s-1STDIN\s0 to rearrange headers and footers however you like. Not very convenient, but doable. .Sh "Accessing Formatting Internals" .IX Subsection "Accessing Formatting Internals" For low-level access to the formatting mechanism. you may use \fIformline()\fR and access \f(CW$^A\fR (the \f(CW$ACCUMULATOR\fR variable) directly. .PP For example: .PP .Vb 3 \& $str = formline <<'END', 1,2,3; \& @<<< @||| @>>> \& END .Ve .PP .Vb 1 \& print "Wow, I just stored `$^A' in the accumulator!\en"; .Ve .PP Or to make an \fIswrite()\fR subroutine, which is to \fIwrite()\fR what \fIsprintf()\fR is to \fIprintf()\fR, do this: .PP .Vb 8 \& use Carp; \& sub swrite { \& croak "usage: swrite PICTURE ARGS" unless @_; \& my $format = shift; \& $^A = ""; \& formline($format,@_); \& return $^A; \& } .Ve .PP .Vb 5 \& $string = swrite(<<'END', 1, 2, 3); \& Check me out \& @<<< @||| @>>> \& END \& print $string; .Ve .SH "WARNINGS" .IX Header \&\s-1SMTP\s0 cutoff. .PP Lexical variables (declared with \*(L"my\*(R") are not visible within a format unless the format is declared within the scope of the lexical variable. (They weren't visible at all before version 5.001.) .PP Formats are the only part of Perl that unconditionally use information from a program's locale; if a program's environment specifies an \&\s-1LC_NUMERIC\s0 locale, it is always used to specify the decimal point character in formatted output. Perl ignores all other aspects of locale handling unless the \f(CW\*(C`use locale\*(C'\fR pragma is in effect. Formatted output cannot be controlled by \f(CW\*(C`use locale\*(C'\fR because the pragma is tied to the block structure of the program, and, for historical reasons, formats exist outside that block structure. See perllocale for further discussion of locale handling. .PP Within strings that are to be displayed in a fixed length text field, each control character is substituted by a space. (But remember the special meaning of \f(CW\*(C`\er\*(C'\fR when using fill mode.) This is done to avoid misalignment when control characters \*(L"disappear\*(R" on some output media.
http://www.fiveanddime.net/ss/man-unformatted/man1/perlform.1
crawl-003
refinedweb
2,205
66.13
Pretty much what the name is, this is my port of Freespace 2 to Homeworld 2. Ever wanted to command a fleet of Terran, Vasudan, or Shivan ships? Well here ya go! Working. No articles were found matching the criteria specified. We suggest you try the article list with no filter applied, to browse all available. Join now to share your own content, we welcome creators and consumers alike and look forward to your comments. Well my no team color version seems good now. So this is pretty much that, but of course with the team color enabled ships. Christmas gift for FSFC players I guess :P Again this is an attempt to fix the flashing thing, perhaps this time it is? I did find some things that prefer this mod than the 2015 version i Really wish this mod would get some update, like more maps and other things. Amazing mod, but for some reason the mod freezes while it's loading a game. Anyone have any ideas? well does it do it once or again and again? I'm assuming you tried playing more than once, if it keeps doing it I have no idea, works fine for me. If you don't mind me asking, how did you get the Freespace models into homeworld? well its a relavtivly simple process I guess. open FS .pof and export as .cob open .cob with 3d exploration, uncheck parts like LODs besides LOD0, debris and animated turrets (cause you will want these things as seperate objects for HW2 use) export to .obj from there with it set to objects to save to visible objects only, will also generate .mtl file you will want to have to see which textures you need import .obj into a hw2 .hod file and go from there (adding turrets and stuff, time consuming especially for FS ships since they have a lot) yeah...took a while for the capital ships This is a great mod. You've done an amazing job :) Maybe you could add some of the skirmish options here like the ones in the 'Dynamic Deathmatch Mod'? And maybe you could change the main menu button texts to something less silly? :p where to download yall? um...like 2 inches above this message? ive got a suggestion,u said the ai needs base ships,then why not have an arcadia space station for gta,gtva,and some made up station for the shivans,based on how those shivan structures looked like in that freespace 2 mission with captured shivan fighters ,cut down production times a bit,and disable production on destroyers,its like the battlestar mod,start with a station,and build from there. well I did want to avoid non-canon ships, though perhaps I could have versions that make use of some...no promises here btw, do not have the time I would like to work on mods these days. You could always make the Shivan base one of those large subspace gates. It'd seem like they're calling in more ships from where ever they come from. And it's canon! i think it will be inevitable cause there arent many canon freespace ships,and thats a problem own,anyways dont give up on this mod,it is very well made and by far the best hw2 freespace mod out there,it'll be sad for alot of freespace fans if this mods dies.... well nothing I do is really dead, seeing as I'm still here and all, will always care about Homeworld...can't see myself ever forgetting it
http://www.moddb.com/mods/freespacefleet-command
CC-MAIN-2017-43
refinedweb
602
80.72
# WebRTC streaming in and around virtual reality ![](https://habrastorage.org/r/w780q1/webt/jw/qo/v9/jwqov9cav_juhuolm3cwf8xm-aw.jpeg) Virtual reality is on the rise these days. The equipment that was previously the exclusive preserve of ~~crazy scientists~~ geeks with big money ~~from the Ministry of Defense~~ back in the The Lawnmower Man days, is currently affordable for ordinary people; those whose pockets are empty, can assemble a VR headset from cardboard and a smartphone according to many recipes. VR can bring much more benefits than 3-4-5-6-7-something-D cinema. Let's say you live in Chicago and want to invest honestly earned resources to i.e. real estate — somewhere along the coast of Florida. As you know, it is better to choose housing yourself and on the spot, but what if you cannot devote enough time to this? This is where virtual reality is needed. Just imagine: the agent sets up a special camera in the room, and you, without leaving your favorite chair, can examine this room, turn your head, and even appreciate the ceiling with a 18th century mural “Greek gods partying!” Then, still without leaving the place, you may wonder what your children are doing in the kindergarten. And again: the camera is in the game room, and you can get an immersive sensory experience by examining all the corners where your children are ~~hiding~~. Now we’ll figure out how to make sure that everything works, and the ~~real estate agents~~ children do not scatter. The nuances of VR picture ------------------------- Technically, a VR media stream is no different from an ordinary one; it is a video track plus an audio track. But there is a nuance. VR stream assumes a stereo image. A special camera looks at the world with two ~~eyes~~ lenses open wide (180 degrees), like a robot. ![](https://habrastorage.org/r/w780q1/webt/yv/wq/gc/yvwqgcgjjnblruhtjnhduw3_xwq.jpeg) the pictures merge in one frame, ![](https://habrastorage.org/r/w1560/webt/ot/mn/li/otmnli2-vsrodo4wcjplsdmuw50.png) therefore, a special player should be installed on the viewer’s device, which will make two pictures one. As you can see, the aspect ratio of the frame is 2:1, which makes a FullHD picture for each eye. The nuances of VR broadcast --------------------------- So, we are talking about broadcasting 4K streams with a high bit rate. What do we have? We have RTMP and WebRTC. RTMP is ~~cheap,~~ reliable and practical. It uses TCP, which is useful in case of not-so-good channels. There are various software solutions for the publishing client, both paid and free. However, despite all its merits, RTMP has high latency. In one of the previous articles, we noted a delay of 2-3 seconds in a 720p stream. In some cases, delays are acceptable, but VR will lag behind reality, and the children will surely scatter. WebRTC is really cool. With good channels, delays are measured in milliseconds, and reality will remain reality. But there are nuances. First, by default WebRTC runs on UDP, which will lead to losses at the slightest deterioration in channel quality. For a 4K stream, any little thing on the channel is already a deterioration. This can be dealt with by switching to TCP transport, but in this case... Second, WebRTC is broadcast from the browser, and we both know which browser is currently the most popular on the planet (spoiler — it is not IE6). In this popular browser, the maximum publication bitrate at the engine level is 2500 kbps. ~~As Google thinks~~, this is enough for FullHD but not enough for 4K. If the bitrate is not accelerated to 5 — 10 Mbps, viewers will see moving watercolor spots instead of virtual reality. Fortunately, there are special settings for overclocking the bitrate that work in ~~pretty much~~ all browsers on the Chromium engine. Then, overcoming this obstacle, we will run into... Third, we will run into channel bandwidth. To publish and play a VR picture with the bitrate mentioned above, the client will need channels of 20+ Mbit, or better 50, and even better 100+ Mbit, both for download and upload. In this case, these should not be the parameters that the provider talks about in advertising booklets, but the actual bandwidth from the client to the server. By the way, read how to [measure it without iperf and command line](https://flashphoner.com/channel-quality-indicator-for-server-webrtc-over-tcp/). Correspondingly, on the server side, it is desirable to have 10 Gb if a large number of streams is envisioned. Fourth is what follows from the requirements for channels. Transcoding a 4K stream will take up too much processor resources on the server. Therefore, you must either choose a king-size server, which is expensive, or use encoding on video cards, which is also very expensive, or avoid transcoding. That is, never change the resolution, frame rate, and bit rate of the streams during broadcasting. Let's try to do this -------------------- Let's take: * a special camera; * a special player; * a server that can [broadcast WebRTC from a browser](https://flashphoner.com/browser-online-broadcasting-from-a-web-cam/) Mount the camera on a table or tripod ![](https://habrastorage.org/r/w780q1/webt/q-/bo/tw/q-botwt5-af0pl19umr-zphiez0.jpeg) Connect it to the PC via USB 3.0 with 1A power, as for external drives ![](https://habrastorage.org/r/w780q1/webt/kh/4p/bp/kh4pbpwvvpvceliez14mgn0ocjc.jpeg) Note that the camera is very sensitive to equipment, and if the laptop has 2 USB 3.0 ports, it may well refuse to work with one of them. Make sure not to use a cheap Chinese connection cable; all pins provided for by the standard should be in place. Even with a perfect connection, the camera can produce glitch, like an old TV in a thunderstorm. The only positive thing is that no drivers are required for Windows 10; it’s an honest Plug-n-Play type connection. We will set the necessary bitrate limits on the server side ``` webrtc_cc_min_bitrate=5000000 webrtc_cc_max_bitrate=10000000 ``` In Chrome, open the [page](https://demo.flashphoner.com:8888/client2/examples/demo/streaming/media_devices_manager/media_device_manager.html) of an example, allowing to set the necessary parameters to capture the stream from the camera, and set * resolution of 3072x1536 * FPS 24 (the camera supports only this FPS when broadcasting from the browser) * TCP transport and configure the SDP settings so that the browser does not cut the bitrate on the client side ``` x-google-max-bitrate=10000;x-google-min-bitrate=5000 ``` or the server side (in this case, the settings will be valid for all publishing clients) ``` webrtc_sdp_min_bitrate_bps=5000000 webrtc_sdp_max_bitrate_bps=10000000 ``` ![](https://habrastorage.org/r/w1560/webt/ae/6z/r7/ae6zr7vxhkeeh65bp144sjklxfg.png) Let's publish the stream from the camera ![](https://habrastorage.org/r/w1560/webt/hq/-r/hu/hq-rhunttdvkc4cff_o9uurcbec.png) Now let's try to play the stream with a regular WebRTC player ![](https://habrastorage.org/r/w1560/webt/ot/mn/li/otmnli2-vsrodo4wcjplsdmuw50.png) All is fine… Almost. The virtuality is not really virtual. Now let's play the same stream in a special player embedded on the page ![](https://habrastorage.org/r/w1560/webt/ij/ki/m-/ijkim-0dccwdgyeccgirdcusgec.png) Now that's better (and we have cats too). If you play the stream on a mobile device or in VR glasses, you can turn your head, and we will move the mouse in the browser on the PC. There is a kid hiding somewhere in this room. Let's look to the left ![](https://habrastorage.org/r/w1560/webt/gc/dm/df/gcdmdflghc1jm1wxnleffttk-he.png) And now to the right ![](https://habrastorage.org/r/w1560/webt/ct/iy/gl/ctiyglkgyc2wb987mj6pzpgqdji.png) And now up ![](https://habrastorage.org/r/w1560/webt/nd/j8/3m/ndj83milhj9weql0x1ifufccuou.png) Where's the kid? There he is, hiding behind the curtain. But the cats sees him! We need more code! ------------------ There is little code on the client's side. Let's publish the stream from the browser page ``` session.createStream({ name: streamName, display: localVideo, cacheLocalResources: true, transport: "TCP", sdpHook: rewriteSdp, constraints: { audio:true, video: { width: 3072, height: 1536, frameRate: 24 } } }).publish(); ``` SDP browser override feature ``` function rewriteSdp(sdp) { var sdpStringFind = "a=fmtp:(.*) (.*)"; var sdpStringReplace = "a=fmtp:$1 $2;x-google-max-bitrate=10000;x-google-min-bitrate=5000"; var newSDP = sdp.sdpString.toString(); newSDP = newSDP.replace(new RegExp(sdpStringFind,"g"), sdpStringReplace); return newSDP; } ``` An example of a page with a VR player ``` WebRTC Delight \ Play Stop Flashphoner.init({flashMediaProviderSwfLocation: '../../../../media-provider.swf'}); var SESSION\_STATUS = Flashphoner.constants.SESSION\_STATUS; var STREAM\_STATUS = Flashphoner.constants.STREAM\_STATUS; var STREAM\_STATUS\_INFO = Flashphoner.constants.STREAM\_STATUS\_INFO; var playBtn = document.getElementById('playBtn'); var display = document.getElementById('display'); var dl8video = null; var url = setURL(); document.addEventListener('x-dl8-evt-ready', function () { dl8video = document.getElementById('remoteVideo'); $('#playBtn').prop('disabled', false).click(function() { playStream(); }); }); function playStream() { $('#playBtn').prop('disabled', true); $('#stopBtn').prop('disabled', false); var video = dl8video.contentElement; Flashphoner.createSession({urlServer: url}).on(SESSION\_STATUS.ESTABLISHED, function (session) { var session = Flashphoner.getSessions()[0]; session.createStream({ name: document.getElementById('playStream').value, display: display, remoteVideo: video, transport: "TCP" }).on(STREAM\_STATUS.PLAYING, function (stream) { dl8video.start(); $('#stopBtn').prop('disabled', false).click(function() { $('#playBtn').prop('disabled', false); $('#stopBtn').prop('disabled', true); stream.stop(); dl8video.exit(); }); }).play(); }) } ``` Usually, when creating a stream for a player (query `session.createStream()`), we pass the div element, into which the video element will be mounted to play the stream via WebRTC. But the VR player uses its own video element, and we need to somehow forward it into the code of the API used. To do this, we directly pass the video element of the third-party player to the session.createStream() with the `remoteVideo` parameter demo.flashphoner.com is used as the server side; examples of web applications are available on the links below. Good luck in your VR endeavors! Happy streaming! Links ----- 1. [Channel quality indicator for server WebRTC over TCP](https://flashphoner.com/channel-quality-indicator-for-server-webrtc-over-tcp/) — Quality control of channels from client to server 2. [Video broadcasting from the web camera of a browser or mobile device](https://flashphoner.com/browser-online-broadcasting-from-a-web-cam/) — WebRTC streaming from browser 3. [Documentation for using WCS with a VR player](https://docs.flashphoner.com/display/WCS52EN/In+a+browser+with+Delight+Player) 4. [WCS](https://flashphoner.com) — Server for transmitting VR 360 video via WebRTC
https://habr.com/ru/post/482270/
null
null
1,744
50.12
I fixed an ikvmstub regression introduced in the previous snapshot and fixed AssemblyClassLoader.getPackage[s]. I did some class file fuzzing and fixed most differences between JDK 1.5 and IKVM (most are trivial and only fixed to reduce the noise in the fuzz differences, but I also found a couple of real bugs). Other changes: Source is in cvs. Binaries: ikvmbin-0.31.2424.zip Now that 0.30 has been released, it's time to talk about the next version. While 0.30 was baking, I've made some significant changes. People sometimes ask me why the version number is so low, part of the reason is that I anticipate that I'll need to make breaking changes a couple more times. Moved Runtime API to IKVM.GNU.Classpath.dll To make the runtime API easier to use and to allow (potential) future changes that remove the need for IKVM.Runtime.dll to discover IKVM.GNU.Classpath.dll, I moved the public API of the runtime into IKVM.GNU.Classpath.dll. Now, IKVM.Runtime.dll still exposes a bunch of public types, but you should not use any of these, they are "undocumented" and only for use by ikvmc generated code and IKVM.GNU.Classpath.dll. They will also change in future versions. Revisiting the ClassLoader per Assembly Idea Over the past couple of years I've slowly come around on my initial decision to have all classes in assemblies appear to be loaded by the boot class loader. My initial reluctance was mostly due to the fact that using a ClassLoader per assembly would require violating the ClassLoader delegation model, but the success of OSGi (which does the same) demonstrates that this isn't such a big deal. Here are some of the advantages: I made a new snapshot that you can play around with to evaluate how the change will impact you. Please let me know, now's the time to convince me to change some of the details Here's a full list of changes in this snapshot: Source is in cvs. Binaries can be downloaded here: ikvmbin-0.31.2421.zip I released 0.30 (same bits as last week's rc1) to SourceForge. Here's the release candidate. Updated japi results are available here.Changes since previous snapshot: Files are available here: ikvm-0.30.0.0.zip (sources + binaries), ikvmbin-0.30.0.0.zip (binaries), ikvmbin-generics-0.30.0.0.zip (binaries built from generics branch) I'm preparing for the 0.30 release and this time I decided to do things a little more structured, so I made a branch in cvs: v0_30. I checked out the code into a clean directory changed allsources.lst and classpath.build to point to a clean check out of the GNU Classpath 0.92 release branch (Note that 0.92 has not yet been released) and ran the build script.The resulting binaries are available here. Note that even though the directory inside the zip is ikvm-0.30.0.0, this is not yet 0.30, but instead should be considered a development snapshot and the binaries are unsigned and have version 0.29.*.Please test this version and report any bugs, now's the time to get them fixed before 0.30 is released!Here's what's new: Recently I changed the way .NET generic types are handled by IKVM. The previous scheme was based on a naive mangling of the .NET Type.FullName property, but that turned out to be problematic for various reasons. The first obvious reason was that type names often were way too long for comfort. For example:Type t = typeof(System.Collections.Generic.List<string>);Console.WriteLine(t.FullName);Console.WriteLine(((java.lang.Class)t).getName());With IKVM 0.28 this prints out(I manually inserted some spaces to make the HTML wrap.)This obviously isn't very practical, but there is also a deeper problem. This literal translation of the name misses the fact that class loading in .NET is fundamentally different from class loading in Java. Which means that it is easy to go from Type to class name, but given a class name it is much harder to construct the corresponding type, especially if on or more of the type parameters are Java types (or remapped types).In the next release the class name will be:cli.System.Collections.Generic.List$$00601_$$$_Ljava__lang__String_$$$$_Not only more readable, but it also correctly reflects the fact that System.String is known as java.lang.String on the Java side.I also changed the way these names are resolved to be more inline with the way Java works. The name is now parsed by the class loader that first tries to load the class which then in turn loads the component classes and constructs the generic type from that. This means that the following code will now work (if you can somehow convince your Java compiler to compile it):import cli.System.Collections.Generic.*;class Test{ public static void main(String[] args) { List$$00601_$$$_LTest_$$$$_ list = new List$$00601_$$$_LTest_$$$$_(); list.Add(new Test()); }}With the previous scheme there was no way to refer to the Test class in the generic class name, but now the correct class loader is used so you can refer to Java classes as well. That leaves only one question, what does list.getClass().getClassLoader() return? Well, for the time being I've decided to automatically construct a class loader that delegates to the defining class loaders of the classes used to construct the generic type, this ensures (as long as no types with the same names are used) that all types used in the definition of the generic type instance can be loaded by its class loader. It isn't actually clear to me that this is required, but at least for the time being it is, because some of the reflection code relies on this fact.Finally, as a reminder, all this stuff is still experimental and, frankly, not intended to be practical. The main reason this support exists is to make the life of reflection/ikvmstub easier, otherwise the runtime would have to have all sorts of complicated support to deal with field types and method parameter/return types that take generic type instantiations. Type t = typeof(System.Collections.Generic.List<string>);Console.WriteLine(t.FullName);Console.WriteLine(((java.lang.Class)t).getName()); cli.System.Collections.Generic.List$$00601_$$$_Ljava__lang__String_$$$$_ import cli.System.Collections.Generic.*;class Test{ public static void main(String[] args) { List$$00601_$$$_LTest_$$$$_ list = new List$$00601_$$$_LTest_$$$$_(); list.Add(new Test()); }} list.getClass().getClassLoader()
http://weblog.ikvm.net/default.aspx?month=2006-08
CC-MAIN-2019-22
refinedweb
1,117
66.03
Even though PyCharm 2016.3 was only released last month, we haven’t been idle, and we have been working hard on improving PyCharm. If you want to have a sneak peek at what’s coming in the next version of PyCharm, you can download our Early Access Program (EAP) versions which we will be releasing regularly from now on until the release. In this first EAP release for PyCharm 2017.1 we’ve included these features: - Zero latency typing as a default. Pavel Fatin, a developer at JetBrains, has done extensive research into editor latency. With his improvements, typing in IDEA-based IDEs (like PyCharm) is now faster than it is in editors like Atom, Sublime Text, Emacs and Notepad++. - Semantic highlighting assigns colors to function parameters so you can see at a glance where they’re being used in the function. - Breadcrumbs let you know where you are within your project. Very useful when you’re working with deep hierarchies. - Better VCS log viewer: you can now search a commit using regex, and choose whether or not the search is case sensitive. - Web development improvements from WebStorm: Mocha test integration and ECMAscript 6 array intentions. See the WebStorm blog for more details! Several bugs have been fixed as well: - Flask extension namespaces (deprecation of flask.ext.*) [pro only] - Passing arguments from Tox run configuration [pro only] - Django test runner hanging on error creating a database [pro only] - BDD: Running scenario outlines separately [pro only] - A number of fixes for code insight and type checking - Hangs on live templates invocation - A few fixes for code refactorings - Show command line after running a script We’d like to invite you to try this EAP build and to let us know how you like it. If you encounter any issues with the EAP you can report an issue on our issue tracker. You can also reach out to us by commenting on this blog post, or by tweeting us. If you’d like to let us know about a feature you’d like us to develop, please let us know as well! Finally, we’d like to wish you a happy 2017, we hope your code in the next year will be better than ever before! -PyCharm Team The Drive to Develop build.txt inside pycharm-professional-171.2014.23.tar.gz says “PY-163.10154.45” and the IDE claims to be 2016.3.2. Are you sure the correct build has been packaged? It looks like the .tar.gz archive for PyCharm Professional 2017.1 EAP available at the EAP page contains the correct version 171.2014.23. Could you please double-check that you’ve downloaded the correct file? My mistake. Pingback: PyCharm 2017.1 EAP 发布,Python IDE - simple Great job! Great job! This is fantastic news on the latency! Sadly it won’t affect me much since I’m a slow typist. The delay that concerns me is usually load times. A lot of that (for a developer) is fixed just my getting an SSD and can’t be helped via software, I suppose. It is awesome that assigning a color to each function parameter. But why not hightlight “function call” and “variable” like other IDEA-based IDEs? I think it is necessary. I just checked with the development team: We don’t highlight function calls, and neither does IntelliJ IDEA, we do highlight local variables. However, we don’t highlight class variables, as you could reference it with a qualifier, and we want to be consistent with other qualified references. Could you please include latest version on? From 2017.1 onwards we will publish all EAP versions on our website: I’ve just downloaded it, hoping that it’s gonna improve my experience with the sluggish editor. Unfortunately, I’m seeing no improvement at all. I’m sorry to hear that. Could you maybe send us a performance report? Submitted Thank you for your report, we’re looking in to it! Great stuff; you guys are totally killing it with this EAP cycle! Again! If I could make a very low-priority suggestion: It would be nice if toggling the Breadcrumbs bar on and off could be a command that one could bind to a key (or even just access from the Find Action popup). It takes up a valuable line of screen real estate, and it would be nice to be able to turn it on or off without a trip to Preferences. Nice improvements! I will take a look and give my opinion later. Overall, really like the enhancements. However, in Pycharm 2016, when you right-clicked on the tab with the filename for an opened file, you were able to click on run/debug the program (with a shortcut reminder for Ctrl-Shift-F10 for run). In Pycharm 2017, the run/debug menu item is no longer present when I open .py files. It is present for .html files. Is this intentional (or am I doing something wrong or have an incorrect settting)? Again, though, really like Pycharm 2017. I just checked, I have the ‘Run’ option in the context menu after right-clicking on a tab. What type of project are you using? Which Python interpreter have you configured? Figured out what the error was. It was previously identified as an issue in a previous build of Pycharm (2010). In the file, I had a function named create_test_data(). The presence of the word ‘test’ in the method name caused the issue. Pycharm interpreted the file as a test case file or unit test file instead of an executable. The context menu is different for the two types of files.
https://blog.jetbrains.com/pycharm/2016/12/pycharm-2017-1-early-access-program-started/?replytocom=301907
CC-MAIN-2020-24
refinedweb
948
74.19
Python's filesystem abstraction layer Project description PyFilesystem2 Python's Filesystem abstraction layer. Documentation Introduction Think of PyFilesystem's FS objects as the next logical step to Python's file objects. In the same way that file objects abstract a single file, FS objects abstract an entire filesystem. Let's look at a simple piece of code as an example. The following function uses the PyFilesystem API to count the number of non-blank lines of Python code in a directory. It works recursively, so it will find .py files in all sub-directories. def count_python_loc(fs): """Count non-blank lines of Python code.""" count = 0 for path in fs.walk.files(filter=['*.py']): with fs.open(path) as python_file: count += sum(1 for line in python_file if line.strip()) return count We can call count_python_loc as follows: from fs import open_fs projects_fs = open_fs('~/projects') print(count_python_loc(projects_fs)) The line project_fs = open_fs('~/projects') opens an FS object that maps to the projects directory in your home folder. That object is used by count_python_loc when counting lines of code. To count the lines of Python code in a zip file, we can make the following change: projects_fs = open_fs('zip://projects.zip') Or to count the Python lines on an FTP server: projects_fs = open_fs('') No changes to count_python_loc are necessary, because PyFileystem provides a simple consistent interface to anything that resembles a collection of files and directories. Essentially, it allows you to write code that is independent of where and how the files are physically stored. Contrast that with a version that purely uses the standard library: def count_py_loc(path): count = 0 for root, dirs, files in os.walk(path): for name in files: if name.endswith('.py'): with open(os.path.join(root, name), 'rt') as python_file: count += sum(1 for line in python_file if line.strip()). PyFilesystem2 owes a massive debt of gratitude to the following developers who contributed code and ideas to the original version. - Ryan Kelly - Andrew Scheller - Ben Timby Apologies if I missed anyone, feel free to prompt me if your name is missing here. Support If commercial support is required, please contact Will McGugan. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/fs/2.2.1/
CC-MAIN-2021-21
refinedweb
387
65.73
User:Imagic/LaneMapping *************** This page is in some aspects outdated! *************** On this page I will try to show some examples of lane mapping. All tags written in italic are under discussion! Contents Motorway with links and destinations Tags 1 lanes=3 destination:lanes=A|A|B 2 lanes=3 turn:lanes=none|none|through;slight_right 3 lanes=4 turn:lanes=none|through|through|slight_right change:lanes=yes|not_right|yes|yes 4 lanes=3 5 lanes=4 turn:lanes=none|none|none|merge_to_left 6 lanes=3 Motorway that splits up Tags on the ways 1 lanes=3 destination:lanes=A|A;B|B 2 lanes=3 turn:lanes=slight_left|slight_left;slight_right|slight_right 3 lanes=3 turn:lanes=slight_left|slight_left;slight_right|slight_right destination:lanes=A|A;B|B 4 lanes=4 turn:lanes=slight_left|slight_left|slight_right|slight_right destination:lanes=A|A|B|B 5 lanes=4 change:lanes=yes|not_right|not_left|yes 6_up lanes=2 6_down lanes=2 turn:lanes=none|merge_to_left 7_up lanes=3 7_down lanes=1 Relations for connectivity: 3 to 4 members=from(way3) , via(node way3-way4) , to(way4) type=connectivity from:lanes=1|2|3 to:lanes=1|2;3|4 5 to 6_up members=from(way5), via (node way5-way6_up), to(way6_up) type=connectivity from:lanes=3|4 to:lanes=1|2 <---- Is this "obvious"? 5 to 6_down members=from(way5), via (node way5-way6_down), to(way6_down) type=connectivity from:lanes=1|2 to:lanes=1|2 <---- Is this "obvious"? 6_up to 7_up members=from(way6_up), via(node way6_up-way7_up), to(way7_up) type:connectivity from:lanes=1|2 to:lanes=1;2|3 <---- Anything suspicious? Road with lanes for motorized traffic, trams and bicycles 1 highway=secondary cycleway=lane 1) railway:lanes:forward=tram|no 2) turn:lanes:backward=left|through railway:lanes:backward=tram|no 3) 2 highway=secondary cycleway=lane railway:lanes:forward=tram|no turn:lanes:backward=none|left;through railway:lanes:backward=tram|no access:lanes:backward=no|yes 4) train:lanes:backward=yes|no 5) 3 highway=secondary cycleway=lane railway:lanes:forward=tram|no railway:lanes:backward=tram|no access:lanes:backward=no|yes train:lanes:backward=yes|no 4 highway=secondary cycleway=lane turn:lanes:forward=slight_left|through;right railway:lanes=no|tram|no|no 6) access:lanes=yes|no|yes|yes train:lanes=no|yes|no|no 1) Any lanes specified with keys without :lanes are added at their "natural" position. In this example, the cycleway lanes are added at the right and left side of the other lanes. 2) As we specified tram:lanes:forward, this track is a oneway track in the same direction as the osm-way. 3) As we specified tram:lanes:backward, this track is a oneway track in the opposite direction as the osm-way. 4) First we forbid any access on the tram track, and 5) Second we allow explicitly access for trains 6) Neither :forward nor :backward: this tram-track is not a oneway track. Question: how could/should we tag, that the tram track merges in section 3? Mapping the destination signs On the way starting right at the position of the sign: turn:lanes=left|left;through|through destination:lanes=Brno;Poysdorf;Mistelbach|Brno;Poysdorf;Mistelbach;Graz;Wien|Graz;Wien destination:ref:lanes=A5|A5;S1;A2|S1;A2 1) destination:country:lanes=CZ|CZ;SK;HU;SI;IT|SK;HU;SI;IT 2) destination:sign:lanes=none|airport|airport 3) Please discuss on the following: 1) The key destination_ref is already used but not documented. Nevertheless I suggest to use destination:ref for a consistent namespace - I doubt destination_ref is already processed anywhere. 2) destination:country would accept standardized country codes 3) destination:sign would accept predefined values, like airport, centre, trainstation, and so on. Examples with aerial images Example 1: Deceleration lane Exit 115 on the motorway A9 in Styria, Austria. Background image (C) geoimage.at . - A: Ordinary motorway with two lanes. highway=motorway oneway=yes ref=A9 lanes=2 - B: The nodes are placed in the middle of the two lanes. The OSM-way is split at this node. - C: Road markings of turning lanes are present. highway=motorway oneway=yes ref=A9 lanes=2 turn:lanes=none|through;slight_right - D: The deceleration lane starts. The node is placed in the middle of the two lanes and the OSM-way is not yet split. - E: The deceleration lane has reached its full width, therefore the OSM-way is split at this node. The node is placed in the middle of all three lanes. - F: Three lanes are visible, two with road markings. highway=motorway oneway=yes ref=A9 lanes=3 turn:lanes=none|through|slight_right - G: The name and reference number of the exit is given on a signpost. At the beginning of the separation of the deceleration lane, the OSM-way of the motorway is split and the new OSM-way of the slip road starts. The node itself is placed in the middle of all three lanes. The node is tagged as motorway junction. highway=motorway_junction name=Mautern ref=115 - H: The OSM way of the motorway continues. highway=motorway oneway=yes ref=A9 lanes=2 - I: The OSM way of the slip road. Signposts indicate that the road ahead is referred to as B113 and is leading to Mautern. highway=motorway_link oneway=yes lanes=1 destination=Mautern destination:ref=B113 - J: The first node of the motorway as well as of the slip road after the junction are placed at approximately the same distance to the junction. The nodes should not be placed to near to the junction to prevent steep angles (see the note below). The node of the motorway is placed in the middle of both lanes, the node of the slip road is placed in the middle of the lane. Note about the placement of nodes G and J: This placement of the nodes 1) guarantees an acceptable rendering result, and 2) prevents misleading routing instructions. Some people might prefer to place node G at the beginning of the physical separation instead of the legal one (as in the example). Also if the legal separations starts very long before the physical one it is recommended to split not at the beginning of the legal separation but slightly before (or at) the physical one. Please consider to use change:lanes=yes|not_right|not_left to indicate the legal separation (i.e. the solid line) before the physical separation. Example 2: Lane changing forbidden Near the motorway interchange of A1 and A9 in Austria, slightly to the north of exit 196 of the A1. Background image (C) geoimage.at . - A: Slightly before the interchange three lanes are present on a parallel motorway, all of them with road markings. See the article about motorway_link for information about parallel motorways. highway=motorway_link oneway=yes ref=A1 lanes=3 turn:lanes=through|slight_right|slight_right - B: The nodes are placed in the middle of the three lanes. The OSM-way is split at this node, because from this point on it is not allowed to enter or leave the leftmost lane. - C: Now it is not allowed to enter or leave the leftmost lane. highway=motorway_link oneway=yes ref=A1 lanes=3 turn:lanes=through|slight_right|slight_right change:lanes=no|not_left|yes - D: At the beginning of the separation of the motorway link leading to A9, the OSM-way of the parallel motorway is split and the new OSM-way of the link starts. The node itself is placed in the middle of all three lanes. - E: The OSM way of the link. Road markings are visible. highway=motorway_link oneway=yes lanes=2 destination:ref=A9 turn:lanes=slight_right|slight_right - F: The OSM way of the parallel motorway continues. highway=motorway_link oneway=yes ref=A1 lanes=1 - G: The first node of the parallel motorway as well as of the link after the split are placed at approximately the same distance to the split. The nodes should not be placed to near to the split to prevent steep angles. The node of the parallel motorway is placed in the middle of the lane, the node of the link is placed in the middle of both lanes. Please see also the note in the first example. Note about signposts: Between C and D a signpost is clearly visible on the aerial image. If the information from this signpost is also available it should be tagged using destination:lanes=*, destination:ref:lanes=*, destination:sign:lanes=* and destination:country:lanes=*. Example 3: Acceleration lane An acceleration lane on the S6 near Rastplatz Schottwien, Austria. Background image (C) geoimage.at . - A: The last node of the motorway as well as of the slip road just before they merge are placed at approximately the same distance to the merge. The nodes should not be placed to near to the merge to prevent steep angles (see the note in the first example). The node of the motorway is placed in the middle of both lanes, the node of the slip road is placed in the middle of the lane. - B: The slip road. highway=motorway_link oneway=yes lanes=1 - C: Ordinary motorway with two lanes. highway=motorway oneway=yes ref=S6 lanes=2 - D: The slip road merges with the motorway and the acceleration lane starts. The node is placed in the middle of all three lanes. The OSM way of the motorway is split. - E: The road markings indicate that the acceleration lane will be merged with the middle lane. highway=motorway oneway=yes ref=S6 lanes=3 turn:lanes=none|none|merge_to_left - F: The acceleration lane starts to disappear, i.e. its doesn't have its full width any more and narrows further. The OSM way is split and the node is placed in the middle of all three lanes. - G: The acceleration lane is not considered when taggging, because it doesn't have full width any more. highway=motorway oneway=yes ref=S6 lanes=2 - H: The first node of the motorway after the acceleration lane is not tagged any more should be placed in the middle of both lanes and where the acceleration lane has completely disappeared.
http://wiki.openstreetmap.org/wiki/User:Imagic/LaneMapping
CC-MAIN-2017-13
refinedweb
1,699
53.51
TM THE PATHFINDER REPORT February 2019 IN THIS ISSUE 2 CHARTING THE COURSE Winter is Coming 5 FINDING YOUR PATH Warning Signs Ahead 8 GUEST FEATURE Thinking Outside the Box? 10 ZEITGEIST: NEWS HIGHLIGHTS 11 TRAILBLAZING Driftwood Apartments, Pacific Beach (San Diego), CA 13 NOTABLES AND QUOTABLES Preparation T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 1 CHARTING THE COURSE Winter is Coming By Mitch Siegler, Senior Managing Director Fans of the critically-acclaimed HBO series Game of Thrones know “Winter is Coming” as the motto of House Stark, one of the Great Houses of the continent of Westeros. These words evoke warning and constant vigilance as the Starks, lords of the North, strive to always be prepared for the coming of winter, which impacts them greatly. “Winter is Coming” is also an apt metaphor for investor caution and preparation. Today, we’re about a decade into a bull market for many asset classes, including stocks and real estate. While we’re not now ringing the bell and calling the market at a top, the easy money in stocks and real estate appears to be behind us. We believe 2019 will be a turning-point year and “caution”, “hedging” and “harvesting” are our operative words. Since trees don’t grow to the sky, Pathfinder began preparing for the coming winter three years ago and we remain vigilant with respect to protecting our investment portfolio (more on the steps we’ve taken and are continuing to take below). Our awareness of the possibility of challenging times ahead for investors has become heightened by several factors, including increased market volatility, asset prices at or near record levels, the 2020 presidential elections, increasing antiCapitalist sentiment and a likely housing slowdown, which we will discuss further below. Market Volatility The major stock market indices had their worst quarterly performance in a decade during the fourth quarter of 2018 sending them into bear market territory, down more than 20% from the highs. The Dow Jones Industrial Average (DJIA), S&P 500 and NASDAQ indices were down 11%, 13% and 15%, respectively, during the quarter. The S&P 500 was especially volatile, with intraday swings of more than 1% on four out of five trading days with intraday swings of 3% or more occurring ten times. Bond yields also swung wildly, with the benchmark 10-year Treasury note reaching 3.25% (it’s back to 2.65% at press-time). We expect continued volatility in the months ahead. Asset Values At/Near Peak Levels The heightened market volatility occurs against a backdrop of stock, bond and real estate prices that are at or near record levels. It’s been a decade since the collapse of Lehman Brothers and Bear Stearns, which precipitated the 2008 Great Recession. Stock market indices hit lows in March 2009 – the DJIA has quadrupled since then. Real estate values have similarly skyrocketed as interest rates and cap rates have fallen and remained low. In 2009, investors in stocks and real estate had considerable “margins of safety”. While it’s still possible today to buy assets with some margin of safety, you really must search far and wide to find these opportunities. Viewed through that prism, the investing environment is riskier now and expected investment returns during the next ten years are likely to be well below returns during the past decade. 2020 Election and Increasing Anti-Capitalist Sentiment Uncertainty brings volatility and presidential elections can create both. Given the political divisions and large field of potential Democratic challengers, we expect the 2020 presidential election to be the mother of all uncertain events. The signs are already apparent: the biggest political story of 2019 is that Democrats are beating the drum for policies that include government control of huge chunks of the American economy. Bernie Sanders kicked off this theme in the 2016 primaries with calls for economic justice, restrictions on corporate money in politics and promises of health care and education for all. Recent proposals from the progressive/far left wing of the Democratic party, a few of which are summarized below, will exert strong influence on the upcoming presidential primaries: T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 2 1. Bernie Sanders’ Medicare for All plan, endorsed by 16 other Senators, would replace all private health insurance with a federally-administered, single-payer system. Government bureaucrats would decide what health care and drugs you should receive and how much to pay doctors and hospitals. Remember “You can keep your health plan”? 2. The Green New Deal, endorsed by 40 House Democrats and several presidential candidates, would mandate that the U.S. be “carbon-neutral” in just ten years. Since non-carbon sources account for only 11% of U.S. energy today, this would require a complete reinvention of our electric power and transportation systems with profound implications for industry, workers and homeowners. And if 29-year-old Congresswoman and avowed Democratic Socialist Alexandria Ocasio-Cortez (AOC for short) has her way, it would all be overseen by a Select Committee for a Green New Deal – five-year planners in the Politburo would be proud. 3. Many of the same folks advocating for The Green New Deal are also behind a guaranteed government job for all to counter the effects of technological change and globalization. And who said there’s no free lunch? Why strive to do well in school or work hard to compete for jobs if they’re guaranteed? 4. Senator and Presidential candidate Elizabeth Warren proposed a new federal charter for businesses generating over $1 billion in annual revenue that would make these companies answer to more than shareholders. Her proposed system for corporate control would require that employees elect 40% of corporate directors who would be forced to consider “benefits” beyond shareholder returns. Lenin and Mao would be pleased. 5. These ideas would require vastly more federal revenue and proposals abound for how to generate it through much higher taxes. Mr. Sanders calls for a top death tax rate of 77%. AOC, who proudly accepts the label “radical”, wants a 70% tax rate on high incomes. Ms. Warren wants a new 2% “wealth tax” on assets over $50 million and 3% over $1 billion. (France recently scrapped its wealth tax because it was so counterproductive, stifling growth and causing entrepreneurs and wealthy taxpayers to flee.) The Democratic House Ways and Means Committee is developing a plan to increase the payroll tax from 12.4% to 14.8% on incomes above $400,000. Irrespective of whether these knee-jerk proposals ever become law, they certainly change the political conversation and are likely to bring about changes in behavior. Notably, those affected, who own a disproportionate share of the nation’s wealth (the wealthiest 1% own 50% of stocks, per Goldman Sachs), might be inclined to sell shares to pay the higher taxes. At the very least, that means greater volatility and slowing economic growth are likely. Declines in the prices of stocks and other assets, including real estate might not be far behind. As former British Prime Minister Margaret Thatcher said, “The problem with socialism is that you eventually run out of other people’s money.” Housing Slowdown and Impact on the Economy In addition to signs of slowing economic growth and heightened volatility, we expect home sales to slow, as often occurs during presidential election years. A 2008 survey found that “the election was really weighing on the minds of the would-be home buyers,” according to a report issued by Realtytoday. com. Potential homebuyers are concerned about these risks and many may defer purchases until the political environment is less uncertain. Election years can be stressful and uneasy for many Americans says movoto.com, an online real estate brokerage firm. People are less likely to make large purchases, particularly homes, in very uncertain times. The results of a presidential election can affect your finances, so fewer people are willing to invest in a home when their financial future might be uncertain or influenced by the incoming president – who (or whose party) may have different housing or mortgage policies that affect potential homebuyers in various ways. The mind boggles about the policy changes that may follow from the progressive, anti-Capitalist banter. And by the way: housing accounts for 15-18% of the U.S. economy, according to the National Association of Home Builders. T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 3 How Pathfinder is Preparing for “Winter” As we’ve said in the past, investing in apartments provides steady income and growth, in good times and bad. Simply put, people need a place to rest their weary heads and an estimated 37% of Americans rent today – a number that has grown significantly during the past decade and is higher than at any time since 1965. Value-add apartments provide a strong margin of safety since the purchase price is based on the previous management (often unsophisticated) and property condition (generally never improved or not improved in decades). By renovating the property, we can dramatically boost rents and income. If you keep the leverage low (as we do), risks are substantially mitigated. If you focus on high-growth markets with strong population and job growth (as we do), you set yourself up for appreciation and success down the road. Since 2016, all our acquisitions have been these types of properties. We’re being defensive, keeping our heads down below the parapets. Meanwhile, we’ve been pruning our portfolio of assets outside of the value-add apartment ‘sweet spot’. We’ve sold or are selling office buildings, retail and commercial centers and vacant land acquired years ago and are wrapping up our active residential development projects. Tightening our supply lines, chopping extra wood for the castle’s wood-burning stoves and hunkering down for winter. PAT HF I NDE R R E PO R T: FE B R UARY 2019 4 FINDING YOUR PATH Warning Signs Ahead By Lorne Polger, Senior Managing Director In September 2006, I gave a speech to the San Diego County Apartment Association. I had been a real estate lawyer for around 20 years, and my practice was focused on representing apartment investors and condominium converters. I warned that our real estate economy was not sustainable, that pricing had become out of whack, and that a period of economic decline was forthcoming. In hindsight, my prediction was both early and understated. At the time, it was not well received. I received calls and emails from several real estate industry insiders following my speech, chastising me for my negativity. Two years later, the Great Recession formally commenced. From October 2007 through March 2009, the Dow Jones Industrial Average fell 54% . Real estate values followed a similar pattern. How did I know what was going to happen before it happened? Four ways. First, excessive leverage in real estate investments. Over the years, people continue to gasp when I tell them that I worked on a $72,000,000 deal that was structured with $71,750,000 of debt, and $250,000 of equity. It was one of many that I worked on structured with similar leverage. How could that have been possible? In fact, this type of deal structure was prevalent back then. The banks were largely unregulated when it came to leverage in their loan portfolios, and it showed. And the big banks were not immune from this. In fact, some of the big banks created subsidiary organizations which lent in the riskier part of the capital stack, at higher rates, even within the same loan structure. By way of example, Bank of America may have made a $50 million loan on an $80 million asset. Not crazy leverage, right? But B of A’s wholly-owned subsidiary, TriSail Capital Corporation, then may have loaned another $20 million (as either a second mortgage or mezzanine debt). And then, of the remaining $10 million in the capital stack, $8-9 million may have been structured as preferred equity ahead of the sponsor’s equity. When the market dropped 35% in value, the sponsor, the preferred equity provider and TriSail were completely wiped out. Bottom line? Massive leverage + undercapitalized sponsor + overheated economy = Bad deal for all. Crisis for many. Second, sloppy underwriting. From 2004-2006, I was privy to rosy predictions of continued meteoric price appreciation, sloppy and incomplete appraisals littered with bad comparable properties. Investors, underwriters and appraisers all appeared to be looking solely in the rear-view mirror instead of through the windshield to see what was ahead. Financial institution budgets weighted to fee income and producer bonus targets – greed – had something to do with it as well. Third, the quality (or lack thereof ) of many borrowers and sponsors. Money was flowing during those years to undercapitalized and inexperienced borrowers, many of whom took an undisciplined, cowboy approach to investing. Bad track records were overlooked as easily as a bad latte at Starbucks®. The impetus was more about getting money out the door than validating the quality of the investment or the principals. Again, greed. Fourth, the cycle of real estate. Trees never grow to the sky. The music does stop occasionally; even Elton John does not play an endless live concert (except perhaps on his Pandora® channel). Values go up for a while, and then they go down for a while. It’s the natural order of things. What are Some of the Current Warning Signs? As profit margins become more compressed as the cycle evolves, real estate investors begin to use financial engineering to make deals pencil. Let’s walk through an example. Let’s say you were developing an apartment building earlier in the cycle. Big Money Center Bank gave you a loan for 70% of the construction cost, and you funded the rest with equity. Pretty good cushion for the bank. Your return on costs was about 7% and T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 5 the deal underwrote to a 20% annualized internal rate of return (IRR). Flash forward to today. The FDIC has started to get concerned about real estate lending practices, so they tightened the screws on the banks and told them to reduce the leverage on those loans. So now, 70%, became 60%. The equity check got bigger, just as the returns shrank. A deal that underwrote to a 7% return on costs is now closer to 6%. 20% IRR’s shrank to 16%. So, what happened? Financial engineering. You add more debt or preferred equity to the capital stack at rates that are theoretically lower than the overall project returns to increase the return on equity. Makes sense, right? It does, until the deal has a cost overrun, or a project delay, or, heaven forbid, the economy slows. In each case, the equity return then gets marginalized; or in some cases, eliminated entirely. As the cycle has evolved, we’ve been seeing more financial engineering in deals that have been presented to us as investors. And the numbers don’t lie. According to the Mortgage Bankers Association, unregulated higherleverage, higher-priced private debt funds placed $67 billion in mortgage loans in the U.S. in 2018, up from $52 billion in 2017 and $32 billion in 2016. Contrast this with the $70 billion loaned by Fannie Mae and Freddie Mac on apartment loans for 2018 (the agencies are capped at the same number for 2019). The numbers on a deal may not work with bank leverage at 60%, but they suddenly make sense with private, highpriced money at 80% leverage. Why? Because only half of the equity is required. But the risk rises exponentially as well. In addition, we’ve seen massive shifts in how certain segments of commercial real estate are used, perhaps increasing their vulnerability at the tail end of a cycle. Most notably, of course, are retail and office, laggards in performance for more than a decade. Bottom line, we don’t shop like we used to, and we don’t work like we used to. Those trends do not appear to be ebbing; in fact, they appear to be accelerating. An economic downturn could further magnify the challenges that those two sectors continue to face. Another warning sign has been the massive increase in construction costs. Over the last three years alone, costs have risen more than 30% in many markets, dramatically above inflation. That makes tight deals even tighter (and riskier). Pathfinder has exited the development game in part for that reason. Are Certain Geographic Markets More Vulnerable? We all know that Vegas, Phoenix and Florida were among the worst-performing markets in the Great Recession, as oversupplied and speculative residential housing fueled the problem fires. Are there similar red flags in certain geographies this time around? We don’t see it yet. We have concerns about demographic trends in high tax states. We have similar concerns about business exits from highly regulated states. But short of a potential oversupply of new Class-A apartment buildings in downtown Denver and Houston, and highrise condominiums in downtown Miami, we’re hard pressed to forecast distress in particular markets due to oversupply. Is Another Great Recession Coming This Time? In a word, no, or at least not one that can be currently predicted absent a geopolitical-type “black swan” event. And there are many reasons why. Among them, first, as a direct result of lessons learned from the Great Recession, restrictions were placed on financial institutions. Risky lending practices were curtailed, and the Feds continue to watch with eagle eyes across all regulated lending platforms. I’m currently the chair of the loan committee of a community bank and can attest to how the FDIC is guiding banks with respect to curbs on current commercial real estate loan practices. Second, this time around we did not overbuild in various sectors of commercial real estate and residential housing. In fact, we have generally undersupplied housing this time around, especially in difficult markets for development like coastal California. Arguably, among the four primary classes of investment real estate (office, retail, industrial and multifamily), while office and retail continue to perform at the bottom of the stack, this time around performance is not due to speculative development. T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 6 Third, macroeconomic factors suggest that if there is a dip, it likely won’t be a big one. Unemployment remains at all-time lows. The economy is humming along across most sectors. Interest rates remain low. Political uncertainty may continue to prevail for the foreseeable future, but that uncertainty does not seem to have had a negative impact on the economy (yet). context of inexperienced and undercapitalized sponsors getting overleveraged, and over their skis, particularly in the context of development deals. We expect more of that ahead. On the positive side, these types of situations will present meaningful buy opportunities for well capitalized and experienced groups like Pathfinder. Either way, it will remain an interesting ride ahead. What Lies Ahead?. We’ve said it many times over the past few years. We continue to believe that the safe play in the current environment is in the workforce housing sector. We don’t see that going away any time soon as that element of housing has barely added any new supply over the past decade. Outside of workforce housing, we see both equal measures of concern and green shoots of opportunity. The early warning signs are starting to appear in the T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 7 GUEST FEATURE Thinking Outside the Box? By Brent Rivard, Managing Director The 800-pound gorilla is sitting next to me. It’s time to sit down and finally write my article for the Pathfinder newsletter. I’m going to give 110% on this one and bring my ‘A’ game. Take it to the next level. Forget about a 20,000´ view, I’m going to dig in and get granular. I want to write something about being results-oriented and holding people accountable. I didn’t think I had the bandwidth to get it done – but today, more than ever…I don’t have a choice! It is what it is. Business clichés – we all use them even if we’re trying hard not to. My partner, Mitch Siegler’s article reminded me that we can add one more to the list of top clichés – Winter is Coming. Or for that matter, [insert anything here] is Coming these days. Clichés are defined as “a phrase or opinion that is overused and betrays a lack of original thought.” They may get overused, but I wanted to pick a few to describe further how Pathfinder is (and we all should consider) “preparing for winter.” Blocking and Tackling It’s defined as “The basic, fundamental skills, tasks, or roles necessary to the function of something.” This one gets overused but for good reason. Over the last ten years as the market has recovered and reached near record levels, some businesses still prospered without taking care of the fundamentals. As the market slows and uncertainty increases, we need to block and tackle even better to find and create value for our customers or investors. For Pathfinder, this means strong and regular financial analysis and reporting. We receive daily leasing reports (yes, every single night) from our property managers. These may become spam emails that get deleted for a lot of firms, but we need to pay attention to the daily details as value is starting to be achieved at the margin. The ability to get real time information and develop strategies based on that information might be the difference in capitalizing on opportunities and harvesting that value or not. We’re constantly analyzing our performance at a “granular” level for each property and investment and comparing performance to our forecasts and budgets. By identifying when we’re off track sooner, we can fix the issues and “right the ship.” As they say, “what gets measured, gets managed.” Best Practices No definition needed for this one. Our investment strategy was born out of the over-leverage and mismanagement that created the 2008 Great Recession. We developed early what we felt were solid best practices for creating value for our investors while reducing risk. At the core of those best practices are fixing the uncontrollable facets of our business and staying focused on the items we can control. We have always and continue to be a firm that employs low leverage (less debt) on our properties and matching the debt to our business plans. By keeping the leverage low and fixing our interest rates, we have cushion for the factors we can’t control like state of the market and interest rates. Over the last few years, we have started to see some firms employ higher leverage using private lenders and mezzanine debt to boost returns to investors. Feels like a winter forecast to me – glad we’re bundled up and prepared. On the “flipside,” we can control how and when we invest in a property. Our value-add strategy for apartments includes renovations to common areas, upgrading units and often turning over property management to local market specialists. We can measure and control the velocity and level of renovations to adjust to changing market conditions and test certain levels of renovations unit by unit to determine what level – bronze, silver or gold – provides the most value to our tenants and ultimately to our investors. Depending on what works best at each property, we can use that information to apply those “best practices” to other properties. T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 8 The Hedgehog Concept In his book, Good to Great, Jim Collins describes the hedgehog concept as the intersection of “1) what you are deeply passionate about, 2) what you can be the best in the world at, and 3) what best drives your economic or resource engine.” It’s an amazing concept that, unfortunately, has become somewhat of a business cliché, but that’s not going to stop me from using it to prepare for Winter. At Pathfinder, we are deeply passionate about residential real estate. Early on, we invested in a few non-residential assets, but we quickly learned that we like residential best. That’s one of the reasons we’ve been actively selling our office buildings, retail centers and other nonresidential assets – so we can focus on not only what we’re passionate about, but what we believe we can be the best at. Value-add multifamily investments also happen to be what drives our economic engine. We believe value-add apartments provide the best risk-adjusted returns to our investors in any market. The reasons Jim Collins called it The Hedgehog Concept is that the hedgehog is focused and disciplined. Not only are we focused on value-add multifamily, but we remain focused and disciplined in investing only in highgrowth markets. There are opportunities all over the U.S. for multifamily investing in markets that do not have the population and job growth characteristics of the markets we invest in. Those markets don’t provide the margin of safety – or the potential upside – that we believe is important. At the end of the day (cliché intended), we’ll continue to stay focused, get granular on our business and sleep well at night as we prepare for…Winter. Brent Rivard is Managing Director, CFO and COO of Pathfinder Partners, LLC. Prior to joining Pathfinder in 2008, Brent was the President of a national wealth management firm and CFO/COO of one of southern California’s leading privately-held commercial real estate brokerage firms. He can be reached at brivard@pathfinderfunds.com. T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 9 ZEITGEIST – SIGN OF THE TIMES 2019 Multifamily Health Check-up Despite the heightened volatility in debt and equity markets, Freddie Mac’s 2019 Multifamily Outlook is reporting that the driving multifamily market economic indicators remain strong and there is little that is likely to significantly impact this market in 2019. The study reports an unemployment rate of 3.9% at the end of 2018 and estimated job growth of 2.6 million in 2019. Supported by the low unemployment rate, the U.S. Census Bureau reported 2.3 million new households were formed in 2018. This robust household formation growth has helped most apartment markets absorb the influx of new supply, keep occupancy rates stable and see continued – albeit moderate – rent growth. In addition, the U.S. homeownership rate continues to hover at historically low levels and evolving demographic and lifestyle preferences are increasing the demand for multifamily properties. Freddie Mac predicts that new apartment supply in 2019 will only marginally outpace absorption and gross income should grow 3.7%, above long-term averages and supporting the continued resilience of the multifamily market. Making the Move As the San Francisco Bay Area’s economy continues to expand, many residents are moving to more affordable locations to live and work. The median home price is now the highest in the nation at $775,000 (and avocado toast can cost north of $15!). A recent study by Redfin reported that nearly 25% of online home searches by Bay Area residents are focused on out-of-the-area options, up from 19% the prior year. Top searches include Sacramento, Portland, Seattle and Austin – all cities with a robust economy and more affordable suburban home buying and rental options. The trend of migration out of expensive (and often very big) cities is being felt across the U.S. and is especially evident among millennials. A Brookings Institute study tracking millennial migration from 2004 to 2017 showed New York, Los Angeles, Chicago, Boston, Philadelphia, Miami and Washington D.C. as some of the biggest losers and Portland, Phoenix, Las Vegas, Sacramento, Dallas, Austin and Nashville as some of the biggest gainers, reflecting a trend towards smaller, more affordable cities. Phoenix-based moving company U-Haul also tracks migration data measured by how many one-way, do-it-yourself movers are arriving in various cities and states compared with how many are leaving. According to their data for 2018, Utah ranked #1 in net gains followed by Texas, Florida and South Carolina. Inventory of For-Sale Housing Hits Ten Year High A volatile stock market, temporary government shutdown and interest rate increases kept many would-be buyers on the sidelines over the past 90 days. The pace of U.S. homes sales declined for the sixth straight month in January, helping create the largest for-sale inventory increase in the last decade. On average, homes sold in January spent 59 days on the market and inventory levels are at a 3.9-month supply, a 15% increase from January 2018 levels. Nationwide, California experienced one of the more drastic slowdowns in home sales with approximately 30,700 sales in December 2018, the lowest level for a December in 11 years and a 20% decrease from December 2017. In Southern California, home sales historically rise between November and December but the region saw more than an 8% decline over the period. The U.S. new construction market – typically a leading indicator of overall home sales – saw meaningful price cuts in the fourth quarter of 2018 with more than 25% of new home inventory experiencing some level of price reduction. T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 10 TRAILBLAZING: DRIFTWOOD APARTMENTS, PACIFIC BEACH (SAN DIEGO, CA) A True Coastal Treasure Driftwood – Unrenovated Kitchen Driftwood – Renovated Kitchen Beachcombing involves “combing” the shoreline looking for things of value or interest. In 2015, while combing investment opportunities along San Diego’s Pacific Coast, we discovered Driftwood – a 24-unit apartment community in the quaint Crown Point neighborhood of Pacific Beach in San Diego. Driftwood, built in 1992, is situated on a one-acre parcel and includes four two-story garden-style apartment buildings comprised of two-bedroom/two-bathroom apartments averaging about 1,000 square feet. The property’s low density and large setback from the street provides an open and spacious feel, a point of differentiation with the denser apartment communities nearby. Crown Point – just west of Interstate-5 and centrally located between the major employment centers of Downtown San Diego and University Town Center – is in one of San Diego’s most desired coastal neighborhoods. The property’s proximity to Mission Bay Park (two blocks) and the Pacific Ocean (under one mile) provides an abundance of recreational activities for outdoor enthusiasts (swimming, sailing, fishing, paddle-boarding, surfing, biking and jogging). The neighborhood is thriving with eateries, retailers and nightlife – all just a short walk away. Pathfinder purchased the property in 2015 from a nonprofit organization; the buildings had not been upgraded in nearly a quarter-century. The interiors lacked functional floorplans and there was inadequate onsite parking – conditions that served the needs of the nonprofit but would not meet the demands of today’s renters. We saw beyond these inherit deficiencies and recognized a rare opportunity to reposition a well-located property into a high-end, boutique coastal community. Our business plan involved rebranding the property () and completely remodeling the apartment interiors including reconfiguring the floorplans, adding washer/dyers and installing smarthome-features (keyless-entry locks, voice-activated lights, video-monitoring doorbells and smart phone compatibility). Additionally, we painted the exterior, installed drought-tolerant landscaping, increased parking and installed a dog wash station, resident package lockers, bike racks and two community BBQ/firepit T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 11 lounge areas. In January, we completed our renovations and began leasing. Like beachcombing, the search for a new home is a process of discovery and we believe our residents at Driftwood have found a true coastal treasure. PACIFIC BEACH: Did You Know? Pacific Beach – Early History: One of San Diego’s oldest suburbs, Pacific Beach was established in 1887 by bankers and real estate operators who cleared away grainfields, mapped lots and hired an auctioneer. To attract people, the founders built a race track and a college, neither of which exist today. In 1902, Pacific Beach lots sold for $350-$700 for ocean front property. By 1950, the average home price was $12,000 – today’s Pacific Beach’s median home price is $895,000 and the median rent is $2,850/month (Zillow). Mission Bay Park: A 4,235-acre park comprised of 46% land and 54% water, this is the largest man-made aquatic park in the country. The park provides an abundance of recreational activities including sailing, golfing, waterskiing, fishing, camping, cycling, jogging and 27 miles of shoreline, 19 of which are sandy beaches ideal for sunbathing. The first modern triathlon was held at Mission Bay Park in 1974. Jefferson Pacific Beach: In September 2017, Texas-based developer JPI broke ground on a $104,000,000 mixed-use project comprised of 172unit luxury apartments and 14,000 square feet of retail. The project, named Jefferson Pacific Beach, is located on the former site of the Guy Cadillac auto dealership and is designed to serve as a new gateway to Pacific Beach and Mission Bay. The project marks the first major new apartment development in the area in decades. Construction is scheduled for completion later this year. T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 12 NOTABLES AND QUOTABLES “ Preparation “Give me six hours to chop down a tree, and I will spend the first four sharpening the ax.” “Success occurs when opportunity meets preparation.” - Zig Ziglar, American author - Abraham Lincoln “I don’t believe in luck, I believe in preparation.” “Spectacular achievement is always preceded by unspectacular preparation.” - Robert H. Schuller, American author - Bobby Knight, College basketball coach “One important key to success is selfconfidence. An important key to selfconfidence is preparation.” “There is no shortcut to achievement. Life requires thorough preparation – veneer isn’t worth anything.” - George Washington Carver, American scientist - Arthur Ashe, American tennis player “The best preparation for tomorrow is to do today’s work superbly well.” “Success depends on previous preparation and without such preparation there is sure to be failure.” - Sir William Osler, Canadian physician T HE PAT HF I NDE R R E PO R T: FE B R UARY 2019 - Confucius, Chinese philosopher 13 PAT HF I NDE R R E PO R T: FE B R UARY 2019 14 Winter is Coming
https://issuu.com/pfpllc/docs/pathfinder-report-february2019?e=0
CC-MAIN-2019-13
refinedweb
5,839
60.75
SYNOPSIS #include <nng/transport/inproc/inproc.h> int nng_inproc_register(void); DESCRIPTION The inproc transport provides communication support between nng sockets within the same process. This may be used as an alternative to slower transports when data must be moved within the same process. This transport tries hard to avoid copying data, and thus is very light-weight. The inproc transport is generally built-in to the nng core, so no extra steps to use it should be necessary. URI Format This transport uses URIs using the scheme inproc://, followed by an arbitrary string of text, terminated by a NUL byte. Multiple URIs can be used within the same application, and they will not interfere with one another. Two applications may also use the same URI without interfering with each other, and they will be unable to communicate with each other using that URI. Socket Address When using an nng_sockaddr structure, the actual structure is of type nng_sockaddr_inproc. Transport Options The inproc transport has no special options.
https://nng.nanomsg.org/man/v1.2.2/nng_inproc.7.html
CC-MAIN-2020-10
refinedweb
166
55.34
In this article, we are going to download the dataset that we are going to use for our model. This is article is the second part of the series about this amazing Segmentation Network used for the task of semantic segmentation. Furthermore, this Segmentation Network brings a novel approach to decouple the function of spatial information preservation (high-resolution features) and receptive field offering two paths. Specifically, it is proposed a Bilateral Segmentation Network(BiSeNet) with a Spatial Path(SP) and a Context(CP). This two paths came to fix previous approaches used in the semantic segmentation task, that compromise of accuracy over speed. I have alredy covered Semantic segmentation and BiSeNet introduction, its not in the scope of this blog post. Therefore, for more details about BiSeNet with SP & CP, please click on the links to see my previous blog posts. Without further ado, let’s get this show on the road! Dataset A data set (or dataset) is a collection of data. Most commonly a data set corresponds to the contents of a single database table. i.e An excel spreadsheet is a great example of a dataset. First things first, we have got to have data to train our Artificial Intelligence(AI) algorithm, for example: In supervised learning we want the AI algorithm to learn the mapping between the input(x) and output(y), so that given a new input(x) that is not part of the dataset it was trained on it can predict the output(y). In order to get a dataset, we can collect it ourselves via web scraping or download a dataset someone else put together. There are some pretty famous dataset repositories which offer us a variety of datasets for many ends, such as : - ImageNet - CamVid (which is the dataset we will be using) - COCO stuff - Kaggle and etc.. Unlike many think, Kaggle does not only host Data Science competitions, it also a dataset and kernel repositories, where Data Scientist share their dataset and their kernels that give more insight about their datasets. For our implementation of the BiSeNet, we are going to use a dataset called CamVid, that was mentioned in the research paper by the researchers that invented BiSeNet. The CamVid dataset is a street scene dataset from the perspective of a driving automobile. It is composed of 701 images in total, in which 367 for training, 101 for validation and 233 for testing. The images have a resolution of 960×720 and 11 semantic categories/labels. To download the dataset and labels click here. Preprocessing and Visualizing. Furthermore, we might not use the entire dataset because some features are not important or relevant to our problem. For example if we want an algorithm to distinguish dogs from cats, and our dataset contains their pictures in one column and the name of the owners in the other column as input features, we can discard the name of the owners column because it does not contribute at all to distinguish dogs from cats, all we need is the features like shape of the ears , nose, and type of fur, which are in picture’s column. Implementation In this section, I’m going to present you the code I use to load the files, convert them into a Numpy array and plot them using jupyter notebooks. The first step is to import the libraries we are going to use to manipulate the data and get the path where the dataset is saved, whether on your laptop or cloud. import os import matplotlib.pyplot as plt import matplotlib.image as mpimg #image_path is defined as a global variable image_path = "path to where you saved your dataset" After this, we are going to write a function which receives path as a parameter in order to get all the files in that path and put them in a list. def loadImages(path): image_files = sorted([os.path.join(path, 'train', file) for file in os.listdir(path + "/train") if file.endswith('.png')]) annotation_files = sorted([os.path.join(image_path, 'trainannot', file) for file in os.listdir(path + "/trainannot") if file.endswith('.png')]) image_val_files = sorted([os.path.join(path, 'val', file) for file in os.listdir(path + "/val") if file.endswith('.png')]) annotation_val_files = sorted([os.path.join(path, "valannot", file) for file in os.listdir(path + "/valannot") if file.endswith('.png')]) return image_files, annotation_files, image_val_files, annotation_val_files Then we can make the main function that calls the loadImages() function and passes the parameter path. Algorithms can’t read an image as they are, we need to convert them into a 2d array so we can then feed it to the algorithm and visualize it. def main(): #calling global variable global image_path # The var Dataset is a list of size 4 that gets all files from different folders so we can access different folders using dataset[0...3] dataset = loadImages(image_path) train_set = dataset[0] r = [i for i in train_set] print(r[0]) img_1 = mpimg.imread(r[0]) display = plt.imshow(img_1) print(img_1) main() For the full code used in this post, here is the link for my GitHub. This repo contains the code for a fierce t attempt to implement this amazing Research paper. …github.com This concludes the Part II of this series about BiSeNet, stay tuned for more amazing content and Part II with the code for implementing this state-of-the-art Real-time semantic segmentation Network research paper. Thank you for reading if you have any thoughts, comments or critics please comment down below. If you like it please give me a round of applause👏👏 👏and share it with your friends. Resources: In this post, I’m going to give you an introduction to Bilateral Segmentation Network for Real-time Semantic…medium.com The recipe of the Success of BiSeNet (Bilateral Segmentation Network).medium.com Data is measured, collected and reported, and analyzed, whereupon it can be visualized using graphs, images or other…en.wikipedia.org In relational databases and flat file databases, a table is a set of data elements (values) using a model of vertical…en.wikipedia.org Source: Deep Learning on Medium
http://mc.ai/bisenet-for-real-time-segmentation-part-ii/
CC-MAIN-2019-09
refinedweb
1,021
62.58
Products and Services Downloads Store Support Education Partners About Oracle Technology Network FULL PRODUCT VERSION : A DESCRIPTION OF THE PROBLEM : This is a problem shared between Java >=1.6 and the ion3 window manager. In combination, a Swing application which has keyboard focus on a field will lose it if you change to other window and return back to the first one. Then, no key works until you click again on any field. This happens prominently with Netbeans 6.5 (all editors are blocked) but also with a simple program like this one: --- TypeInSwing.java ---------------------------------------- import javax.swing.JFrame; import javax.swing.JTextField; public class TypeInSwing { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorldSwing"); final JTextField field = new JTextField("type here"); frame.getContentPane().add(field); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } -------------------------------------------------------------- To reproduce the bug: 1. Install in GNU/Linux the ion3 window manager (both 20080207-2 from Ubuntu or the latest version, 20090110, works. You can run it without installing via 2. Learn to move between tabs with the keyboard. I think the default is Alt+K N for next and Alt+K P for previous. 3. Run some programs so that you have more than one tab. 4. Run that example program with Java 1.6 or 1.7. 5. Click on the text field and type; it works. 6. In ion's tab bar, select another tab (either with mouse or with keyboard). 7. Select the example program's tab again (either with mouse or with keyboard). 8. Try to continue typing, but it doesn't work. The cursor is nowhere. You must click again in the editor. In my tests I saw: - another window manager (ex: icewm) doesn't show this problem: the focus isn't lost. This with Java 1.6 - but in ion3, Java 1.4 and Java 1.5 also don't show this problem. - Affected: Java 1.6.0_06 on Ubuntu, Java 1.6.0_10 on Debian, OpenJDK 1.6.0_0-b11 Debian, Java 1.7.0-ea-b43 Debian. - Not affected: sun-java5-bin on Debian Etch, gij/libgcj 1.4.2 (4.0.2), 1.5.0_16-b02 on Debian This may be a regression in Java 1.6 or a bug in ion3. REPRODUCIBILITY : This bug can be reproduced always. Release Regression From : 5.0 The above release value was the last known release where this bug was not reproducible. Since then there has been a regression. EVALUATION The problem is still reproducible in latest jdk7 and 6 update builds on xmonad/ion3 WMs. There is a bug submitted against xmonad: that describes the problem in WM: "Java sets <Globally Active> model for its Frames/Dialogs, and <No Input> model for its Windows. In both of these cases the WM shouldn't call XSetInputFocus by itself. In the former case it should send the WM_TAKE_FOCUS event to the window (when it decides that the toplevel window should get the focus), in the latter case it shouldn't do anything (Java processes all the clicks by itself)." The test attached to the report demonstrates the problem: "The correct behaviour of this program in the WM is to print the message "event on frame %i: WM_TAKE_FOCUS" (where %i is the number of frame, 0 or 1 in this program) whenever the focus is set to its window using the WM (either using keys, or mouse). Incorrect behaviour is when it prints only pairs of the "FocusIn"/"FocusOut" messages." When I run the native test in my environment (xmonad 0.9.1), I'm always seeing that the test prints the "FocusIn"/"FocusOut" messages (without any WM_TAKE_FOCUS) event which is considered improper. So, I'm closing this CR as "Not a defect". In addition to the above, it should be mentioned that in jdk7 the failure becomes more severe. This is how the Java's test behaves: 1-7. same as the CR describes 8. try to continue typing, but it doesn't work. Try click in the editor and continue, it still DOESN'T work. So, user unable to move focus to the editor at all. It's been introduced by the following focus changes (part of 6522725): src/solaris/classes/sun/awt/X11/XDecoratedPeer.java public boolean requestWindowFocus(...) + if (target == realNativeFocusedWindow) { + focusLog.fine("The window is already natively focused."); + return true; + } Obviously, the method will always skip "request focus" when WM automatically sets the input focus itself. I guess this is what happens on xmonad/ion3: when the user moves mouse over a window, the WMs set focus to the window because the focus-follows-mouse policy is enabled by default in the WMs. EVALUATION An issue specific to Ion window manager (officially not supported). Not reproducible for me using ubuntu 8.04, GNOME, Metacity window manager, jdk6u7. EVALUATION A problem with the specific window manager, reassigned to AWT
http://bugs.sun.com/view_bug.do?bug_id=6798064
CC-MAIN-2013-20
refinedweb
815
68.36
got an application that is run from Java Web Start (or any JNLP launcher). Because it is run from a JNLP file it has to come in the form of one or more jar files. Recently I added IBM's Bean Scripting Framework (BSF) and Jython as one of the languages so I now include bsf.jar and jython.jar with my application. So far, so good... But if I run a script that does something like: from pawt import swing I get an error because it doesn't know what pawt is, I assume I would get the same error using any of the various Python modules. This is hardly surprising though as I didn't include the library it needed. Unfortunately, my crude attempt to add the library by turning the Lib directory from jython-2.1a3 into a Lib.jar file did not work. It still doesn't find pawt even when I just run the BSF from the command line like so: C:\Program Files\jython-2.1a3\Demo\swing>java com.ibm.bsf.Main -in simple.py -mode exec Traceback (innermost last): File "<string>", line 7, in ? ImportError: no module named pawt exception from Jython: Traceback (innermost last): File "<string>", line 7, in ? ImportError: no module named pawt : Traceback (innermost last): File "<string>", line 7, in ? ImportError: no module named pawt The classpath in this case included bsf.jar, jython.jar, and the Lib.jar I made. It was capable of running another example from the BSF examples that only used the awt and didn't need pawt. Question 1: Is there a way to create a jar I can include with my distribution that I can include in my classpath and jython will find its library files within it? I did get a message from the jython runtime telling me it was "processing" (or something like that) Lib.jar the first time I ran this command with Lib.jar in the classpath but I still got the error seen above. Question 2: Shouldn't there be a way to do this AND shouldn't the jar be provided by default or a way to create it be provided? Distribution of jython with other applications is hardly an unusual thing. Thanks very much, John Muns
https://sourceforge.net/p/jython/mailman/message/7578112/
CC-MAIN-2017-13
refinedweb
380
75.2
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. hello, I'm try to create a script field that will give me all the fix version of specif project, based on Jira project picker field. so if will select project x i will see all fix version of x project. how can i create this script field. Thanks. Hello, I am not sure what you mean by all fix versions for x project. But If you want to get all versions for the selected project. The script will be like this import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.project.Project def projectCS = ComponentAccessor.getCustomFieldManager().getCustomFieldObjectByName("test_project_picker") def project = issue.getCustomFieldValue(projectCS) as Project def versionList = ComponentAccessor.getVersionManager().getVersions(project) return versionList.toString() thanks, but I was wrong with my approach to this problem. the problem is: The user should select a project from the Jira project picker field. after the user selects a project he will be able to select the project version from custom select list field. so I need another field that will copy the script field value (your answer ) or maybe script listener..
https://community.atlassian.com/t5/Jira-questions/How-to-get-fix-version-of-specific-project-based-on-Jira-project/qaq-p/708608
CC-MAIN-2018-09
refinedweb
202
51.44
Stackblitz is a popular online IDE for creating and sharing projects that is used by companies like Google and GitHub. Stackblitz, which is powered by VS Code, provides its users with the capability to spin up and share fullstack applications that use frameworks and libraries like React, Vue, and Angular. Because Stackblitz projects are online immediately, you can share your project with just a single click! Recently, Stackblitz introduced WebContainers, which allow users to run entire Node.js processes inside of the browser, offering benefits for security, speed, and performance. As a result, users can also run Next.js projects in the browser! In this article, we’ll explore this functionality in depth. Let’s get started! Node.js primitives Before we can understand how Stackblitz works, we have to understand the functionality behind Node.js. Node.js, a JavaScript runtime, is built on top of the Chrome V8 engine, which converts JavaScript code written by developers into something that a computer can understand. Node.js made it possible for developers to run their JavaScript code in native environments like the operating system without the need for a browser. I/O primitives, which are part of the standard library, allow Node.js to perform operations like accessing a database, making a network request, and reading from the file system. Node.js offers both blocking and non-blocking implementations of I/O primitives. However, we prefer non-blocking primitives, which are executed on a single thread. Node.js depends on its own unique event-based system that prevents concurrency issues that arise due to multi-threading when running operations in parallel. Node.js in the browser You can install Node.js on macOS, Windows, and Linux machines. Although currently still in beta, thanks to WASM and the capabilities API, it’s also possible to run Node.js in the browser! In Stackblitz WebContainers, the WASM layer successfully abstracts the OS layer away, causing the Node.js process running inside of the browser tab to actually function as if it were running inside of a full-fledged operating system! Setting up a Node.js WebContainer Now, let’s try it out! Let’s head over to Stackblitz and try running some of our own code. To start a new project, visit the homepage and click on Node.js. Within seconds, a new project will be created for us, which includes the file system for our project on the left, a code editor for making changes in the center, and a terminal at the bottom. To add our code, run the code snippet below in the terminal: node index.js The version of Node.js we’re currently using will be printed to the console via the code. Let’s write some code that works with our file system. Create a file called tmp.txt in the same project and add the following text: Hello World Next, we’ll add the following code snippet, which reads the file and truncates it to just five characters: const { open } = require('fs/promises'); async function readAndTruncate() { let filehandle = null; try { filehandle = await open('tmp.txt', 'r+'); await filehandle.truncate(5); } finally { await filehandle?.close(); } } readAndTruncate(); Upon running this code and checking tmp.txt, we see that our initial input has been modified to read Hello, meaning our Node.js primitive for reading from and writing to a file has worked! Next.js in the browser Now that we’ve run the Node.js WebContainer successfully, let’s set up a Next.js project. First, let’s understand the functionality behind Next.js and Stackblitz. Keep in mind that Next.js is a React-based framework that offers static rendering, server-side rendering, and image optimization out of the box. Let’s briefly consider the differences between accessing a React application and accessing a Next.js application. Accessing a React application To access a React application, we enter the application URL in the browser. The browser will fetch the HTML, CSS, and JavaScript bundles. The JavaScript is then compiled on the browser while the React code is converted to the corresponding HTML and CSS, generating the page. The page is then inserted into a div inside of the fetched HTML, pulling up the UI. Accessing a Next.js application To access a Next.js application, we enter the URL in the browser. At build time, there are several pages marked as static. If the requested page is static, it is served as is. If the page is not static, the browser checks if it is a server-side rendered page. If so, the necessary API calls are performed, and the final generated HTML and CSS are sent to the browser to display directly. If the page is neither static nor server-side rendered, you can access it in a way that is very similar to a React application! However, the final HTML and CSS will be delivered directly to the browser instead of being created when you unpack the JavaScript bundle. Rendering your page directly in the browser improves overall page load time and increases compatibility with SEO crawler bots, causing an overall performance boost! With Stackblitz web containers, you can gain these benefits without having to leave the browser. Creating our Next.js project in Stackblitz You might have noticed that the server plays a larger role in the lifecycle of a Next.js app than the lifecycle of a normal React application. The Next.js server is based on Node.js, so, historically, the Next.js server could run on any system that could support running Node.js. Now, Node.js can run completely inside of the browser with WebContainers, meaning we can also run a Next.js app in the browser! To start a new Next.js project, go to the Stackblitz home screen and click on Next.js. Alternately, you can open any browser, type Next.new in the address bar, and press enter. A new Next.js project will be set up for us! We can also create a new project based on the examples in the Next.js GitHub! We just need to append the project name in front of Next.new. For example, if I wanted to start a new project with the blog-starter example, I could run the following code in the browser: next.new/blog-starter Integrating an API Following the steps above generates a project that has two files, index.js and about.js. These files cater to two routes that the Next.js starter template provides for you, / and /about. Let’s integrate an API into our project and modify the UI rendered at the / route. For this demo, we’ll use the NASA Events API, which returns a summary of all of the climate events currently occurring on earth. We’ll use components from the React Bootstrap library to design our UI. Install the library by running the following command in the terminal: npm install --save [email protected] bootstrap We are installing these dependencies inside the Node.js environment created inside the browser. Next, let’s import Bootstrap CSS inside the index.js file: import 'bootstrap/dist/css/bootstrap.css'; Server-side rendering To retrieve the data for our project, we’ll use the getServerSideProps function in Next.js. We’ll make the call on the server side, then use the result inside IndexPage, our React component. Doing so instructs Next.js to make the call on the server side whenever any request is made from the browser for this particular component: export async function getServerSideProps(context) { const res = await fetch(''); const events = await res.json(); return { props: { nasaEvents: events } // will be passed to the page component as props }; } UI rendering Next, we’ll return the events that were fetched inside of a props key, which Next.js will pass to the React component as props. Then, we’ll use the Bootstrap components to display the events as a list: export default function IndexPage({ nasaEvents }) { return ( <div style={{ padding: 10 }}> <h2>Nasa Events</h2> <div> {nasaEvents.events.map(event => ( <Item event={event} /> ))} </div> </div> ); } Next, we’ll abstract the UI that needs to be rendered for each event into another UI component that we name Item: Helper component function Item({ event }) { return ( <Card style={{ width: '90%', marginBottom: 10 }}> <Card.Body> <Card.Title>{event?.categories[0]?.title}</Card.Title> <Card.Text>{event.title}</Card.Text> <a href={event?.sources[0]?.url}> <Button>visit</Button> </a> </Card.Body> </Card> ); } Now, our code is complete! Upon refresh, we’ll see that we are able to get a list of climate events taking place around the globe: Conclusion In this tutorial, we learned how to run a Next.js project entirely in the browser using Stackblitz WebContainers. We set up a Node.js container, then accessed a Next.js project through it, integrating an API with server-side and UI rendering. Our project includes a project URL, which helps collaboration on the development, and a deployment URL, which lets the user preview the end result. To share this project, I can simply share the project URL. I hope you enjoyed this tutorial!.
https://blog.logrocket.com/stackblitz-webcontainers-nextjs-browser/
CC-MAIN-2022-05
refinedweb
1,524
66.84
#include "ltocr.h" L_LTOCR_API L_INT EXT_FUNCTION L_OcrPage_HitTestZone(page, point, zoneIndex) Gets the zero-based index of the zone under a certain point. Gets the zero-based index of the zone under a certain point. If no zone is under the test point, 'zoneIndex' parameter will have he value -1. You can use this method to check whether a zone (either added manually or automatically) is under a given test point. For example, if you have a bitmap in your viewer you had the page zones drawn over the bitmap as rectangles and you wish to allow the user to click with the mouse on the viewer to select and de-select drawn zones, you can use L_OcrPage_HitTestZone. Required DLLs and Libraries // This example assumes you already have a page created and you have WM_LBUTTONDOWN or WM_LBUTTONUP messages taken care of // so you can send the test point you wish to check again page zones and then the example will delete the zone under that point. L_INT L_OcrPage_HitTestZoneExample(L_OcrPage ocrPage, L_POINT point) { L_INT zoneIndex = -1; L_INT retCode = L_OcrPage_HitTestZone(ocrPage, point, &zoneIndex); if(retCode != SUCCESS) return FAILURE; if(zoneIndex >= 0) { // we were able to successfully find the zone that includes the user passed point, so delete it. retCode = L_OcrPage_RemoveZoneAt(ocrPage, zoneIndex); if(retCode != SUCCESS) return FAILURE; } return SUCCESS; }
https://www.leadtools.com/help/leadtools/v20/ocr/api/l-ocrpage-hittestzone.html
CC-MAIN-2018-22
refinedweb
216
59.13
: Errror in cendif - tidotforsomersd(): 3499 tidottree() not found The fix to Richard's problem is probably to exit Stata after installing the -somersd- package (which includes -cendif-) and then launch Stata again. The -somersd- package (including -cendif-) should then work. mata: mata mlib query This list is constructed when Stata is launched. In some versions of Stata (but not others), Stata does not update its list of Mata libraries to be searched when a new package (such as -somersd-) is installed. This has the consequence that, if the user then tries to use the -somersd- package, then Stata looks for the Mata procedure -tidottree()- in its old list of libraries, and does not find -tidottree()-, and therefore gives the error message tidotforsomersd(): 3499 tidottree() not found that James has received. If James exits Stata and then launches Stata again, then Stata should re-initialize its list of Mata libraries to be searched, and this list should then include the Mata library -lsomersd.mlib-, which contains -tidottree()- and other Mata procedures used by the -somersd- package. I hope this helps. Let me know if there are any problems./07/2010 15:34, Richard Palmer-Jones wrote: Dear Readers I have the following error: . cendif incompc, by(_treat) variable incompc not found r(111); . cendif incomepc, by(_treat) Y-variable: incomepc ((mean) incomepc) Grouped by: _treated (psmatch2: Treatment assignment) Group numbers: psmatch2: | Treatment | assignment | Freq. Percent Cum. ------------+----------------- ------------------ Untreated | 260 33.85 33.85 Treated | 508 66.15 100.00 ------------+----------------------------------- Total | 768 100.00 tidotforsomersd(): 3499 tidottree() not found <istmt>: - function returned error Mata run-time error r(3499); treat is 0/1; incomepc is continuous cendif is dated 4th August 2008, and somersd has teh same date. tidotforsomersd(): 3499 tidottree() are bothe in c:\ado/plus/t which is in my ado path. . which cendif c:\ado\plus\c\cendif.ado *! Author: Roger Newson *! Date: 04 August 2008 . adopath [1] (UPDATES) "C:\Program Files\Stata11\ado\updates/" [2] (BASE) "C:\Program Files\Stata11\ado\base/" [3] (SITE) "C:\Program Files\Stata11\ado\site/" [4] "." [5] (PERSONAL) "c:\ado\personal/" [6] (PLUS) "c:\ado\plus/" [7] (OLDPLACE) "c:\ado/" I am running Stata 11.1 born 16/6/2010 All advice very gratefully recieved. Richard * * For searches and help try: * * * * * For searches and help try: * * * The reason for this is that the -somersd- package includes a Mata library -lsomersd.mlib-. In general. Stata looks for Mata routines in a list of libraries, which can be found by typing, in StataThe reason for this is that the -somersd- package includes a Mata library -lsomersd.mlib-. In general. Stata looks for Mata routines in a list of libraries, which can be found by typing, in Stata
http://www.stata.com/statalist/archive/2010-07/msg00050.html
CC-MAIN-2016-44
refinedweb
451
64.2
The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. Objective-C and Swift compatible. The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. PureLayout extends UIView/ NSView, NSArray, and NSLayoutConstraintwith. The current release of PureLayout supports all versions of iOS and OS X since the introduction of Auto Layout on each platform, in both Swift and Objective-C, with a single codebase! PureLayoutto your Podfile. pod 'PureLayout' pod installfrom Terminal, then open your app's .xcworkspacefile to launch Xcode. PureLayout.humbrella header. use_frameworks!in your Podfile import PureLayout #import(or with Modules enabled: @import PureLayout;) use_frameworks!in your Podfile #import "PureLayout.h"to your bridging header. #import "PureLayout.h" That's it - now go write some beautiful Auto Layout code! PureLayout/PureLayoutproject to your Cartfile. github "PureLayout/PureLayout" carthage update, then follow the additional steps required to add the framework into your project. import PureLayout #import(or with Modules enabled: @import PureLayout;) That's it - now go write some beautiful Auto Layout code! PureLayout.hheader. #import "PureLayout.h"to your bridging header. #import "PureLayout.h" That's it - now go write some beautiful Auto Layout code! To use PureLayout in an App Extension, you need to do a bit of extra configuration to prevent usage of unavailable APIs. Click here for more info. Releases are tagged in the git commit history using semantic versioning. Check out the releases and release notes for each version. This is just a handy overview of the core API methods. Explore the header files for the full API, and find the complete documentation above the implementation of each method in the corresponding .m file. A couple of notes: auto..., which also makes it easy for Xcode to autocomplete as you type. relation:parameter to make the constraint an inequality.Attributetype. NSLayoutConstraint + autoCreateAndInstallConstraints:subclass),. Open the project included in the repository (requires Xcode 6 or higher). It contains iOS ( Example-iOSscheme) and OS X ( Example-Macscheme)scheme.. Check out some Tips and Tricks to keep in mind when using the API. There are quite a few different ways to implement Auto Layout. Here is a quick overview of the available options: PureLayout takes a balanced approach to Auto Layout that makes it well suited for any project.. Originally designed & built by Tyler Fox (@smileyborg). Currently maintained by Mickey Reiss (@mickeyreiss). Distributed with the MIT license.
https://xscode.com/PureLayout/PureLayout
CC-MAIN-2021-21
refinedweb
397
51.95
The Sigstore Trust Model I hope this post can help reduce confusion around exactly how Sigstore’s trust model works, and how trust flows from the community root down to each short-lived certificate. For more background, read A Deep Dive on Fulcio, It’s Ten O’Clock, Do You Know Where Your Private Keys Are?, and A New Kind of Trust Root first. Sigstore’s support for OIDC and more specifically — Google, Microsoft, and GitHub as Identity Providers — rightly causes concerns about reliance on centralization and “hyperscalers” for identity. This post is to hopefully explain exactly how this trust works, and how to use Sigstore without actually relying on any centralized identity infrastructure! Trust root In Sigstore, the trust flows from the community root down to the hyperscaler identity providers, not the other way around! Clients like cosign start with the TUF root established during our root key signing ceremony, and then use this to verify that all other signing material is still valid and authorized — including Google, GitHub and Microsoft. These keys are managed by a set of trusted community key holders across the world, with no single organization in control of the entire root. In addition, Google/Microsoft/GitHub are only one set of valid identity providers! Anyone can run their own and get it trusted by the Sigstore root (and therefore all Sigstore clients). This can be done using OIDC or any other valid key material accepted by TUF (including PGP). The only real difference between federated trust roots and the hyperscalers is that we currently trust the hyperscalers to issue identity tokens globally (for any email address), while federated providers are only accepted for specific namespaces. This means that you can add your own OIDC endpoint for your own domain, but not for someone else’s. This relies on a simple convention today (we only issue certificates matching the domain of the OIDC endpoint URL), but this could easily be extended to support more complex workflows using the ACME protocol for proof of domain ownership. Here’s what this looks like overall (with the original graphviz): Sigstore Without Big Tech! In the diagram above we can see a few trust flows that clearly do rely on the big identity providers — this is roughly anything going through the email-based system or the custom identity systems like GitHub Actions and EKS. But there are also a few flows that **do not** go through these paths at all! If you want to add your own, here’s how! - Pick a domain! - Setup a SPIFFE/SPIRE endpoint on that domain, and expose the OIDC endpoint - Send a four-line PR to the Fulcio repo, adding your domain! - That’s all! If you already have a SPIFFE endpoint setup, then you can skip those first two steps. You now have a fully keyless trust root that can issue identity tokens using any scheme you want, as long as they’re for your domain. All of those tokens can then be used to retrieve short-lived code signing certificates from Sigstore, and those certificates will be automatically trusted by all Sigstore clients. Don’t want to use SPIFFE/SPIRE, or the keyless system? That’s fine too! We’re also happy to accept other existing trust roots using TUF sub-delegations. These can be done using a similar flow, except via a pull request to the root-signing repository. Sigstore vs PGP When comparing Sigstore to PGP — the first thing to note is that Sigstore actually works with PGP! You can store signatures and keys in the Rekor transparency log, which can help detect key compromise and make recovery/revocation easier. Our TUF delegations also support PGP keys, so if you’re really set on using PGP for your community you can still get a delegation and reuse our trust root. What Sigstore provides is an alternative to the Web of Trust, which is only one component of PGP. PGP can be used to generate keys and use those to sign and verify blobs with no PKI, but it can also be used with the Web of Trust ecosystem. This is probably going to be the most controversial part of this post, but in my opinion the Web of Trust is fundamentally broken and has not been able to scale to the needs of the broader open source ecosystem. But wait — Debian, Ubuntu, RHEL, Node.js, and others all use PGP — how can it be broken? Simple! They’ve all built their own PKI. The Debian package repo signing keys are stored in a package and distributed in each built image. They ARE NOT fetched from key servers. The Node.js project uses a long table/script in their README.md file. Other projects are similar. I really love the idea of the Web-of-Trust, but it just doesn’t work in practice. My basic theory is that key-management is too hard for the average human long-term. I lose my keys constantly and have to make new ones. But the Web-of-Trust relies on people generating, publishing, and verifying/signing the keys of others. Every time someone loses a key and has to start over — an entire portion of the Web disappears and has to be rebuilt. With a strong, healthy trust network this wouldn’t be a big deal. But unfortunately we never get to that point (because too many people lose their keys too frequently), so key distribution has always required out of band mechanisms. I’d love to be proven wrong here. I really do like the idea of a fully decentralized identity system, but in my opinion, web of trust just isn’t that. Some of the new decentralized identity work going on in the W3C looks promising, but very early. I bet there are some new startups working on this in the blockchain space too :) Sigstore Tradeoffs I’ll be the first to say that Sigstore isn’t perfect for everyone! It was designed with a few key tradeoffs and constraints in mind that I think represent the best available today for most people, but it’s a magic solution. The big design decisions in Sigstore were based around these principles: - Centralized infrastructure is not ideal, but Transparency can mitigate many of the problems. - Over long periods of time, humans are bad at key management but great at protecting email accounts. Transparency and Centralized Infrastructure Transparency logs are a relatively new technology, and we’re still learning how they can be best used. The original RFC was written in 2013, while PGP dates back to 1981! They’ve been proven at scale in the Web PKI space where they’ve been protecting browsers and internet users against misbehaving CAs over the last several years. They’ve also started to see usage in supply chains, with Go Module Transparency from Filippo Valsorda and Russ Cox, the rget project from Brandon Philips, and the original Binary Transparency design from Mozilla. Transparency logs are now even being used for firmware transparency in the Google Pixel phones! With transparency at the core, Sigstore’s centralized infrastructure is Trusted but Verifiable — users should not need to trust us to do anything other than keep the log running. And even that part can be fixed over time! Certificate Transparency logs operate in a federated manner today, with many organizations running their own logs that gossip data between them. Certificate Authorities are even required to log certs to multiple independent instances! If we can get to that point, we can completely remove the single point of failure of the Sigstore infrastructure! Summary I hope this post helps show how the trust model in Sigstore actually works, including the role large identity providers and big tech companies actually play here. There are valid concerns with Sigstore’s architecture, but I believe many of them can be mitigated over time. Nothing is perfect, but I strongly believe that the Sigstore design has the best chance of widespread adoption and usage by anyone!
https://dlorenc.medium.com/the-sigstore-trust-model-4b146b2ecf2c?source=post_internal_links---------5----------------------------
CC-MAIN-2022-27
refinedweb
1,342
60.35
Create a Word Document From a Template using c# (Mail Merge) Posted by vivekcek on August 25, 2012 I want to create a word document from a word template.The advantage of using template is, we can define a structure for the document and decorate the it with dynamic text. Software’s Used ——————————– 1. Word 2007. 2. Visual Studio 2010 Library used —————————– 1. Microsoft Word 12.0 Object Library Steps ———————- 1. Create a Word Template. 2. Create a console application using VS 2010. 3. Add reference to Microsoft Word 12.0 Object Library. 4. Enjoy 🙂 1. Create a Word Template. ——————————————- Word templates are created using MergeField’s in word. a. Open a new Word 2007 b. Type “Name:”, Where ‘Name:’ is just a label. c. Now we need to insert a MergeField right to our label ‘Name:’ d. Place cursor on the right of our label. e. Select insert tab in word. f. Select Quick Parts. Then Field. g. Select field category as MergeField. Give the MergeField name as ‘Name’. h. Save the document as WordTemplate. Now our Template contains. Name: «Name» The field inside <> is our merge Field. We will replace that field through code to create a new word document. * Note the extension of out template will be .dotx(MyTemplate.dotx) 2. Create a console application using VS 2010. ————————————————————— a. Create a console application. b. Add refrence to Microsoft Word 12.0 Object Library. c. Add NameSpace “using Microsoft.Office.Interop.Word;”. d. The Final document will be save in MyDocuments. using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Word; namespace WordAuto { class Program { static void Main(string[] args) { //OBJECT OF MISSING "NULL VALUE" Object oMissing = System.Reflection.Missing.Value; Object oTemplatePath = "D:\\MyTemplate.dotx"; Application wordApp = new Application(); Document wordDoc = new Document(); wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing); foreach (Field myMergeField in wordDoc.Fields) { Range rngFieldCode = myMergeField.Code; String fieldText = rngFieldCode.Text; // ONLY GETTING THE MAILMERGE FIELDS if (fieldText.StartsWith(" MERGEFIELD")) { // THE TEXT COMES IN THE FORMAT OF // MERGEFIELD MyFieldName \\* MERGEFORMAT // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName" Int32 endMerge = fieldText.IndexOf("\\"); Int32 fieldNameLength = fieldText.Length - endMerge; String fieldName = fieldText.Substring(11, endMerge - 11); // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE fieldName = fieldName.Trim(); // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****// // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE if (fieldName == "Name") { myMergeField.Select(); wordApp.Selection.TypeText("Vivek"); } } } wordDoc.SaveAs("myfile.doc"); wordApp.Documents.Open("myFile.doc"); wordApp.Application.Quit(); } } } DOWNLOAD SOURCE Umair said thanks titasix said Simple but amazing. Thx Amit said It worked but when i put IF conditions on Merge field its not working as expected, can you suggest any solution for this? WIBI KURNIAWAN said THIS IS WHAT I NEED !!!, THANK YOU dinesh kumar said Thanks…………………….. shubhangi said hi this is amazing stuff what u have posted but i wnat number of copies of the letter for different number of agent…how do i perform this with you code plz sugggest Sam Chang said Many thanks, this is exactly what I need! A user said Hi, thanks you. May i know how to set path for below two? i try out this two line code save the file in different path… wordDoc.SaveAs(“myfile.doc”); wordApp.Documents.Open(“myFile.doc”); robert said string fileName = @”C:\Users\yourUSR\Desktop\myfile.doc”; wordDoc.SaveAs(fileName); Process.Start(“WINWORD.EXE”, fileName); Peter J. said If you use COM on server side (e.g. ASP.NET) you would probably have problems like this:. You can try out this library which is free or some good but affordable third party like. Arnold Wiersma said Thanks, this works great for the body of the document. Does anyone here know how to access the fields in the header and footer for office 2010? Murugavel S said hi, Excellent. But how to be configured the Field names are get from DB. please help me Murugavel S Eduardo Bessa said And to fill in various fields? Help me please Aravind said Its very good for one or two fields,but I need to get a bunch of data merged by connecting to the sql server please help Rutvij Thakar said Hi, its a nice stuff i done it through sql data.. hossein said similiar job with image possible? Momo said Thank you very much!!!!! Very easy to learn!! Dhananjay said Thank u but this code not working on server when i am hosting my web application on server, So please suggest me ??? what can i do??? Rajesh said great great great … simply amazing !!! Just one query can i use this in table view ? pradeep said Hi all, If the fieldname consits of “\”value name \”” ..? then. What is the solution please help me. mmc said I want to do the same for bulk . i.e. letters should open in bulk for different values for the same mergefield in one document and data in there should come from the SQL server database. PS said Thank you. It helps me over dificully Sangeetha said @dhananjay, if it is not working after getting deployed to server that’s mainly because some .dll might be missing. check for msvcp….. Sangeetha said @dhananjay, if its not working after getting deployed in server that’s because some dll might be missing check for msvcp………… Hugh said How can you go about merging mailing labels which required to loop through a set of records (from Linq var List)? which is more a like real world problem? Thanks raja said showing error in wordDoc.SaveAs(“myfile.doc”); wordApp.Documents.Open(“myFile.doc”); wordApp.Application.Quit(); in these lines vibhusha said is it works on web application ? vivekcek said Nop try openxml vibhusha said i’ts working fine , thank you so much vivekcek. now my question is, how to set multiple values on word, the value is getting from database. vibhusha said i’ts working fine , thank you so much vivekcek. now my question is, how to set multiple values on word, the value is getting from database.
https://vivekcek.wordpress.com/2012/08/25/create-a-word-document-from-a-template-using-c-mail-merge/
CC-MAIN-2017-47
refinedweb
1,016
69.38
This. In the XMonad.Hooks namespace you can find modules exporting hooks. Hooks are actions that xmonad performs when certain events occur. The two most important hooks are: Here is a list of the modules found in XMonad.Hooks:. In the XMonad.Prompt name space you can find modules providing graphical prompts for getting user input and using it to perform various actions. The XMonad.Prompt provides a library for easily writing new prompt modules. These are the available prompts: Usually a prompt is called by some key binding. See XMonad.Doc.Extending, which includes examples of adding some prompts.: Since the xmonad.hs file is just another Haskell module, you may import and use any Haskell code or libraries you wish, such as extensions from the xmonad-contrib library, or other code you write yourself.s. In this example we have a list of XMonad.Config.ManageHookss.!
http://hackage.haskell.org/package/xmonad-contrib-bluetilebranch-0.8.1.3/docs/XMonad-Doc-Extending.html
CC-MAIN-2015-48
refinedweb
148
68.36
You can write the data to a file on the SD as a Comma-Separated Values file. A CSV file can be read directly by Excel.Pete can yo help me with some details because i don't dealing with this before Which part are you having trouble with?Do you have an SD card?Can you write a text file to it?Can you google "comma separated variable"? #include <SD.h>File myFile;void setup(){ Serial.begin(9600); myFile = SD.open("test.csv", O_APPEND | O_WRITE); if(myFile) { myFile.println("1,2,3"); myFile.println("101,322,8293"); myFile.println("7012,3964,281"); myFile.close(); } else { Serial.println("Can't open test.csv on the SD card"); }}void loop(void){} I haven't been able to test this code but it does at least compile. It should create the file test.csv on an SD card, write three lines of data to the file and then close it. If it works, you can then just put the SD card in a PC and double-click on the file which should open the file in Excel.Pete That one is not directly compatible with UNO because the UNO uses 5V and micro-SD cards use 3.3V. You would have to do a level conversion to make them compatible.I use the Adafruit board which is a bit more expensive but handles the conversion. are easy to wire up. They will use pins 10,11,12 and 13 on the UNO. And note that the SPI hardware requires Pin 13 which means it can't be used for the LED indicator.Pete These: probably be what you need to use the board you have.You seriously are better off using though.I use it extensively to log to a multiple csv files. Please enter a valid email to subscribe We need to confirm your email address. To complete the subscription, please click the link in the Thank you for subscribing! Arduino via Egeo 16 Torino, 10131 Italy
http://forum.arduino.cc/index.php?topic=142559.msg1070481
CC-MAIN-2016-18
refinedweb
336
77.53
Opened 8 months ago Last modified 7 months ago #23004 new New feature Cleanse entries from request.META in debug views Description In the debug views settings is cleansed, which hides e.g. SECRET_KEY. But a lot of sensible information might also be present / come from request.META, e.g. in the form of DJANGO_SECRET_KEY or DATABASE_URL. It might be sensible to apply a filter in TECHNICAL_500_TEMPLATE (source code reference:). I see that this can be quite specific, but I think it would be sensible to apply HIDDEN_SETTINGS to all entries starting with DJANGO_ and have a setting for additional entries, which might default to DATABASE_URL and SENTRY_DSN. Change History (4) comment:1 Changed 8 months ago by blueyed - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 8 months ago by timo - Triage Stage changed from Unreviewed to Accepted I would do something like move the cleanse_setting() function to a method on ExceptionReporterFilter and make things like HIDDEN_SETTINGS attributes. You could then easily override them in a subclass to avoid introducing more global settings. Regarding your comment, it's a separate issue but I don't think the test client should include os.environ. You shouldn't rely on environment variables in your views. comment:3 Changed 8 months ago by blueyed Just answering to the separate issue from the comment about request.META - I do not have time to provide a patch for this issue myself, but thanks for accepting it and outlining how it could be done! Regarding your comment, it's a separate issue but I don't think the test client should include os.environ. You shouldn't rely on environment variables in your views. It's more that I want to test for e.g. assert settings.SECRET_KEY not in response.content (for a "500" page), and was surprised that request.META in the test client is different from runserver/uwsgi. I have created a new issue for it: comment:4 Changed 7 months ago by sthzg I am interested in this topic and started experimenting with @timo's suggestions. I hope it is okay to put some questions here, because I am not completely sure about the scope of it and would be interested in your opinion. --- After reading through the code, the cleanse_setting() method seems to only be relevant to parsing values from the settings. Cleansing POST for example (which like META is part of the request instance) is done as part of SafeExceptionReporterFilter. What I am experimenting with is to provide similar behavior for request.META as there already is for POST. I implemented a get_meta_parameters() on SafeExceptionReporterFilter that cleanses all values in META that match the HIDDEN_SETTINGS (that are now an attribute of ExceptionReporterFilter). def get_meta_parameters(self, request): """ Replaces the values of META parameters that match defined patterns from HIDDEN_SETTINGS with stars (*********). """ if request is None: return {} else: cleansed = request.META.copy() # Cleanse all values that match the regexp in HIDDEN_SETTINGS. for k, v in cleansed.items(): if self.HIDDEN_SETTINGS.search(k): cleansed[k] = CLEANSED_SUBSTITUTE return cleansed Now my idea would be to extend the Context instance in get_traceback_data() to get a filtered_META, analog to what it does to get the filtered_POST c = { # ... 'filtered_POST': self.filter.get_post_parameters(self.request), 'filtered_META': self.filter.get_meta_parameters(self.request) # ... } Then, if filtered_META is not empty, I thought about changing the TECHNICAL_500_TEMPLATE to loop over that. Before I go on I would be interested if this was still accepted in terms of behavior and scope or if a solution in that direction would be unlikely to make its way to core. If yes I would be happy trying to code it and backing it up by tests and then come back here to discuss the possible patch. I have noticed that the environment variables do not appear to be present when using Django's test.Client / live_server. Shouldn't the test client's request.meta also include os.environ?
https://code.djangoproject.com/ticket/23004
CC-MAIN-2015-11
refinedweb
658
55.13
huex alternatives and similar packages Based on the "Miscellaneous" category. Alternatively, view huex alternatives based on common mentions on social networks and blogs. AtomVM9.5 8.0 huex VS AtomVMTiny Erlang VM porcelain9.4 0.1 huex VS porcelainWork with external processes like a boss ex_rated8.5 3.0 huex VS ex_ratedExRated, the Elixir OTP GenServer with the naughty name that allows you to rate-limit calls to any service that requires it. hammer8.5 0.0 huex VS hammerAn Elixir rate-limiter with pluggable backends Apex8.1 0.0 huex VS ApexAwesome printing for Elixir ex_phone_number7.9 4.8 huex VS ex_phone_numberElixir port of libphonenumber Countries7.7 2.8 huex VS CountriesCollection of Country Information for Elixir. ex2ms7.4 3.2 huex VS ex2ms:ets.fun2ms for Elixir, translate functions to match specifications codec-beam7.2 0.6 huex VS codec-beamGenerate Erlang VM byte code from Haskell ecto_autoslug_field7.1 3.8 huex VS ecto_autoslug_fieldAutomatically create slugs for Ecto schemas. exsync7.0 1.2 huex VS exsyncYet another elixir reloader. phone6.9 4.2 huex VS phoneElixir phone number parser for numbers in international standard. funnel6.5 0.0 huex VS funnelStreaming Elixir API built upon ElasticSearch's percolation. elixir-browser6.2 0.0 huex VS elixir-browserBrowser detection for Elixir exquisite6.1 0.0 huex VS exquisiteLINQ-like match_spec generation for Elixir. std_json_io5.8 0.0 huex VS std_json_ioA simple library for Elixir that provides json over STDIO pact5.8 0.0 huex VS pactBetter dependency injection in Elixir exldap5.7 1.3 huex VS exldapA module for working with LDAP from Elixir molasses5.4 0.0 huex VS molassesFeature toggle library for elixir bupe5.3 0.0 huex VS bupeBUPE is a Elixir ePub generator and parser (supports EPUB v3) reprise5.1 0.0 huex VS repriseSimplified module reloader for Elixir exprint4.9 0.0 huex VS exprintA printf / sprintf library for Elixir. It works as a wrapper for :io.format. gen_task4.9 0.0 huex VS gen_taskGeneric Task behavior that helps encapsulate errors and recover from them in classic GenStage workers. countriex4.5 0.0 huex VS countriexAll sorts of useful information about every country. A pure elixir port of the ruby Countries gem erlang_term4.4 0.0 huex VS erlang_termErlang Term Info address_us4.3 1.3 huex VS address_usUS Address Parsing for Elixir. expyplot3.8 0.0 huex VS expyplotMatplotlib for Elixir Jisho-Elixir3.5 0.0 huex VS Jisho-ElixirA Japanese dictionary API; a wrapper around Jisho's API () ratx3.4 0.0 huex VS ratxRate limiter and overload protection for erlang application expool3.4 0.0 huex VS expoolExtremely simple Process pooling and task submission in Elixir vessel3.3 0.0 huex VS vesselElixir MapReduce interfaces with Hadoop Streaming integration dye3.0 0.0 huex VS dyeDyeing your terminal! egaugex2.8 0.0 huex VS egaugexA simple egauge parser to retrieve and parse data from egauge devices presentex2.5 0.0 huex VS presentexElixir -> HTML/JavaScript based presentation framework intended for showing Elixir code ratekeeper2.3 0.0 huex VS ratekeeperRatekeeper is a library for scheduling rate-limited actions. mixgraph2.1 0.0 huex VS mixgraphAn interactive dependency plotter for your Hex Package mixstar2.1 0.0 huex VS mixstarElixir Mix task to starring GitHub repository with `mix deps.get`ting dependent library exlibris1.8 0.0 huex VS exlibrisA collection of random library functions. gimei_ex1.8 0.0 huex VS gimei_exElixir port of gimei library. growl1.6 0.0 huex VS growlSimple wrapper for growl, the notification system for OSX PhoneNumber1.6 0.0 huex VS PhoneNumberPhone number validating for Elixir Ralitobu1.5 0.0 huex VS RalitobuRate Limiter with Token Bucket algorithm (Elixir) netrc1.4 0.0 huex VS netrcReads netrc files implemented in Elixir url_unroller1.3 0.0 huex VS url_unrollerA simple url unroller (un-shortener) in elixir charm1.3 0.0 huex VS charmANSI rainbow for elixir, be a magician spawndir1.3 0.0 huex VS spawndirSpawn processes from the file system. darksky-elixir1.2 0.0 huex VS darksky-elixirDark Sky API wrapper in Elixir. exfcm1.0 0.0 huex VS exfcmExFCM is a simple wrapper around Firebase Cloud Messaging keys1value1.0 0.0 huex VS keys1valueErlang set associative map for key lists onetime0.8 0.0 huex VS onetimeAn onetime key-value store for Elixir Do you think we are missing an alternative of huex or a related project? Popular Comparisons README Huex Elixir client for Philips Hue connected light bulbs. Installation Add Huex as a dependency in your mix.exs file. def deps do [{:huex, "~> 0.8"}] end Also add HTTPoison as part of your applications, in your mix.exs file. def application do [mod: {YourApp, []}, applications: [:httpoison]] end After you are done, run mix deps.get in your shell to fetch and compile Huex. Usage First Connection In order to issue queries and commands to the bridge, we need to request an authorization for a so-called devicetype (see Hue Configuration API) which is a string formatted as such: my-app#my-device. Before requesting the authorization: you must press the link button on your bridge device to start a 30 second window during which you may request an authorization as follow: bridge = Huex.connect("192.168.1.100") |> Huex.authorize("my-app#my-device") # A random username is now set IO.puts bridge.username # YApVhLTwWUTlGJDo... # The bridge connection is now ready for use IO.inspect Huex.info(bridge) # %{"config" => ...} Subsequent Connections Once a devicetype has been authorized with the bridge, there's no need to perform the authorization process again. In other words, you must store the generated username received set by authorize/2. With the username at hand, you can connect right away: bridge = Huex.connect("192.168.1.100", "YApVhLTwWUTlGJDo...") IO.inspect Huex.info(bridge) # %{"config" => ...} Bridge IP address discovery You may use Huex.Discovery.discover/0 to retrieve a list of bridges on your network using SSDP: Huex.Discovery.discover # ["192.168.1.43"] This optional feature depends on nerves_ssdp_client which must be added explicitly to your own application dependencies in mix.exs: def deps do [{:huex, "~> 0.7"}, {:nerves_ssdp_client, "~> 0.1"}] end Queries Query functions return the message received from the bridge API. IO.inspect Huex.info(bridge) # %{"config" => %{"UTC" => "1970-01-01T03:00:40", "dhcp" => true, # "gateway" => "192.168.1.1", "ipaddress" => "192.168.1.100", # ... # "schedules" => %{}} IO.inspect Huex.lights(bridge) # %{"1" => %{"name" => "Lobby"}, "2" => %{"name" => "Living Room"}, # "3" => %{"name" => "Bedroom"}} IO.inspect Huex.light_info(bridge, 1) # %{"modelid" => "LCT001", "name" => "Lobby", # ... # "swversion" => "66009663", "type" => "Extended color light"} Commands Command functions return a Huex.Bridge struct and are thus chainable. bridge |> Huex.turn_off(1) # Turn off light 1 |> Huex.turn_on(2) # Turn on light 2 |> Huex.set_color(2, {10000, 255, 255}) # HSV |> Huex.set_color(2, {0.167, 0.04}) # XY |> Huex.set_color(2, Huex.Color.rgb(1, 0.75, 0.25)) # RGB (see limitations) |> Huex.set_brightness(2, 0.75) # Brightness at 75% Error Handling For error handling, the Huex.Bridge struct has a status attribute which is either set to :ok or :error by command functions. When an error occured, the complete error response is stored in the error attribute of the Huex.Bridge struct. Examples Look into the examples directory for more advanced usage examples. Current Limitations Color space conversion from RGB to XY currently feels a little fishy: I can't seem to get bright green or red using the given formula. To Do - [ ] Reliable color conversion from RGB Contributors In order of appearance: - Xavier Defrang (xavier) - Brandon Hays (tehviking) - Brian Davis (mrbriandavis) - Pete Kazmier (pkazmier) - Derek Kraan (derekkraan) - Arijit Dasgupta (arijitdasgupta) huex README section above are relevant to that project's source code only.
https://elixir.libhunt.com/huex-alternatives
CC-MAIN-2021-43
refinedweb
1,278
59.7
I discovered a problem with the way references are resolved with the package on Visual Studio 2017. Visual Studio 2019 (supports Community, Professional, and Enterprise versions) extension that enables developers to rapidly generate data entry forms from view models or entity objects for Xamarin Forms, Windows Universal (UPW), WPF, and Silverlight 5. For WPF both .NET Full Framework Full and .NET Core 3 projects are supported. At the writing of this, the primary scenario for Xamarin Forms is pages that don't require Platform-specific features to accomplish the layout, navigation, animation, or functional implementation. This tool is designed to enable the developer to create cross-platform data-bound, data entry forms rapidly.. Please see the changelog here. result will be a data entry form that renders well across platforms, with all data bindings, format strings, etc. set the way you would have you hand-coded the form. Easy Workflow From a XAML file in a Xamarin Forms or WPF project, right-click in the editor where you want your form to be inserted. NOTE: You must build your solution if you've made changes to any view model or entity class BEFORE opening XAML Power Toys. This tool uses reflection to load up your solution's view models and entity classes. After clicking the XAML Power Toys command in the context menu, the below Select Source Class dialog appears. When the dialog opens: it loads the left list box will all classes where their name ends with ViewModel; case-insensitive, and it loads up all classes by the assembly, namespace, class name in the tree view on the right. It attempts to locate a view model for the active XAML file by naming convention. If one is found, it will be selected in the ViewModels list box on the left and the Next... button will be enabled. If one is not found by naming convention, the Next... button will be disabled until you selected either a view model from the ViewModels list box or a class from the Assemblies tree view. After clicking the Next... button the XAML Power Toys Form Layout Tool dialog will appear. Description Simple Usage the Generate UI button and the following form will be inserted into your XAML file where you opened the context menu. Run the Xamarin Forms UWP application, the UI looks like this: With a little styling, these forms would look great and took less than a minute to create each one. Have a look at the above application sample images that have the City, State, and Zip on the same row. The below image pictures the required settings to accomplish this. Table Section Title This form's Column Root Object is a Table View. The table views group controls in sections. In the below image, all fields are grouped in the "Address" section. City State BindablePicker The BindablePicker control is one I created and blogged about here. You can also get the BindablePicker and see many usage examples in the Xamarin Forms Bindable Picker repo here. You can see two of the supported scenarios: The States and Countries collections are exposed on the view model, making the task of setting up data bindings trivial. For cloning and building this project yourself, make sure to install the Extensibility Essentials extension for Visual Studio which enables some features used by this project. Apache 2.0
https://marketplace.visualstudio.com/items?itemName=KarlShifflettkdawg.XAMLPowerToysforVisualStudio2015
CC-MAIN-2020-10
refinedweb
563
62.98
We've provided a set of starter files with skeleton code for the exercises in the lab. You can get them in the following places:): self.talk() if thing == "poison": self.lose_life() print(self.name + " ate a " + str(thing) + "!") def talk(self): print("..") What would python print if the following is typed into the interpreter, after the first two class definitions? >>> a = Animal() >>> a.is_alive ________ >>> a.talk() ________ >>> hamster = Pet("Hamster", 2014) >>> hamster.talk() ________ >>> hamster.eat("seed") ________ >>> hamster.eat("poison") ________ Implement a Cat class that inherits from Pet. Use superclass methods wherever possible. class Cat(Pet): """ >>> my_cat = Cat("Furball", 2011, "Me", lives=2) >>> my_cat.talk() Meow! >>> my_cat.name 'Furball' >>> my_cat.lose_life() >>> my_cat.is_alive True >>> my_cat.eat("poison") Meow! Furball ate a poison! >>> my_cat.is_alive False >>> my_cat.lose_life() 'Cat is dead x_x' """ def __init__(self, name, year_of_birth, owner, lives=9): assert type(lives) == int and lives > 0 "*** ***" Now implement a NoisyCat class, which inherits from Cat. A NoisyCat is just like a normal Cat except, when asked to talk, it says what a normal Cat says twice. class NoisyCat(Cat): """ >>> my_cat = NoisyCat("Noisy Kitty", 2011, "Me", lives=1) >>> my_cat.talk() Meow! Meow! >>> my_cat.name 'Noisy Kitty' >>> my_cat.lose_life() >>> my_cat.lose_life() 'Cat is dead x_x' """! Predict what Python will display when the following lines are typed into the interpreter: >>> print _____ In lecture, we learned about the special "underscore" methods for classes, two of which were __len__, which allows you to call the builtin function len on the object, and __getitem__, which allows you to use index notation on the object. Implement both of them for the Rlist class. Afterwards, the doctests for the Rlist class should pass. class Rlist(object): """A mutable rlist class. >>> r = Rlist(3, Rlist(2, Rlist(1))) >>> len(r) 3 >>> len(r.rest) 2 >>> r[0] 3 >>> r[1] 2 """ # previous stuff here def __len__(self): "*** YOUR CODE HERE ***" def __getitem__(self, index): "*** YOUR CODE HERE ***" When we write recursive functions acting on rlists, we often find that they have the following form: def func(rlist): if rlist == Rlist.empty: return <Base case> else: return <Expression involving func(rlist.rest)> In the spirit of abstraction, we want to factor out this commonly seen pattern. It turns out that we can define an abstraction called fold that do this. a starting value. are a way we have of representing a hierarchy of information. A family tree is a good example of something with a tree structure. You have a matriarch and a patriarch followed by all the descendants. Alternately, we may want to organize a series of information geographically. At the very top, we have the world, but below that we have countries, then states, then cities. We can also decompose arithmetic operations into something much the same way. The name "tree" comes from the branching structure of the pictures, like real trees in nature except that they're drawn with the root at the top and the leaves at the bottom. trees ***"
https://inst.eecs.berkeley.edu/~cs61a/sp14/lab/lab06/lab06.php
CC-MAIN-2020-10
refinedweb
499
68.57
I'm a beginner student learning about functions and do not understand them fully. My assignment was to write a program that deals with temperature conversion. My program had to use 6 functions (1. Program overview 2. Enter temp 3. Enter scale 4. Convert F to C 5. Convert C to F 6. Display results) It also needs to display an error message if an inappropriate input is entered for both scale (which I have) and temperature (which I do not know where to place). Appropriate values for temps are >= -459.67 F or -273.15 C. I do not know where to place this scale either. I also have multiple errors in my program. If anyone could give me any guidance in helping me to fix my program, I would greatly appreciate it!! Code:#include <iostream> using namespace std; void programOverview (); char getScale (); int getDegree (); float convertFtoC (float); float convertCtoF (float); int getResults (); int main () { cout.precision (2); programOverview (); getDegree (); getScale(); { if (scale == "F") { convertFtoC(); } else if (scale == "C") { convertCtoF(); } else cout << "ERROR: Invalid temperature scale" << endl; } getResults(); return 0; } //This function displays a brief overview explaining the program to the user void programOverview () { cout << "This program will convert a temperature reading provided in" << endl; cout << "either Fahrenheit or Celsius to the other measurement scale." << endl; } //This function requires the user to enter the temperature scale to be used char getScale () { char scale; cout << "Enter the letter of the temperature scale that will be used:" << endl; cout << "F = Fahrenheit; C = Celsius)" << endl; cin >> scale >> endl; return scale; } //This function requires the user to enter the temperature reading in degrees int getDegree () { int degree; cout << "Enter your temperature reading in degrees:" << endl; cin >> degree; return degree; } //This function converts a Fahrenheit temperature to Celsius float convertFtoC (float Ftemp) { float Ctemp; Ctemp = (Ftemp - 32) / 1.8; return Ctemp; } //This function converts a Celsius temperature to Fahrenheit float convertCtoF (float Ctemp) { float Ftemp; Ftemp = 1.8 * Ctemp + 32; return Ftemp; } //This function displays the results { int getResults () cout << "Your temperature reading converts as follows:" << endl; cout << "Fahrenheit:" << return Ftemp << endl; cout << "Celsius:" << return Ctemp << endl; }
https://cboard.cprogramming.com/cplusplus-programming/136435-temperature-conversion-program.html
CC-MAIN-2017-47
refinedweb
353
61.46
Applies to: General Topics Information in this article applies to: I am using the ORDER compiler directive in my source code and I have declared several variables that I wish to place in memory in the same order. When I examine the symbol table in the map file, they are not kept in the same order that I declared them in. Why? The order is not necessarily taken from the variable declarations, but the first use of the variables. For example, in the following files: extern unsigned char foo; extern unsigned int bar; #include "header.h" unsigned int bar; unsigned char foo; foo is stored in memory first followed by bar. This is because the foo variable is referenced first (by the extern declaration). Make sure that in all declarations and externs your variables are declared in the order you require. An alternative solution is to delare a structure containing the variables you wish to keep in order. This behaviour is changed in C166 Version 4.05 and later to take the variable order from the variable declarations. You may download the latest updates from the Keil Website. Request the files attached to this knowledgebase article. Article last edited on: 2005-07-15 12:47:03 Did you find this article helpful? Yes No How can we improve this article?
http://infocenter.arm.com/help/topic/com.arm.doc.faqs/ka9428.html
CC-MAIN-2017-30
refinedweb
220
64.41
Dart Programming - Quick Guide Dart Programming - Overview Dart is an object-oriented language with C-style syntax which can optionally trans compile into JavaScript. It supports a varied range of programming aids like interfaces, classes, collections, generics, and optional typing. Dart can be extensively used to create single-page applications. Single-page applications apply only to websites and web applications. Single-page applications enable navigation between different screens of the website without loading a different webpage in the browser. A classic example is GMail ─ when you click on a message in your inbox, browser stays on the same webpage, but JavaScript code hides the inbox and brings the message body on screen. Google has released a special build of Chromium – the Dart VM. Using Dartium means you don’t have to compile your code to JavaScript until you’re ready to test on other browsers. The following table compares the features of Dart and JavaScript. This tutorial provides a basic level understanding of the Dart programming language. Dart Programming - Environment This chapter discusses setting up the execution environment for Dart on the Windows platform. Executing Script Online with DartPad You may test your scripts online by using the online editor at. The Dart Editor executes the script and displays both HTML as well as console output. The online editor is shipped with a set of preset code samples. A screenshot of the Dartpad editor is given below − Dartpad also enables to code in a more restrictive fashion. This can be achieved by checking the Strong mode option on the bottom right of the editor. Strong mode helps with − - Stronger static and dynamic checking - Idiomatic JavaScript code generation for better interoperability. You may try the following example using DartpadLive Demo void main() { print('hello world'); } The code will display the following output hello world Setting Up the Local Environment In this section, let us see how to set up the local environment. Using the Text Editor Examples of a few editors include Windows Notepad, Notepad++, Emacs, vim or vi, etc. Editors may vary from one Operating System to another. The source files are typically named with the extension ".dart". Installing the Dart SDK The current stable version of Dart is 1.21.0. The dart sdk can be downloaded from − A screenshot of the Dart SDK installation is given below − On completion of the SDK installation, set the PATH environment variable to − <dart-sdk-path>\bin Verifying the Installation To verify if Dart has been successfully installed, open the command prompt and enter the following command − Dart If installation is successful, it will show the dart runtime. IDE Support A plethora of IDEs support scripting in Dart. Examples include Eclipse, IntelliJ, and WebStorm from Jet brains. Given below are the steps for configuring the Dart environment using WebStrom IDE. Installing WebStorm The installation file for WebStorm can be downloaded from. The WebStorm installation file is available for Mac OS, Windows and Linux. After downloading the installation files, follow the steps given below − Install the Dart SDK: Refer to the steps listed above Create a new Dart project and configure Dart support To create a new Dart project, Click Create New Project from the Welcome Screen In the next dialog box, click Dart If there is no value specified for the Dart SDK path, then provide the SDK path. For example, the SDK path may be <dart installation directory>/dart/dartsdk. Add a Dart File to the Project To add a Dart file to the Project − - Right-click on the Project - New → Dart File - Enter the name of the Dart Script A screenshot of the WebStorm Editor is given below − The dart2js Tool The dart2js tool compiles Dart code to JavaScript. Compiling Dart code to JS enables running the Dart script on browsers that do not support the Dart VM. The dart2js tool is shipped as a part of the Dart SDK and can be found in the /dartsdk/bin folder. To compile Dart to JavaScript, type the following command in the terminal dart2js - - out = <output_file>.js <dart_script>.dart This command produces a file that contains the JavaScript equivalent of your Dart code. A complete tutorial on using this utility can be found on the official Dart website. Dart Programming - Syntax Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A Dart program is composed of − - Variables and Operators - Classes - Functions - Expressions and Programming Constructs - Decision Making and Looping Constructs - Libraries and Packages - Typedefs - Data structures represented as Collections / Generics Your First Dart Code Let us start with the traditional “Hello World” example −Live Demo main() { print("Hello World!"); } The main() function is a predefined method in Dart. This method acts as the entry point to the application. A Dart script needs the main() method for execution. print() is a predefined function that prints the specified string or value to the standard output i.e. the terminal. The output of the above code will be − Hello World! Execute a Dart Program You can execute a Dart program in two ways − - Via the terminal - Via the WebStorm IDE Via the Terminal To execute a Dart program via the terminal − - Navigate to the path of the current project - Type the following command in the Terminal window dart file_name.dart Via the WebStorm IDE To execute a Dart program via the WebStorm IDE − Right-click the Dart script file on the IDE. (The file should contain the main() function to enable execution) Click on the ‘Run <file_name>’ option. A screenshot of the same is given below − One can alternatively click the button or use the shortcut Ctrl+Shift+F10 to execute the Dart Script. Dart Command-Line Options Dart command-line options are used to modify Dart Script execution. Common commandline options for Dart include the following − Enabling Checked Mode Dart programs run in two modes namely − - Checked Mode - Production Mode (Default) It is recommended to run the Dart VM in checked mode during development and testing, since it adds warnings and errors to aid development and debugging process. The checked mode enforces various checks like type-checking etc. To turn on the checked mode, add the -c or –-checked option before the script-file name while running the script. However, to ensure performance benefit while running the script, it is recommended to run the script in the production mode. Consider the following Test.dart script file −Live Demo void main() { int n = "hello"; print(n); } Run the script by entering − dart Test.dart Though there is a type-mismatch the script executes successfully as the checked mode is turned off. The script will result in the following output − hello Now try executing the script with the "- - checked" or the "-c" option − dart -c Test.dart Or, dart - - checked Test.dart The Dart VM will throw an error stating that there is a type mismatch. Unhandled exception: type 'String' is not a subtype of type 'int' of 'n' where String is from dart:core int is from dart:core #0 main () #1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart :261) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Identifiers in Dart Identifiers tables lists a few examples of valid and invalid identifiers − Keywords in Dart Keywords have a special meaning in the context of a language. The following table lists some keywords in Dart. Whitespace and Line Breaks Dart ignores spaces, tabs, and newlines that appear in programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand. Dart is Case-sensitive Dart is case-sensitive. This means that Dart differentiates between uppercase and lowercase characters. Statements end with a Semicolon Each line of instruction is called a statement. Each dart statement must end with a semicolon (;). A single line can contain multiple statements. However, these statements must be separated by a semicolon. Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct etc. Comments are ignored by the compiler. Dart supports the following types of comments − Single-line comments ( // ) − Any text between a "//" and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Example // this is single line comment /* This is a Multi-line comment */ Object-Oriented Programming in Dart Dart is an Object-Oriented language. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. Object − An object is a real-time representation of any entity. As per Grady Brooch, every object must have three. Example: Dart and Object OrientationLive Demo class TestClass { void disp() { print("Hello World"); } } void main() { TestClass c = new TestClass(); c.disp(); } The above example defines a class TestClass. The class has a method disp(). The method prints the string “Hello World” on the terminal. The new keyword creates an object of the class. The object invokes the method disp(). The code should produce the following output − Hello World Dart Programming - Data Types One of the most fundamental characteristics of a programming language is the set of data types it supports. These are the type of values that can be represented and manipulated in a programming language. The Dart language supports the following types− - Numbers - Strings - Booleans - Lists - Maps Numbers Numbers in Dart are used to represent numeric literals. The Number Dart come in two flavours − Integer − Integer values represent non-fractional values, i.e., numeric values without a decimal point. For example, the value "10" is an integer. Integer literals are represented using the int keyword. Double − Dart also supports fractional numeric values i.e. values with decimal points. The Double data type in Dart represents a 64-bit (double-precision) floating-point number. For example, the value "10.10". The keyword double is used to represent floating point literals. Strings Strings represent a sequence of characters. For instance, if you were to store some data like name, address etc. the string data type should be used. A Dart string is a sequence of UTF-16 code units. Runes are used to represent a sequence of UTF-32 code units. The keyword String is used to represent string literals. String values are embedded in either single or double quotes. Boolean The Boolean data type represents Boolean values true and false. Dart uses the bool keyword to represent a Boolean value. List and Map The data types list and map are used to represent a collection of objects. A List is an ordered group of objects. The List data type in Dart is synonymous to the concept of an array in other programming languages. The Map data type represents a set of values as key-value pairs. The dart: core library enables creation and manipulation of these collections through the predefined List and Map classes respectively. The Dynamic Type Dart is an optionally typed language. If the type of a variable is not explicitly specified, the variable’s type is dynamic. The dynamic keyword can also be used as a type annotation explicitly. Dart Programming - Variables A variable is “a named space in the memory” that stores values. In other words, it acts a container for values in a program. Variable names are called identifiers. Following are the naming rules for an identifier − Identifiers cannot be keywords. Identifiers can contain alphabets and numbers. Identifiers cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign. Variable names cannot begin with a number. Type Syntax A variable must be declared before it is used. Dart uses the var keyword to achieve the same. The syntax for declaring a variable is as given below − var name = 'Smith'; All variables in dart store a reference to the value rather than containing the value. The variable called name contains a reference to a String object with a value of “Smith”. Dart supports type-checking by prefixing the variable name with the data type. Type-checking ensures that a variable holds only data specific to a data type. The syntax for the same is given below − String name = 'Smith'; int num = 10; Consider the following example − void main() { String name = 1; } The above snippet will result in a warning since the value assigned to the variable doesn’t match the variable’s data type. Output Warning: A value of type 'String' cannot be assigned to a variable of type 'int' All uninitialized variables have an initial value of null. This is because Dart considers all values as objects. The following example illustrates the same −Live Demo void main() { int num; print(num); } Output Null The dynamic keyword Variables declared without a static type are implicitly declared as dynamic. Variables can be also declared using the dynamic keyword in place of the var keyword. The following example illustrates the same.Live Demo void main() { dynamic x = "tom"; print(x); } Output tom Final and Const The final and const keyword are used to declare constants. Dart prevents modifying the values of a variable declared using the final or const keyword. These keywords can be used in conjunction with the variable’s data type or instead of the var keyword. The const keyword is used to represent a compile-time constant. Variables declared using the const keyword are implicitly final. Syntax: final Keyword final variable_name OR final data_type variable_name Syntax: const Keyword const variable_name OR const data_type variable_name Example – final KeywordLive Demo void main() { final val1 = 12; print(val1); } Output 12 Example – const Keyword void main() { const pi = 3.14; const area = pi*12*12; print("The output is ${area}"); } The above example declares two constants, pi and area, using the const keyword. The area variable’s value is a compile-time constant. Output The output is 452.15999999999997 Note − Only const variables can be used to compute a compile time constant. Compile-time constants are constants whose values will be determined at compile time Example Dart throws an exception if an attempt is made to modify variables declared with the final or const keyword. The example given below illustrates the same −Live Demo void main() { final v1 = 12; const v2 = 13; v2 = 12; } The code given above will throw the following error as output − Unhandled exception: cannot assign to final variable 'v2='. NoSuchMethodError: cannot assign to final variable 'v2=' #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:178) #1 main (file: Test.dart:5:3) #2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) #3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Dart Programming - Operators An expression is a special kind of statement that evaluates to a value. Every expression is composed of − Operands − Represents the data Operator − Defines how the operands will be processed to produce a value. Consider the following expression – "2 + 3". In this expression, 2 and 3 are operands and the symbol "+" (plus) is the operator. In this chapter, we will discuss the operators that are available in Dart. - Arithmetic Operators - Equality and Relational Operators - Type test Operators - Bitwise Operators - Assignment Operators - Logical Operators Arithmetic Operators The following table shows the arithmetic operators supported by Dart. Equality and Relational Operators Relational Operators tests or defines the kind of relationship between two entities. Relational operators return a Boolean value i.e. true/ false. Assume the value of A is 10 and B is 20. Type test Operators These operators are handy for checking types at runtime. Bitwise Operators The following table lists the bitwise operators available in Dart and their role − Assignment Operators The following table lists the assignment operators available in Dart. Note − Same logic applies to Bitwise operators, so they will become ≪=, ≫=, ≫=, ≫=, |= and ^=. Logical Operators Logical operators are used to combine two or more conditions. Logical operators return a Boolean value. Assume the value of variable A is 10 and B is 20. Conditional Expressions Dart has two operators that let you evaluate expressions that might otherwise require ifelse statements − condition ? expr1 : expr2 If condition is true, then the expression evaluates expr1 (and returns its value); otherwise, it evaluates and returns the value of expr2. expr1 ?? expr2 If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2 Example The following example shows how you can use conditional expression in Dart −Live Demo void main() { var a = 10; var res = a > 12 ? "value greater than 10":"value lesser than or equal to 10"; print(res); } It will produce the following output − value lesser than or equal to 10 Example Let’s take another example − void main() { var a = null; var b = 12; var res = a ?? b; print(res); } It will produce the following output − 12 Dart Programming - Loops At times, certain instructions require repeated execution. Loops are an ideal way to do the same. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration. The following figure illustrates the classification of loops − Let’s start the discussion with Definite Loops. A loop whose number of iterations are definite/fixed is termed as a definite loop. Moving on, let’s now discuss the indefinite loops. An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − Let us now move on and discuss the Loop Control Statements of Dart.. Example: Label with BreakLive Demo void main() { outerloop: // This is the label name for (var i = 0; i < 5; i++) { print("Innerloop: ${i}"); innerloop: for (var j = 0; j < 5; j++) { if (j > 3 ) break ; // Quit the innermost loop if (i == 2) break innerloop; // Do the same thing if (i == 4) break outerloop; // Quit the outer loop print("Innerloop: ${j}"); } } } The following output is displayed on successful execution of the above code. Innerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Innerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Innerloop: 2 Innerloop: 3 Innerloop: 0 Innerloop: 1 Innerloop: 2 Innerloop: 3 Innerloop: 4 Example: Label with continueLive Demo void main() { outerloop: // This is the label name for (var i = 0; i < 3; i++) { print("Outerloop:${i}"); for (var j = 0; j < 5; j++) { if (j == 3){ continue outerloop; } print("Innerloop:${j}"); } } } The following output is displayed on successful execution of the above code. Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 2 Innerloop: 0 Innerloop: 1 Innerloop: 2 Dart Programming - Decision Making A conditional/decision-making construct evaluates a condition before the instructions are executed. Conditional constructs in Dart are classified in the following table. Dart Programming - Numbers Dart numbers can be classified as − int − Integer of arbitrary size. The int data type is used to represent whole numbers. double − 64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard. The double data type is used to represent fractional numbers The num type is inherited by the int and double types. The dart core library allows numerous operations on numeric values. The syntax for declaring a number is as given below − int var_name; // declares an integer variable double var_name; // declares a double variable ExampleLive Demo void main() { int num1 = 10; // declare an integer double num2 = 10.50; // declare a double value print(num1); print(num2); } It will produce the following output − 10 10.5 Note − The Dart VM will throw an exception if fractional values are assigned to integer variables. Parsing The parse() static function allows parsing a string containing numeric literal into a number. The following illustration demonstrates the same −Live Demo void main() { print(num.parse('12')); print(num.parse('10.91')); } The above code will result in the following output − 12 10.91 The parse function throws a FormatException if it is passed any value other than numerals. The following code shows how to pass an alpha-numeric value to the parse() function. ExampleLive Demo void main() { print(num.parse('12A')); print(num.parse('AAAA')); } The above code will result in the following output − Unhandled exception: FormatException: 12A #0 num.parse (dart:core/num.dart:446) #1 main () #2 _startIsolate.<anonymous closure> (dart:isolatepatch/isolate_patch.dart:261) #3 _RawReceivePortImpl._handleMessage (dart:isolatepatch/isolate_patch.dart:148) Number Properties The following table lists the properties supported by Dart numbers. Number Methods Given below are a list of commonly used methods supported by numbers − Dart Programming - String The String data type represents a sequence of characters. A Dart string is a sequence of UTF 16 code units. String values in Dart can be represented using either single or double or triple quotes. Single line strings are represented using single or double quotes. Triple quotes are used to represent multi-line strings. The syntax of representing string values in Dart is as given below − Syntax String variable_name = 'value' OR String variable_name = ''value'' OR String variable_name = '''line1 line2''' OR String variable_name= ''''''line1 line2'''''' The following example illustrates the use of String data type in Dart.Live Demo void main() { String str1 = 'this is a single line string'; String str2 = "this is a single line string"; String str3 = '''this is a multiline line string'''; String str4 = """this is a multiline line string"""; print(str1); print(str2); print(str3); print(str4); } It will produce the following Output − this is a single line string this is a single line string this is a multiline line string this is a multiline line string Strings are immutable. However, strings can be subjected to various operations and the resultant string can be a stored as a new value. String Interpolation The process of creating a new string by appending a value to a static string is termed as concatenation or interpolation. In other words, it is the process of adding a string to another string. The operator plus (+) is a commonly used mechanism to concatenate / interpolate strings. Example 1Live Demo void main() { String str1 = "hello"; String str2 = "world"; String res = str1+str2; print("The concatenated string : ${res}"); } It will produce the following output − The concatenated string : Helloworld Example 2 You can use "${}" can be used to interpolate the value of a Dart expression within strings. The following example illustrates the same.Live Demo void main() { int n=1+1; String str1 = "The sum of 1 and 1 is ${n}"; print(str1); String str2 = "The sum of 2 and 2 is ${2+2}"; print(str2); } It will produce the following output − The sum of 1 and 1 is 2 The sum of 2 and 2 is 4 String Properties The properties listed in the following table are all read-only. Methods to Manipulate Strings The String class in the dart: core library also provides methods to manipulate strings. Some of these methods are given below − Dart Programming - Boolean Dart provides an inbuilt support for the Boolean data type. The Boolean data type in DART supports only two values – true and false. The keyword bool is used to represent a Boolean literal in DART. The syntax for declaring a Boolean variable in DART is as given below − bool var_name = true; OR bool var_name = false ExampleLive Demo void main() { bool test; test = 12 > 5; print(test); } It will produce the following output − true Example Unlike JavaScript, the Boolean data type recognizes only the literal true as true. Any other value is considered as false. Consider the following example − var str = 'abc'; if(str) { print('String is not empty'); } else { print('Empty String'); } The above snippet, if run in JavaScript, will print the message ‘String is not empty’ as the if construct will return true if the string is not empty. However, in Dart, str is converted to false as str != true. Hence the snippet will print the message ‘Empty String’ (when run in unchecked mode). Example The above snippet if run in checked mode will throw an exception. The same is illustrated below −Live Demo void main() { var str = 'abc'; if(str) { print('String is not empty'); } else { print('Empty String'); } } It will produce the following output, in Checked Mode − Unhandled exception: type 'String' is not a subtype of type 'bool' of 'boolean expression' where String is from dart:core bool is from dart:core #0 main () #1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) #2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) It will produce the following output, in Unchecked Mode − Empty String Note − The WebStorm IDE runs in checked mode, by default. Dart. Dart Programming - Lists (Basic Operations) In this chapter, we will discuss how to carry out some basic operations on Lists, such as − Dart Programming - Map The Map object is a simple key/value pair. Keys and values in a map may be of any type. A Map is a dynamic collection. In other words, Maps can grow and shrink at runtime. Maps can be declared in two ways − - Using Map Literals - Using a Map constructor Declaring a Map using Map Literals To declare a map using map literals, you need to enclose the key-value pairs within a pair of curly brackets "{ }". Here is its syntax − var identifier = { key1:value1, key2:value2 [,…..,key_n:value_n] } Declaring a Map using a Map Constructor To declare a Map using a Map constructor, we have two steps. First, declare the map and second, initialize the map. The syntax to declare a map is as follows − var identifier = new Map() Now, use the following syntax to initialize the map − map_name[key] = value Example: Map LiteralLive Demo void main() { var details = {'Usrname':'tom','Password':'pass@123'}; print(details); } It will produce the following output − {Usrname: tom, Password: pass@123} Example: Adding Values to Map Literals at RuntimeLive Demo void main() { var details = {'Usrname':'tom','Password':'pass@123'}; details['Uid'] = 'U1oo1'; print(details); } It will produce the following output − {Usrname: tom, Password: pass@123, Uid: U1oo1} Example: Map ConstructorLive Demo void main() { var details = new Map(); details['Usrname'] = 'admin'; details['Password'] = 'admin@123'; print(details); } It will produce the following output − {Usrname: admin, Password: admin@123} Note − A map value can be any object including NULL. Map – Properties The Map class in the dart:core package defines the following properties − Map - Functions Following are the commonly used functions for manipulating Maps in Dart. Dart Programming - Symbol Symbols in Dart are opaque, dynamic string name used in reflecting out metadata from a library. Simply put, symbols are a way to store the relationship between a human readable string and a string that is optimized to be used by computers. Reflection is a mechanism to get metadata of a type at runtime like the number of methods in a class, the number of constructors it has or the number of parameters in a function. You can even invoke a method of the type which is loaded at runtime. In Dart reflection specific classes are available in the dart:mirrors package. This library works in both web applications and command line applications. Syntax Symbol obj = new Symbol('name'); // expects a name of class or function or library to reflect The name must be a valid public Dart member name, public constructor name, or library name. Example Consider the following example. The code declares a class Foo in a library foo_lib. The class defines the methods m1, m2, and m3. Foo.dart library foo_lib; // libarary name can be a symbol class Foo { // class name can be a symbol m1() { // method name can be a symbol print("Inside m1"); } m2() { print("Inside m2"); } m3() { print("Inside m3"); } } The following code loads Foo.dart library and searches for Foo class, with help of Symbol type. Since we are reflecting the metadata from the above library the code imports dart:mirrors library. FooSymbol.dart import 'dart:core'; import 'dart:mirrors'; import 'Foo.dart'; main() { Symbol lib = new Symbol("foo_lib"); //library name stored as Symbol Symbol clsToSearch = new Symbol("Foo"); // class name stored as Symbol if(checkIf_classAvailableInlibrary(lib, clsToSearch)) // searches Foo class in foo_lib library print("class found.."); } bool checkIf_classAvailableInlibrary)) return true; return false; } } Note that the line libMirror.declarations.forEach((s, d) => print(s)); will iterate across every declaration in the library at runtime and prints the declarations as type of Symbol. This code should produce the following output − Found Library checkng...class details.. No of classes found is : 1 Symbol("Foo") // class name displayed as symbol class found. Example: Display the number of instance methods of a class Let us now consider displaying the number of instance methods in a class. The predefined class ClassMirror helps us to achieve the same. import 'dart:core'; import 'dart:mirrors'; import 'Foo.dart'; main() { Symbol lib = new Symbol("foo_lib"); Symbol clsToSearch = new Symbol("Foo"); reflect_InstanceMethods(lib, clsToSearch); } void reflect_InstanceMethods)) print("found class"); ClassMirror classMirror = libMirror.declarations[className]; print("No of instance methods found is ${classMirror.instanceMembers.length}"); classMirror.instanceMembers.forEach((s, v) => print(s)); } } This code should produce the following output − Found Library checkng...class details.. No of classes found is : 1 Symbol("Foo") found class No of instance methods found is 8 Symbol("==") Symbol("hashCode") Symbol("toString") Symbol("noSuchMethod") Symbol("runtimeType") Symbol("m1") Symbol("m2") Symbol("m3") Convert Symbol to String You can convert the name of a type like class or library stored in a symbol back to string using MirrorSystem class. The following code shows how you can convert a symbol to a string.Live Demo import 'dart:mirrors'; void main(){ Symbol lib = new Symbol("foo_lib"); String name_of_lib = MirrorSystem.getName(lib); print(lib); print(name_of_lib); } It should produce the following output − Symbol("foo_lib") foo_lib Dart Programming - Runes Strings are a sequence of characters. Dart represents strings as a sequence of Unicode UTF-16 code units. Unicode is a format that defines a unique numeric value for each letter, digit, and symbol. Since a Dart string is a sequence of UTF-16 code units, 32-bit Unicode values within a string are represented using a special syntax. A rune is an integer representing a Unicode code point. The String class in the dart:core library provides mechanisms to access runes. String code units / runes can be accessed in three ways − - Using String.codeUnitAt() function - Using String.codeUnits property - Using String.runes property String.codeUnitAt() Function Code units in a string can be accessed through their indexes. Returns the 16-bit UTF-16 code unit at the given index. Syntax String.codeUnitAt(int index); ExampleLive Demo import 'dart:core'; void main(){ f1(); } f1() { String x = 'Runes'; print(x.codeUnitAt(0)); } It will produce the following output − 82 String.codeUnits Property This property returns an unmodifiable list of the UTF-16 code units of the specified string. Syntax String. codeUnits; ExampleLive Demo import 'dart:core'; void main(){ f1(); } f1() { String x = 'Runes'; print(x.codeUnits); } It will produce the following output − [82, 117, 110, 101, 115] String.runes Property This property returns an iterable of Unicode code-points of this string.Runes extends iterable. Syntax String.runes ExampleLive Demo void main(){ "A string".runes.forEach((int rune) { var character=new String.fromCharCode(rune); print(character); }); } It will produce the following output − A s t r i n g Unicode code points are usually expressed as \uXXXX, where XXXX is a 4-digit hexadecimal value. To specify more or less than 4 hex digits, place the value in curly brackets. One can use the constructor of the Runes class in the dart:core library for the same. ExampleLive Demo main() { Runes input = new Runes(' \u{1f605} '); print(new String.fromCharCodes(input)); } It will produce the following output − Dart Programming - Enumeration An enumeration is used for defining named constant values. An enumerated type is declared using the enum keyword. Syntax Status { none, running, stopped, paused } ExampleLive Demo enum Status { none, running, stopped, paused } void main() { print(Status.values); Status.values.forEach((v) => print('value: $v, index: ${v.index}')); print('running: ${Status.running}, ${Status.running.index}'); print('running index: ${Status.values[1]}'); } It will produce the following output − [Status.none, Status.running, Status.stopped, Status.paused] value: Status.none, index: 0 value: Status.running, index: 1 value: Status.stopped, index: 2 value: Status.paused, index: 3 running: Status.running, 1 running index: Status.running Dart Programming - Functions. Optional Parameters Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution. A parameter can be marked optional by appending a question mark to its name. The optional parameter should be set as the last argument in a function. We have three types of optional parameters in Dart − Recursive Dart Functions Recursion is a technique for iterating over an operation by having a function call to itself repeatedly until it arrives at a result. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop. ExampleLive Demo void main() { print(factorial(6)); } factorial(number) { if (number <= 0) { // termination case return 1; } else { return (number * factorial(number - 1)); // function invokes itself } } It should produce the following output − 720 Lambda Functions Lambda functions are a concise mechanism to represent functions. These functions are also called as Arrow functions. Syntax [return_type]function_name(parameters)=>expression; ExampleLive Demo void main() { printMsg(); print(test()); } printMsg()=> print("hello"); int test()=>123; // returning function It should produce the following output − hello 123 Dart Programming - Interfaces An interface defines the syntax that any entity must adhere to. Interfaces define a set of methods available on an object. Dart does not have a syntax for declaring interfaces. Class declarations are themselves interfaces in Dart. Classes should use the implements keyword to be able to use an interface. It is mandatory for the implementing class to provide a concrete implementation of all the functions of the implemented interface. In other words, a class must redefine every function in the interface it wishes to implement. Syntax: Implementing an Interface class identifier implements interface_name Example In the following program, we are declaring a class Printer. The ConsolePrinter class implements the implicit interface declaration for the Printer class. The main function creates an object of the ConsolePrinter class using the new keyword. This object is used to invoke the function print_data defined in the ConsolePrinter class.Live Demo void main() { ConsolePrinter cp= new ConsolePrinter(); cp.print_data(); } class Printer { void print_data() { print("__________Printing Data__________"); } } class ConsolePrinter implements Printer { void print_data() { print("__________Printing to Console__________"); } } It should produce the following output − __________Printing to Console__________ Implementing Multiple Interfaces A class can implement multiple interfaces. The interfaces are separated by a comma. The syntax for the same is given below − class identifier implements interface-1,interface_2,interface_4……. The following example shows how you can implement multiple interfaces in Dart −Live Demo void main() { Calculator c = new Calculator(); print("The gross total : ${c.ret_tot()}"); print("Discount :${c.ret_dis()}"); } class Calculate_Total { int ret_tot() {} } class Calculate_Discount { int ret_dis() {} } class Calculator implements Calculate_Total,Calculate_Discount { int ret_tot() { return 1000; } int ret_dis() { return 50; } } It should produce the following output − The gross total: 1000 Discount:50 Dart Programming - Classes Dart is an object-oriented language. It supports object-oriented programming features like classes, interfaces, etc. A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object. Dart gives built-in support for this concept called class. Declaring a Class Use the class keyword to declare a class in Dart. A class definition starts with the keyword class followed by the class name; and the class body enclosed by a pair of curly braces. The syntax for the same is given below − Syntax class class_name { <fields> <getters/setters> <constructors> <functions> } The class keyword is followed by the class name. The rules for identifiers must be considered while naming a class. A class definition can include the following − Fields. Functions − Functions represent actions an object can take. They are also at times referred to as methods. These components put together are termed as the data members of the class. Example: Declaring a class class Car { // field String engine = "E1001"; // function void disp() { print(engine); } } The example declares a class Car. The class has a field named engine. The disp() is a simple function that prints the value of the field engine. Creating Instance of the class To create an instance of the class, use the new keyword. Example: Instantiating a class var obj = new Car("Engine 1") Accessing Attributes and Functions A class’s attributes and functions can be accessed through the object. Use the ‘.’ dot notation (called as the period) to access the data members of a class. //accessing an attribute obj.field_name //accessing a function obj.function_name() Example Take a look at the following example to understand how to access attributes and functions in Dart −Live Demo void main() { Car c= new Car(); c.disp(); } class Car { // field String engine = "E1001"; // function void disp() { print(engine); } } The output of the above code is as follows − E1001 Dart Constructors A constructor is a special function of the class that is responsible for initializing the variables of the class. Dart defines a constructor with the same name as that of the class. A constructor is a function and hence can be parameterized. However, unlike a function, constructors cannot have a return type. If you don’t declare a constructor, a default no-argument constructor is provided for you. Syntax Class_name(parameter_list) { //constructor body } Example The following example shows how to use constructors in Dart −Live Demo void main() { Car c = new Car('E1001'); } class Car { Car(String engine) { print(engine); } } It should produce the following output − E1001 Named Constructors Dart provides named constructors to enable a class define multiple constructors. The syntax of named constructors is as given below − Syntax : Defining the constructor Class_name.constructor_name(param_list) Example The following example shows how you can use named constructors in Dart −Live Demo void main() { Car c1 = new Car.namedConst('E1001'); Car c2 = new Car(); } class Car { Car() { print("Non-parameterized constructor invoked"); } Car.namedConst(String engine) { print("The engine is : ${engine}"); } } It should produce the following output − The engine is : E1001 Non-parameterized constructor invoked The this Keyword The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class’s field are the same. Hence to avoid ambiguity, the class’s field is prefixed with the this keyword. The following example explains the same − Example The following example explains how to use the this keyword in Dart −Live Demo void main() { Car c1 = new Car('E1001'); } class Car { String engine; Car(String engine) { this.engine = engine; print("The engine is : ${engine}"); } } It should produce the following output − The engine is : E1001 Dart Class ─ Getters and Setters Getters and Setters, also called as accessors and mutators, allow the program to initialize and retrieve the values of class fields respectively. Getters or accessors are defined using the get keyword. Setters or mutators are defined using the set keyword. A default getter/setter is associated with every class. However, the default ones can be overridden by explicitly defining a setter/ getter. A getter has no parameters and returns a value, and the setter has one parameter and does not return a value. Syntax: Defining a getter Return_type get identifier { } Syntax: Defining a setter set identifier { } Example The following example shows how you can use getters and setters in a Dart class −Live Demo class Student { String name; int age; String get stud_name { return name; } void set stud_name(String name) { this.name = name; } void set stud_age(int age) { if(age<= 0) { print("Age should be greater than 5"); } else { this.age = age; } } int get stud_age { return age; } } void main() { Student s1 = new Student(); s1.stud_name = 'MARK'; s1.stud_age = 0; print(s1.stud_name); print(s1.stud_age); } This program code should produce the following output − Age should be greater than 5 MARK Null Class Inheritance Dart supports the concept of Inheritance which is the ability of a program to create new classes from an existing. Syntax class child_class_name extends parent_class_name Note − Dart doesn’t support multiple inheritance. Example: Class Inheritance In the following example, we are declaring a class Shape. The class is extended by the Circle class. Since there is an inheritance relationship between the classes, the child class, i.e., the class Car gets an implicit access to its parent class data member.Live Demo void main() { var obj = new Circle(); obj.cal_area(); } class Shape { void cal_area() { print("calling calc area defined in the Shape class"); } } class Circle extends Shape {} It should produce the following output − calling calc area defined in the Shape class Types of Inheritance Inheritance can be of the following three types − Single − Every class can at the most extend from one parent class. Multiple − A class can inherit from multiple classes. Dart doesn’t support multiple inheritance. Multi-level − A class can inherit from another child class. Example The following example shows how multi-level inheritance works −Live Demo void main() { var obj = new Leaf(); obj.str = "hello"; print(obj.str); } class Root { String str; } class Child extends Root {} class Leaf extends Child {} //indirectly inherits from Root by virtue of inheritance The class Leaf derives the attributes from Root and Child classes by virtue of multi-level inheritance. Its output is as follows − hello Dart – Class Inheritance and Method Overriding Method Overriding is a mechanism by which the child class redefines a method in its parent class. The following example illustrates the same − ExampleLive Demo void main() { Child c = new Child(); c.m1(12); } class Parent { void m1(int a){ print("value of a ${a}");} } class Child extends Parent { @override void m1(int b) { print("value of b ${b}"); } } It should produce the following output − value of b 12 The number and type of the function parameters must match while overriding the method. In case of a mismatch in the number of parameters or their data type, the Dart compiler throws an error. The following illustration explains the same −Live Demo import 'dart:io'; void main() { Child c = new Child(); c.m1(12); } class Parent { void m1(int a){ print("value of a ${a}");} } class Child extends Parent { @override void m1(String b) { print("value of b ${b}"); } } It should produce the following output − value of b 12 The static Keyword The static keyword can be applied to the data members of a class, i.e., fields and methods. A static variable retains its values till the program finishes execution. Static members are referenced by the class name. ExampleLive Demo class StaticMem { static int num; static disp() { print("The value of num is ${StaticMem.num}") ; } } void main() { StaticMem.num = 12; // initialize the static variable } StaticMem.disp(); // invoke the static method } It should produce the following output − The value of num is 12 The super Keyword The super keyword is used to refer to the immediate parent of a class. The keyword can be used to refer to the super class version of a variable, property, or method. The following example illustrates the same − ExampleLive Demo void main() { Child c = new Child(); c.m1(12); } class Parent { String msg = "message variable from the parent class"; void m1(int a){ print("value of a ${a}");} } class Child extends Parent { @override void m1(int b) { print("value of b ${b}"); super.m1(13); print("${super.msg}") ; } } It should produce the following output − value of b 12 value of a 13 message variable from the parent class Dart Programming - Object Object-Oriented Programming defines an object as “any entity that has a defined boundary.” An object has the following − State − Describes the object. The fields of a class represent the object’s state. Behavior − Describes what an object can do. Identity − A unique value that distinguishes an object from a set of similar other objects. Two or more objects can share the state and behavior but not the identity. The period operator (.) is used in conjunction with the object to access a class’ data members. Example Dart represents data in the form of objects. Every class in Dart extends the Object class. Given below is a simple example of creating and using an object.Live Demo class Student { void test_method() { print("This is a test method"); } void test_method1() { print("This is a test method1"); } } void main() { Student s1 = new Student(); s1.test_method(); s1.test_method1(); } It should produce the following output − This is a test method This is a test method1 The Cascade operator (..) The above example invokes the methods in the class. However, every time a function is called, a reference to the object is required. The cascade operator can be used as a shorthand in cases where there is a sequence of invocations. The cascade ( .. ) operator can be used to issue a sequence of calls via an object. The above example can be rewritten in the following manner.Live Demo class Student { void test_method() { print("This is a test method"); } void test_method1() { print("This is a test method1"); } } void main() { new Student() ..test_method() ..test_method1(); } It should produce the following output − This is a test method This is a test method1 The toString() method This function returns a string representation of an object. Take a look at the following example to understand how to use the toString method.Live Demo void main() { int n = 12; print(n.toString()); } It should produce the following output − 12 Dart Dart Programming - Generics Dart is an optionally typed language. Collections in Dart are heterogeneous by default. In other words, a single Dart collection can host values of various types. However, a Dart collection can be made to hold homogenous values. The concept of Generics can be used to achieve the same. The use of Generics enforces a restriction on the data type of the values that can be contained by the collection. Such collections are termed as type-safe collections. Type safety is a programming feature which ensures that a memory block can only contain data of a specific data type. All Dart collections support type-safety implementation via generics. A pair of angular brackets containing the data type is used to declare a type-safe collection. The syntax for declaring a type-safe collection is as given below. Syntax Collection_name <data_type> identifier= new Collection_name<data_type> The type-safe implementations of List, Map, Set and Queue is given below. This feature is also supported by all implementations of the above-mentioned collection types. Example: Generic ListLive Demo void main() { List <String> logTypes = new List <String>(); logTypes.add("WARNING"); logTypes.add("ERROR"); logTypes.add("INFO"); // iterating across list for (String type in logTypes) { print(type); } } It should produce the following output − WARNING ERROR INFO An attempt to insert a value other than the specified type will result in a compilation error. The following example illustrates this. ExampleLive Demo void main() { List <String> logTypes = new List <String>(); logTypes.add(1); logTypes.add("ERROR"); logTypes.add("INFO"); //iterating across list for (String type in logTypes) { print(type); } } It should produce the following output − 1 ERROR INFO Example: Generic SetLive Demo void main() { Set <int>numberSet = new Set<int>(); numberSet.add(100); numberSet.add(20); numberSet.add(5); numberSet.add(60); numberSet.add(70); // numberSet.add("Tom"); compilation error; print("Default implementation :${numberSet.runtimeType}"); for(var no in numberSet) { print(no); } } It should produce the following output − Default implementation :_CompactLinkedHashSet<int> 100 20 5 60 70 Example: Generic QueueLive Demo import 'dart:collection'; void main() { Queue<int> queue = new Queue<int>(); print("Default implementation ${queue.runtimeType}"); queue.addLast(10); queue.addLast(20); queue.addLast(30); queue.addLast(40); queue.removeFirst(); for(int no in queue){ print(no); } } It should produce the following output − Default implementation ListQueue<int> 20 30 40 Generic Map A type-safe map declaration specifies the data types of − - The key - The value Syntax Map <Key_type, value_type> ExampleLive Demo void main() { Map <String,String>m={'name':'Tom','Id':'E1001'}; print('Map :${m}'); } It should produce the following output − Map :{name: Tom, Id: E1001} Dart Programming - Packages A package is a mechanism to encapsulate a group of programming units. Applications might at times need integration of some third-party libraries or plugins. Every language has a mechanism for managing external packages like Maven or Gradle for Java, Nuget for .NET, npm for Node.js, etc. The package manager for Dart is pub. Pub helps to install packages in the repository. The repository of packages hosted can be found at. The package metadata is defined in a file, pubsec.yaml. YAML is the acronym for Yet Another Markup Language. The pub tool can be used to download all various libraries that an application requires. Every Dart application has a pubspec.yaml file which contains the application dependencies to other libraries and metadata of applications like application name, author, version, and description. The contents of a pubspec.yaml file should look something like this − name: 'vector_victor' version: 0.0.1 description: An absolute bare-bones web app. ... dependencies: browser: '>=0.10.0 <0.11.0' The important pub commands are as follows − If you are using an IDE like WebStorm, then you can right-click on the pubspec.yaml to get all the commands directly − Installing a Package Consider an example where an application needs to parse xml. Dart XML is a lightweight library that is open source and stable for parsing, traversing, querying and building XML documents. The steps for achieving the said task is as follows − Step 1 − Add the following to the pubsec.yaml file. name: TestApp version: 0.0.1 description: A simple console application. #dependencies: # foo_bar: '>=1.0.0 <2.0.0' dependencies: xml: Right-click on the pubsec.yaml and get dependencies. This will internally fire the pub get command as shown below. The downloaded packages and its dependent packages can be verified under the packages folder. Since installation is completed now, we need to refer the dart xml in the project. The syntax is as follows − import 'package:xml/xml.dart' as xml; Read XML String To read XML string and verify the input, Dart XML uses a parse() method. The syntax is as follows − xml.parse(String input): Example : Parsing XML String Input The following example shows how to parse XML string input − import 'package:xml/xml.dart' as xml; void main(){ print("xml");); print(document.toString()); } It should produce the following output − xml <?xml version = "1.0"?><bookshelf> <book> <title lang = "english">Growing a Language</title> <price>29.99</price> </book> <book> <title lang = "english">Learning XML</title> <price>39.95</price> </book> <price>132.00</price> </bookshelf> Dart Programming - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally. Built-in Dart exceptions include − Every exception in Dart is a subtype of the pre-defined class Exception. Exceptions must be handled to prevent the application from terminating abruptly. The try / on / catch Blocks The try block embeds code that might possibly result in an exception. The on block is used when the exception type needs to be specified. The catch block is used when the handler needs the exception object. The try block must be followed by either exactly one on / catch block or one finally block (or one of both). When an exception occurs in the try block, the control is transferred to the catch. The syntax for handling an exception is as given below − try { // code that might throw an exception } on Exception1 { // code for handling exception } catch Exception2 { // code for handling exception } Following are some points to remember − A code snippet can have more than one on / catch blocks to handle multiple exceptions. The on block and the catch block are mutually inclusive, i.e. a try block can be associated with both- the on block and the catch block. The following code illustrates exception handling in Dart − Example: Using the ON Block The following program divides two numbers represented by the variables x and y respectively. The code throws an exception since it attempts division by zero. The on block contains the code to handle this exception.Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } } It should produce the following output − Cannot divide by zero Example: Using the catch Block In the following example, we have used the same code as above. The only difference is that the catch block (instead of the ON block) here contains the code to handle the exception. The parameter of catch contains the exception object thrown at runtime.Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } catch(e) { print(e); } } It should produce the following output − IntegerDivisionByZeroException Example: on…catch The following example shows how to use the on...catch block.Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException catch(e) { print(e); } } It should produce the following output − IntegerDivisionByZeroException The Finally Block The finally block includes code that should be executed irrespective of an exception’s occurrence. The optional finally block executes unconditionally after try/on/catch. The syntax for using the finally block is as follows − try { // code that might throw an exception } on Exception1 { // exception handling code } catch Exception2 { // exception handling } finally { // code that should always execute; irrespective of the exception } The following example illustrates the use of finally block.Live Demo main() { int x = 12; int y = 0; int res; try { res = x ~/ y; } on IntegerDivisionByZeroException { print('Cannot divide by zero'); } finally { print('Finally block executed'); } } It should produce the following output − Cannot divide by zero Finally block executed Throwing an Exception The throw keyword is used to explicitly raise an exception. A raised exception should be handled to prevent the program from exiting abruptly. The syntax for raising an exception explicitly is − throw new Exception_name() Example The following example shows how to use the throw keyword to throw an exception −Live Demo main() { try { test_age(-2); } catch(e) { print('Age cannot be negative'); } } void test_age(int age) { if(age<0) { throw new FormatException(); } } It should produce the following output − Age cannot be negative Custom Exceptions As specified above, every exception type in Dart is a subtype of the built-in class Exception. Dart enables creating custom exceptions by extending the existing ones. The syntax for defining a custom exception is as given below − Syntax: Defining the Exception class Custom_exception_Name implements Exception { // can contain constructors, variables and methods } Custom Exceptions should be raised explicitly and the same should be handled in the code. Example The following example shows how to define and handle a custom exception.Live Demo class AmtException implements Exception { String errMsg() => 'Amount should be greater than zero'; } void main() { try { withdraw_amt(-1); } catch(e) { print(e.errMsg()); } finally { print('Ending requested operation.....'); } } void withdraw_amt(int amt) { if (amt <= 0) { throw new AmtException(); } } In the above code, we are defining a custom exception, AmtException. The code raises the exception if the amount passed is not within the excepted range. The main function encloses the function invocation in the try...catch block. The code should produce the following output − Amount should be greater than zero Ending requested operation.... Dart_12<<. Dart Programming - Typedef A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function. Given below are the steps to implement typedefs in a Dart program. Step 1: Defining a typedef A typedef can be used to specify a function signature that we want specific functions to match. A function signature is defined by a function’s parameters (including their types). The return type is not a part of the function signature. Its syntax is as follows. typedef function_name(parameters) Step 2: Assigning a Function to a typedef Variable A variable of typedef can point to any function having the same signature as typedef. You can use the following signature to assign a function to a typedef variable. type_def var_name = function_name Step 3: Invoking a Function The typedef variable can be used to invoke functions. Here is how you can invoke a function − var_name(parameters) Example Let’s now take an example to understand more on typedef in Dart. At first, let us define a typedef. Here we are defining a function signature. The function will take two input parameters of the type integer. Return type is not a part of the function signature. typedef ManyOperation(int firstNo , int secondNo); //function signature Next, let us define the functions. Define some functions with the same function signature as that of the ManyOperation typedef. Add(int firstNo,int second){ print("Add result is ${firstNo+second}"); } Subtract(int firstNo,int second){ print("Subtract result is ${firstNo-second}"); } Divide(int firstNo,int second){ print("Add result is ${firstNo/second}"); } Finally, we will invoke the function via typedef. Declare a variable of the ManyOperations type. Assign the function name to the declared variable. ManyOperation oper ; //can point to any method of same signature oper = Add; oper(10,20); oper = Subtract; oper(30,20); oper = Divide; oper(50,5); The oper variable can point to any method which takes two integer parameters. The Add function's reference is assigned to the variable. Typedefs can switch function references at runtime Let us now put all the parts together and see the complete program.Live); } void main(){ ManyOperation oper = Add; oper(10,20); oper = Subtract; oper(30,20); oper = Divide; oper(50,5); } The program should produce the following output − Add result is 30 Subtract result is 10 Divide result is 10.0 Note − The above code will result in an error if the typedef variable tries to point to a function with a different function signature. Example Typedefs can also be passed as a parameter to a function. Consider the following example −Live); } main(){ Calculator(5,5,Add); Calculator(5,5,Subtract); Calculator(5,5,Divide); } It will produce the following output − Inside calculator Add result is 10 Inside calculator Subtract result is 0 Inside calculator Divide result is 1.0 Dart Programming - Libraries A library in a programming language represents a collection of routines (set of programming instructions). Dart has a set of built-in libraries that are useful to store routines that are frequently used. A Dart library comprises of a set of classes, constants, functions, typedefs, properties, and exceptions. Importing a library Importing makes the components in a library available to the caller code. The import keyword is used to achieve the same. A dart file can have multiple import statements. Built in Dart library URIs use the dart: scheme to refer to a library. Other libraries can use a file system path or the package: scheme to specify its URI. Libraries provided by a package manager such as the pub tool uses the package: scheme. The syntax for importing a library in Dart is given below − import 'URI' Consider the following code snippet − import 'dart:io' import 'package:lib1/libfile.dart' If you want to use only part of a library, you can selectively import the library. The syntax for the same is given below − import 'package: lib1/lib1.dart' show foo, bar; // Import only foo and bar. import 'package: mylib/mylib.dart' hide foo; // Import all names except foo Some commonly used libraries are given below − Example : Importing and using a Library The following example imports the built-in library dart: math. The snippet calls the sqrt() function from the math library. This function returns the square root of a number passed to it.Live Demo import 'dart:math'; void main() { print("Square root of 36 is: ${sqrt(36)}"); } Output Square root of 36 is: 6.0 Encapsulation in Libraries Dart scripts can prefix identifiers with an underscore ( _ ) to mark its components private. Simply put, Dart libraries can restrict access to its content by external scripts. This is termed as encapsulation. The syntax for the same is given below − Syntax _identifier Example At first, define a library with a private function.Live Demo library loggerlib; void _log(msg) { print("Log method called in loggerlib msg:$msg"); } Next, import the library import 'test.dart' as web; void main() { web._log("hello from webloggerlib"); } The above code will result in an error. Unhandled exception: No top-level method 'web._log' declared. NoSuchMethodError: method not found: 'web._log' Receiver: top-level Arguments: [...] #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:184) #1 main () #2 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:261) #3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Creating Custom Libraries Dart also allows you to use your own code as a library. Creating a custom library involves the following steps − Step 1: Declaring a Library To explicitly declare a library, use the library statement. The syntax for declaring a library is as given below − library library_name // library contents go here Step 2: Associating a Library You can associate a library in two ways − - Within the same directory import 'library_name' - From a different directory import 'dir/library_name' Example: Custom Library First, let us define a custom library, calculator.dart. library calculator_lib; import 'dart:math'; //import statement after the libaray statement int add(int firstNumber,int secondNumber){ print("inside add method of Calculator Library ") ; return firstNumber+secondNumber; } int modulus(int firstNumber,int secondNumber){ print("inside modulus method of Calculator Library ") ; return firstNumber%secondNumber; } int random(int no){ return new Random().nextInt(no); } Next, we will import the library − import 'calculator.dart'; void main() { var num1 = 10; var num2 = 20; var sum = add(num1,num2); var mod = modulus(num1,num2); var r = random(10); print("$num1 + $num2 = $sum"); print("$num1 % $num2= $mod"); print("random no $r"); } The program should produce the following output − inside add method of Calculator Library inside modulus method of Calculator Library 10 + 20 = 30 10 % 20= 10 random no 0 Library Prefix If you import two libraries with conflicting identifiers, then you can specify a prefix for one or both libraries. Use the 'as' keyword for specifying the prefix. The syntax for the same is given below − Syntax import 'library_uri' as prefix Example First, let us define a library: loggerlib.dart. library loggerlib; void log(msg){ print("Log method called in loggerlib msg:$msg"); } Next, we will define another library: webloggerlib.dart. library webloggerlib; void log(msg){ print("Log method called in webloggerlib msg:$msg"); } Finally, we will import the library with a prefix. import 'loggerlib.dart'; import 'webloggerlib.dart' as web; // prefix avoids function name clashes void main(){ log("hello from loggerlib"); web.log("hello from webloggerlib"); } It will produce the following output − Log method called in loggerlib msg:hello from loggerlib Log method called in webloggerlib msg:hello from webloggerlib Dart. Dart Programming - Concurrency Concurrency is the execution of several instruction sequences at the same time. It involves performing more than one task simultaneously. Dart uses Isolates as a tool for doing works in parallel. The dart:isolate package is Dart’s solution to taking single-threaded Dart code and allowing the application to make greater use of the hard-ware available. Isolates, as the name suggests, are isolated units of running code. The only way to send data between them is by passing messages, like the way you pass messages between the client and the server. An isolate helps the program to take advantage of multicore microprocessors out of the box. Example Let’s take an example to understand this concept better.Live Demo import 'dart:isolate'; void foo(var message){ print('execution from foo ... the message is :${message}'); } void main(){ Isolate.spawn(foo,'Hello!!'); Isolate.spawn(foo,'Greetings!!'); Isolate.spawn(foo,'Welcome!!'); print('execution from main1'); print('execution from main2'); print('execution from main3'); } Here, the spawn method of the Isolate class facilitates running a function, foo, in parallel with the rest of our code. The spawn function takes two parameters − - the function to be spawned, and - an object that will be passed to the spawned function. In case there is no object to pass to the spawned function, it can be passed a NULL value. The two functions (foo and main) might not necessarily run in the same order each time. There is no guarantee as to when foo will be executing and when main() will be executing. The output will be different each time you run. Output 1 execution from main1 execution from main2 execution from main3 execution from foo ... the message is :Hello!! Output 2 execution from main1 execution from main2 execution from main3 execution from foo ... the message is :Welcome!! execution from foo ... the message is :Hello!! execution from foo ... the message is :Greetings!! From the outputs, we can conclude that the Dart code can spawn a new isolate from running code like the way Java or C# code can start a new thread. Isolates differ from threads in that an isolate has its own memory. There’s no way to share a variable between isolates—the only way to communicate between isolates is via message passing. Note − The above output will be different for different hardware and operating system configurations. Isolate v/s Future Doing complex computational work asynchronously is important to ensure responsiveness of applications. Dart Future is a mechanism for retrieving the value of an asynchronous task after it has completed, while Dart Isolates are a tool for abstracting parallelism and implementing it on a practical high-level basis. Dart Programming - Unit Testing Unit Testing involves testing every individual unit of an application. It helps the developer to test small functionalities without running the entire complex application. The Dart external library named "test" provides a standard way of writing and running unit tests. Dart unit testing involves the following steps − Step 1: Installing the "test" package To installing third-party packages in the current project, you will require the pubspec.yaml file. To install test packages, first make the following entry in the pubspec.yaml file − dependencies: test: After making the entry, right-click the pubspec.yaml file and get dependencies. It will install the "test" package. Given below is a screenshot for the same in the WebStorm Editor. Packages can be installed from the command line too. Type the following in the terminal − pub get Step 2: Importing the "test" package import "package:test/test.dart"; Step 3 Writing Tests Tests are specified using the top-level function test(), while test assertions are made using the expect() function. For using these methods, they should be installed as a pub dependency. Syntax test("Description of the test ", () { expect(actualValue , matchingValue) }); The group() function can be used to group tests. Each group's description is added to the beginning of its test's descriptions. Syntax group("some_Group_Name", () { test("test_name_1", () { expect(actual, equals(exptected)); }); test("test_name_2", () { expect(actual, equals(expected)); }); }) Example 1: A Passing Test The following example defines a method Add(). This method takes two integer values and returns an integer representing the sum. To test this add() method − Step 1 − Import the test package as given below. Step 2 − Define the test using the test() function. Here, the test() function uses the expect() function to enforce an assertion. import 'package:test/test.dart'; // Import the test package int Add(int x,int y) // Function to be tested { return x+y; } void main() { // Define the test test("test to check add method",(){ // Arrange var expected = 30; // Act var actual = Add(10,20); // Asset expect(actual,expected); }); } It should produce the following output − 00:00 +0: test to check add method 00:00 +1: All tests passed! Example 2: A Failing Test The subtract() method defined below has a logical mistake. The following test verifies the same. import 'package:test/test.dart'; int Add(int x,int y){ return x+y; } int Sub(int x,int y){ return x-y-1; } void main(){ test('test to check sub',(){ var expected = 10; // Arrange var actual = Sub(30,20); // Act expect(actual,expected); // Assert }); test("test to check add method",(){ var expected = 30; // Arrange var actual = Add(10,20); // Act expect(actual,expected); // Asset }); } Output − The test case for the function add() passes but the test for subtract() fails as shown below. 00:00 +0: test to check sub 00:00 +0 -1: test to check sub Expected: <10> Actual: <9> package:test expect bin\Test123.dart 18:5 main.<fn> 00:00 +0 -1: test to check add method 00:00 +1 -1: Some tests failed. Unhandled exception: Dummy exception to set exit code. #0 _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:938) #1 _microtaskLoop (dart:async/schedule_microtask.dart:41) #2 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50) #3 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:394) #4 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:414) #5 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:148) Grouping Test Cases You can group the test cases so that it adds more meaning to you test code. If you have many test cases this helps to write much cleaner code. In the given code, we are writing a test case for the split() function and the trim function. Hence, we logically group these test cases and call it String. Example import "package:test/test.dart"; void main() { group("String", () { test("test on split() method of string class", () { var string = "foo,bar,baz"; expect(string.split(","), equals(["foo", "bar", "baz"])); }); test("test on trim() method of string class", () { var string = " foo "; expect(string.trim(), equals("foo")); }); }); } Output − The output will append the group name for each test case as given below − 00:00 +0: String test on split() method of string class 00:00 +1: String test on trim() method of string class 00:00 +2: All tests passed Dart_16<<_17<< Step 1 − In the section "Generate sample content", select SimpleWebApplication. _20<<_21<<
https://www.tutorialspoint.com/dart_programming/dart_programming_quick_guide.htm
CC-MAIN-2018-30
refinedweb
11,652
55.03
When I use the PLS C:\Python26\lib\site-packages\PLS.py:51: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 if not e.message.startswith("cannot import name"): Extension command PLS could not be loaded. The module or a module that it requires may be missing, or there may be syntax errors in it. what's wrong with my work? Topic This topic has been locked. SystemAdmin 110000D4XK 1106 Posts Pinned topic PLS 2012-11-12T03:29:57Z | - SystemAdmin 110000D4XK1106 Posts Re: PLS2012-11-12T13:33:04Z This is the accepted answer. This is the accepted answer.That probably means that the numpy/scipy libraries are not installed or that you have the wrong version of them. If you think that you have installed these correctly, run this program in a syntax window and report back along with the Statistics version (including whether 32 or 64 bit) and platform. begin program. import numpy numpy.__version__ import scipy scipy.__version__ end program.
https://www.ibm.com/developerworks/community/forums/html/topic?id=77777777-0000-0000-0000-000014907437
CC-MAIN-2016-07
refinedweb
165
70.5
Introduction This document will brief us on how we connect SAP Lumira Desktop with SAP HANA cloud platform and develop bus transport visualizations on the bus data put into SAP HANA Cloud. Steps: - Connect to SAP HANA Cloud Platform from Eclipse IDE. - Create a Calculation View on the data of SAP HANA Cloud Platform using SAP HANA Modeler - Create a DB Tunnel and Connect SAP Lumira Desktop to SAP HANA Cloud platform using the DB tunnel credentials. - Once SAP Lumira is connected to SAP HANA Cloud, analyze the data of HANA Cloud Platform by making visualizations. Firstly, we need to install Eclipse IDE version Mars or Luna. We need to install SAP HANA tools for Eclipse. Also, we have to register and login to SAP HANA Cloud Cockpit using the given link. We need to select “Database and Schemas” to create a New trial XS instance of SAP HANA database. Reading csv file in SAP HANA Cloud Platform Create a Package and right Click on Package and go to File->Import. Import the CSV file. e.g. bus.csv Create a new file with the name bus.hdbti and write the following code in it import = [ { table = “s0009779955trial.hana::mymodel.bus”; schema = “_SYS_BIC”; file = “s0009779955trial.hana:bus.csv”; header = false; }]; Create one more file with the name mymodel.hdbdd and write the following code in it. namespace s0009779955trial.hana; @Schema: ‘_SYS_BIC’ context mymodel { type SString: String(60); @Catalog.tableType: #COLUMN @nokey Entity busfinal { busno: Integer; source: SString; destination: SString; arrival: SString; departure: SString; distance : Integer; }; } Note: Column name in the code above should be same as used in CSV file. Use Quick fix to change the encoding of individual files to UTF-8. Create Calculation View 1. In the Repository Package in Eclipse IDE, a calculation view of type “Graphical” is created. 2. In the Scenario Editor, we need to link the join node with the aggregation node. 3. Select the aggregation node and add all the columns to output. 4. Semantics node should be selected and the enable analytic privilege checkbox in the Details pane should be deselected 5. View should be Saved and Activated. The user needs to be granted select privileges. This is done by calling a procedure through the following in SQL Console. CALL “HCP”.”HCP_GRANT_SELECT_ON_ACTIVATED_OBJECTS” Catalog Folder is refreshed and generated calculation view can be seen in _SYS_BIC schema. We can connect “SAP Lumira Desktop” with SAP HANA Cloud Platform by creating a DB tunnel. We need to run the following command at command prompt. neo open-db-tunnel -a <account_name> -h <landscape_host> -u <user> -i <schema_ID> <landscape_host> = hanatrial.ondemand.com This cmd will give us the password to connect to SAP HANA Cloud Platform. Once SAP lumira is started, we can connect to SAP HANA Cloud Platform using the credentials of DB tunnel and see the calculation view created in SAP HANA Cloud. I have made following visualizations in SAP Lumira by making use of SAP HANA cloud platform data. These visualizations could be helpful for Transport Manager of Bus Service. The below visualization gives an idea what is the distance between source and destination and which bus no is going on that route. The below visualization we made use of donut charts. This will tell the distance between two stations and bus number. This visualization depicts the network chart of all the buses on routes. This shows which all buses are going from source to destination. This visualization made use of stacked column chart of sap lumira. This shows the bus no and the buses departure time from source station This visualization also made use of stacked column chart of sap lumira. This shows the bus no and the buses arrival time on destination station. Hope you like reading my blog. Please do not forget to provide your valuable feedback and responses. Thanks & Regards, Saurabh Raheja Hi Saurabh , Thank you for nice blog. Which Lumira Desktop version and Drivers you are using to connect HANA? Hi Sateesh, Thank you for reading my blog. I worked on Lumira Desktop v 1.27. I think as long as lumira supports connection to sap hana, it will work. I used DB tunnel To connect lumira to hana cloud platform. from 1.29 connecting to cloud is removed . Could you please share any documented evidence of the same ? Saurabh , I could find supporting doc. Can you create this workflow in lum 1.29 ? I have not tried for lumira 1.29 .
https://blogs.sap.com/2016/04/22/visualizations-created-using-sap-hana-cloud-platform-and-sap-lumira/
CC-MAIN-2017-51
refinedweb
744
66.64
Your browser does not seem to support JavaScript. As a result, your viewing experience will be diminished, and you have been placed in read-only mode. Please download a browser that supports JavaScript, or enable it if it's disabled (i.e. NoScript). Hello, I'm having issues wrapping my head around how to change an FBX Importer preference via Python. Any help would be appreciated, below explains my approach and what I was able to figure out so far. Please note that I am fairly new to the C4D Python API. The specific goal is to change c4d.FBXIMPORT_NORMALS of the FBX Import. c4d.FBXIMPORT_NORMALS First I need to figure out what the plugin ID is. I used the below approach to do. Please let me know if there is a better way to do this - for p in c4d.plugins.FilterPluginList(c4d.PLUGINTYPE_ANY,True): print (p.GetID(), " = ", p.GetName()) The above output gives me - 1026370 = FBX (*.fbx) 1026369 = FBX (*.fbx) 1026370 = FBX (*.fbx) Export 1026369 = FBX (*.fbx) Import 1026371 = FBXExportReferenceTag The FBX Import Plugin Id is 1026369 . I now can return the BasePlugin object and SHOULD be able to set the parameter from here - 1026369 plug = c4d.plugins.FindPlugin(1026369, c4d.PLUGINTYPE_SCENELOADER) print(plug) >>> <c4d.plugins.BasePlugin object called FBX (*.fbx) with ID 15 at 2429143389120> plug[c4d.FBXIMPORT_NORMALS] = c4d.FBXIMPORT_NORMALS_NORMALTAGS I run the above without any changes to the Preferences/FBX Import UI. Following the same concept for the "Units" plugin I get the expected results when modifying it's parm Units[c4d.PREF_UNITS_AUTOCONVERT] = False Units[c4d.PREF_UNITS_AUTOCONVERT] = False Am I doing something incorrectly? Is this access via Python just not supported? Any help would be great. Thank you. Hi @clayton_krause sorry for the late reply, There is actually two ways, one by accessing the global preference, but that will change the default import settings for every FBX importation. I would recommend to no change the preference as this could confuse user and instead use the second way that you tried to achieve (at least I think) by accessing the SceneLoader and only change the setting for the current Cinema 4D session. To do so you need to retrieve the SceneLoader and then send the message MSG_RETRIEVEPRIVATEDATA to retrieve a dictionary containing a BaseList2D holding the settings used for the loading: MSG_RETRIEVEPRIVATEDATA import c4d def main(): # Retrieves a path to load the imported file selectedFile = c4d.storage.LoadDialog(title="Import a FBX File", type=c4d.FILESELECTTYPE_ANYTHING, force_suffix="fbx") if not selectedFile: return plug = c4d.plugins.FindPlugin(c4d.FORMAT_FBX_IMPORT, c4d.PLUGINTYPE_SCENELOADER) if plug is None: raise RuntimeError("Failed to retrieve the FBX importer.") data = dict() if not plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data): raise RuntimeError("Failed to retrieve private data.") # BaseList2D object stored in "imexporter" key hold the settings fbxImport = data.get("imexporter", None) if fbxImport is None: raise RuntimeError("Failed to retrieve BaseList2D settings holder.") # Defines the settings fbxImport[c4d.FBXIMPORT_NORMALS] = c4d.FBXIMPORT_NORMALS_NORMALTAGS # Imports without dialogs if not c4d.documents.MergeDocument(doc, selectedFile, c4d.SCENEFILTER_OBJECTS | c4d.SCENEFILTER_MATERIALS, None): raise RuntimeError("Failed to load the document.") # Pushes an update event to Cinema 4D c4d.EventAdd() if __name__ == '__main__': main() Cheers, Maxime.
https://plugincafe.maxon.net/topic/14086/python-change-fbx-exporter-settings
CC-MAIN-2022-27
refinedweb
522
52.05
On 29 December 2010 15:18, Georg Brandl g.brandl@gmx.net wrote: Am 29.12.2010 15:46, schrieb Michael Foord: I like the idea, but that's a fairly big semantic change. What about adding an -e option that takes an expression, and prints its value? So you'd have python -e "12 / 4.1" (AFAICT, -e is unused at present). That would be great. I did worry that changing the output would be backwards incompatible with code that shells out to Python using "-c", so a different command line option would be great. So long as it works with multiple statements (semi-colon separated) like the current "-c" behaviour. Hey, what about this little module: import sys for x in sys.argv[1:]: exec compile(x, '<cmdline>', 'single') Then: $ python -me '1+1; 2+2' 2 4 So now you can pip install e and then python -me... Michael > Georg Python-ideas mailing list Python-ideas@python.org -- May you do good and not evil May you find forgiveness for yourself and forgive others May you share freely, never taking more than you give. -- the sqlite blessing
https://mail.python.org/archives/list/python-ideas@python.org/message/ZLGPUO4FRYH52OLKBQRAVMEG6M7BFDGS/
CC-MAIN-2021-04
refinedweb
190
84.57
Other AliasggiSetFlags, ggiGetFlags, ggiAddFlags SYNOPSIS #include <ggi/ggi.h> int ggiSetFlags(ggi_visual_t vis, ggi_flags flags); ggi_flags ggiGetFlags(ggi_visual_t vis); #define ggiAddFlags(vis,flags) \ ggiSetFlags((vis), ggiGetFlags((vis)) | (flags)) #define ggiRemoveFlags(vis,flags) \ ggiSetFlags((vis), ggiGetFlags((vis)) & ~(flags)) DESCRIPTIONggiSetFlags sets the specified flags (bitwise OR'd together) on a visual. ggiGetFlags obtains the flags currently in effect. ggiAddFlags and ggiRemoveFlags are macros that set or unset the specified flags. Flags are used to alter a visual's underlying behavior. All flags default to an unset value. Flags which are not supported by a given visual will remain unset even when an attempt is made to raise them. Thus, it is possible to tell by reading back the flags whether or not each of the flags is supported by the given. GGI guarantees that the effects of drawing operations on the final state of the buffer are consistant with the order in which they were invoked, but as to what order the operations visibly appear during a flush, that is entirely up to the target. You could draw a red square with the GPU (through the target), and then draw a green square inside it via software -- you will always end up with a red square inside a green square, but the user may see the red square appear first. When it comes to directbuffer, though, that is the problem that the TIDYBUF flag is meant to fix. Or at least, the TIDYBUF flag fixes a problem with the way GGI fixes the serialization problem. The display is flushed entirely before the acquire completes, and then the db is flushed entirely before the db is released, so that is serialized. The TIDYBUF stuff lets you bypass this serialization for efficiency. So the recommendation for all graphics applications is to set the asynchronous mode. It will be far more efficient on some platforms and will never be worse. Setting up asynchronous mode: ggiAddFlags(vis, GGIFLAG_ASYNC); /* switches to asynchronous mode */ ggiFlush(vis); /* updates the screen */ ggiRemoveFlags(vis, GGIFLAG_ASYNC); /* switches to synchronous mode */. These visuals may also perform dirty-region tracking, such that if the directbuffer is used, altered data may never reach the screen until the lock is released, because the visual does not know that a certain area of the backbuffer contains new (dirty) data. Even explicitly calling ggiFlushRegion(3) on the affected area may not cause the data to be sent to the screen. -. Note that this means that, as long as the lock is held, affected regions may also have to be flushed (and thus, should be flushed) after normal drawing primitives are called. Before releasing the lock, applications should be sure to flush all affected regions, because the visual may revert to its default dirty-region management behavior after the lock is released. Do note, also, that in multi-frame displays ggiFlushRegion(3) affects only the current write frame, so even though it is possible to use a directbuffer to alter a different frame, you must call ggiSetWriteFrame(3) to tell the visual that you will be altering the frame. The GGIFLAG_TIDYBUF flag is not available on all visuals, but it is safe to attempt to set it whether or not it is available. Code written for the tidy-buffering mode will display correctly on visuals which do not have a tidy-buffering mode (but not vice-versa), so it is not necessary to adapt program behavior to its non-presence. It is recommended that, if an application must use directbuffer, the application should attempt to place the visual in tidy-buffered mode. Do note, though, that many applications that use the directbuffer do not actually need to do so and probably should not, as it reduces portability.
http://manpages.org/ggiremoveflags/3
CC-MAIN-2018-43
refinedweb
618
56.89
Created on 2008-12-02 15:42 by mrts, last changed 2012-06-28 13:32 by python-dev. This issue is now closed. Race. What course of action do you suggest? First chmod 0700 on the directory? Mmmh, very recent Linux kernels (>= 2.6.16) seem to have specific functions to deal with this (see man pages for openat, unlinkat, etc.). A shameless copy of the Perl fix for the bug looks like the evident solution. Somebody has to examine the fix though, I'm afraid I'm not currently able to do it. The Perl patch is here:;filename=etch_03_fix_file_path;att=1;bug=286922 It is a recursive implementation of rmtree. What it does is 1) get the inode of the path 2) unlink it altogether if not a dir 3) otherwise, chdir to it 4) check that '.' still has the same inode, otherwise bail out.. Using chdir() makes sense and it doesn't look like a too big problem to me: def rmtree(...): ... curdir = os.getcwd() try: call chdir() as required finally: try: os.chdir(curdir) except: warnings.warn("Unable to chdir to previous current dir") ... > Using chdir() makes sense and it doesn't look like a too big problem to me: It's a problem if another thread in the process is making file operations using relative paths at the same time. Since shutil functions have until now been safe against this possibility, I don't think it's ok to make them unsafe in future versions. Ah, right you are. Attaching an initial alpha-quality patched shutil.py and a script to test the attack. Run the script by sourcing it with . test_issue4489.sh, not by executing (job control won't work in this case). And here's the diff so you can review what I was up to. Note that this does not yet fix the problem (although the logic looks about right), I have to examine the problem more thoroughly. Aha, got it -- while removing /a/b/c/d, there's no easy way to detect that b or c has become a symlink. I.e. given directory tree a `-- b |-- c `-- d 1. os.rmdir('/a/b/c') succeeds 2. execution is suspended 3. '/a/b' is made a symlink to a path that contains 'd' 4. '/a/b/d' is neither a symlink, nor has it's inode been recorded, so os.rmdir('/a/b/d') succeeds I'm afraid the solution for the Perl bug is susceptible to the same problem. A blunt, ineffective solution would be to walk the tree before removing it and recording path : inode pairs in a dict on first pass and then checking that the inodes have not changed during removal on second pass. If no clever bulletproof fix emerges, perhaps this should be added as shutil.rmtree_safe (duh, API bloat...)? > A blunt, ineffective solution would be to walk the tree before removing > it and recording path : inode pairs in a dict on first pass and then > checking that the inodes have not changed during removal on second pass. There's no way to do the "check inode then remove" sequence atomically. Fixed a minor bug in test script and added Perl test as well. Perl with File-Path-2.07 passes the test. Antoine, what if we add another function, rmtree_safe() that uses chdir() and document that it is protected from the race condition but may have the side effect of changing the current dir in threaded environment? Replying to previous comment: > There's no way to do the "check inode then remove" sequence atomically. Right, although the attack window would be tiny, this is not a real solution. > Anto). FWIW, I've opened a separate bug entry for the creation of the openat(), etc. wrappers: #4761. Those functions seem to exist on recent Linux distros (even Debian stable). Mart, How does "rm -rf" address this issue? Or does it? shutils.rmtree should probably do the same thing. Here is a draft patch. It uses the *at functions and fdlistdir consequently it only makes it safe if those functions are available. It works using a recursive implementation and an open file descriptor pointing to a directory, instead of maintaining state by changing the current directory. If the *at functions are unavailable, it falls back to the unsafe implementation. It requires the patches from issue4761 and issue10755 to work. Thanks for the patch. There seems to be a race remaining here: + try: + if os.path.islink(path): + # symlinks to directories are forbidden, see bug #1669 + raise OSError("Cannot call rmtree on a symbolic link") + except OSError: + onerror(os.path.islink, path, sys.exc_info()) + # can't continue even if onerror hook returns + return + fd = os.open(path, os.O_RDONLY) Someone could change `path` to be a symlink between the calls to islink() and open(). You probably need to stat the fd instead. Some other things: - if close() is meant to be a private helper, it should be named _close() - instead of a bare "except" in close(), use "except EnvironmentError" or "except OSError" I haven't looked at the tests yet. Updated patch removes the race condition. Since an open follows symlinks, you can't just fstat the fd to see if it is a link. I followed the following to overcome this: Le mercredi 05 janvier 2011 à 16:58 +0000, Ross Lagerwall a écrit : > Ross Lagerwall <rosslagerwall@gmail.com> added the comment: > > Updated patch removes the race condition. Since an open follows symlinks, you can't just fstat the fd to see if it is a link. I followed the following to overcome this: > Nice. I am unsure about the following piece of code: + if stat.S_ISDIR(mode): + if stat.S_ISLNK(mode): + try: + raise OSError("Cannot call rmtree on a symbolic link") + except OSError: + onerror(os.fstatat, (dirfd, name), sys.exc_info()) If rmtree() encounters a symlink *inside* the tree, I would expect it to simply remove the symlink, rather than choke and abort (it's also what the unsafe implementation does). I think I misread the original implementation. Here is an updated version with that code just taken out. I made two comments on rietveld but the email was rejected. Updated patch based on Eric's comments: Store _supports_safe_rmdir at the module level. Move imports up to module level Skip test on non-threading build I made another review but my mail was rejected. Lib/test/test_shutil.py:319: @unittest.skipIf(threading == None, 'requires threading') You can just say skipUnless(threading, 'msg') Lib/test/test_shutil.py:344: raise Shouldn’t this use self.fail? Lib/test/test_shutil.py:319: @unittest.skipIf(threading == None, 'requires threading') On 2011/10/07 19:29:47, eric.araujo wrote: > You can just say skipUnless(threading, 'msg') Right. Lib/test/test_shutil.py:344: raise On 2011/10/07 19:29:47, eric.araujo wrote: > Shouldn’t this use self.fail? I would have thought it's better if the original exception is passed through and displayed rather than some sort of failure message that just says "OSError occurred". There's a race: """ --- Lib/shutil.py 2011-11-05 00:11:05.745221315 +0100 +++ Lib/shutil.py.new 2011-11-05 00:11:01.445220324 +0100 @@ -307,6 +307,7 @@ try: mode = os.fstatat(dirfd, name, os.AT_SYMLINK_NOFOLLOW).st_mode except os.error: mode = 0 if stat.S_ISDIR(mode): + input("press enter") newfd = os.openat(dirfd, name, os.O_RDONLY) _rmtree_safe(newfd, ignore_errors, onerror) try: """ $ rm -rf /tmp/target $ mkdir -p /tmp/target/etc $ ./python -c "import shutil; shutil.rmtree('/tmp/target')" press enter^Z [1]+ Stopped ./python -c "import shutil; shutil.rmtree('/tmp/target')" $ rm -r /tmp/target/etc; ln -s /etc /tmp/target/ $ fg ./python -c "import shutil; shutil.rmtree('/tmp/target')" Traceback (most recent call last): File "<string>", line 1, in <module> File "/home/cf/python/cpython/Lib/shutil.py", line 290, in rmtree _rmtree_safe(fd, ignore_errors, onerror) File "/home/cf/python/cpython/Lib/shutil.py", line 314, in _rmtree_safe _rmtree_safe(newfd, ignore_errors, onerror) File "/home/cf/python/cpython/Lib/shutil.py", line 323, in _rmtree_safe onerror(os.unlinkat, (dirfd, name), sys.exc_info()) File "/home/cf/python/cpython/Lib/shutil.py", line 321, in _rmtree_safe os.unlinkat(dirfd, name) PermissionError: [Errno 13] Permission denied [52334 refs] """ openat(3, "etc", O_RDONLY|O_LARGEFILE) = 4 dup(4) = 5 fstat64(5, {st_mode=S_IFDIR|0755, st_size=4096, ...}) = 0 fcntl64(5, F_GETFL) = 0x8000 (flags O_RDONLY|O_LARGEFILE) fcntl64(5, F_SETFD, FD_CLOEXEC) = 0 getdents64(5, /* 162 entries */, 32768) = 5176 getdents64(5, /* 0 entries */, 32768) = 0 close(5) = 0 fstatat64(4, "passwd", {st_mode=S_IFREG|0644, st_size=980, ...}, AT_SYMLINK_NOFOLLOW) = 0 unlinkat(4, "passwd", 0) = -1 EACCES (Permission denied) """ You should use the lstat/open/fstat idiom. Also, here: """ mode1 = os.lstat(path).st_mode if stat.S_ISLNK(mode1): raise OSError("Cannot call rmtree on a symbolic link") except OSError: onerror(os.lstat, path, sys.exc_info()) # can't continue even if onerror hook returns return fd = os.open(path, os.O_RDONLY) try: mode2 = os.fstat(fd).st_mode if mode1 != mode2: raise OSError("Target changed") """ You check that path is not a symlink, then you open it, perform fstat on it, and check that the mode is the same. But if someone replaces path by a symlink to a directory with the same mode, then rmtree won't catch this. You should also compare st_dev and st_ino to make sure we're dealing with the same file. One more thing :-) """ fd = os.open(path, os.O_RDONLY) try: mode2 = os.fstat(fd).st_mode if mode1 != mode2: raise OSError("Target changed") except OSError: onerror(os.fstat, fd, sys.exc_info()) # can't continue if target has changed return """ Here `fd` is not closed (there might be other places leaking FD).? Sounds good. FYI, I have a pathlib experiment in, with an optional openat-based accessor. > FYI, I have a pathlib experiment in >, with an optional openat-based > accessor. Interesting: I used to think that the current API for dealing with paths was a little too basic and terse. Concerning this issue, one (last) thing: rmtree performs a depth-first traversal of the directory tree, keeping an open FD at each directory level: in case of deeply-nested directory hierarchy, or if there are many open FDs, there's the risk of running out of FDs. I think the best thing would be to let rmtree fail (provided it closes all the FDs it opened): falling back to the "unsafe" version would be stupid (an attacker would just have to create a deeply-nested hierarchy, and then use the same old symlink race). > I think the best thing would be to let rmtree fail (provided it closes > all the FDs it opened) Agreed. Thanks Charles, I'll take your comments into account and take a look at making a general walker method. What's the current state here? Anyone working on a solution or are we waiting how will work out? If the consensus is to add a generic walker method, wouldn't be appropriate to open a new bug and add it as dependency? Or is there one I've missed? >? > If the consensus is to add a generic walker method, wouldn't be > appropriate to open a new bug and add it as dependency? Agreed. > >? In case you want opinions on pathlib: I, for one, disliked Jason Orendorff’s path module, because it did not distinguish between pure string operations and I/O-inducing operations, and also because it duplicated os/os.path functions. Your API doesn’t have these issues, so for my taste it’s conceptually better. I should clone your repo and play with the module a bit to see if I like it. Anybody working on this one? I’d give it a shot otherwise. > Anybody working on this one? I’d give it a shot otherwise. Go ahead. You could - should? - probably use the new os.fwalk() to walk directories in a safe maner. I've implemented a _safe_rmtree which gets used if os.fwalk() and os.unlinkat() are available. Test suite still passes in regression mode both on Mac (= no effect) and Linux. Let me know if I missed something. + Same a rmtree but uses safe functions to avoid race conditions ^ typo + onerror(os.unlinkat, os.path.join(path, name), sys.exc_info()) + onerror(os.fwalk, path, sys.exc_info()) The documentation currently states that the first argument of onerror will be one of os.path.islink, os.listdir, os.remove, os.rmdir. You shuld probably add os.unlinkat and os.fwalk to that list now. Otherwise, looks good to me. Thanks Petri. I've added the missing s in my repo and attach a proposed separate doc patch, I'd like reviewed by someone whose English is better than mine. :) I'm taking Charles-François' review comments here. > 1. since fwalk() uses O(depth directory tree) file descriptors, we might run out > of FD on really deep directory hierarchies. It shouldn't be a problem in > practise Should I mention it in the docs? The old one uses recursion and we don't warn about the stack too... > 2. there is a slight API change, since the API exposes the function that > triggered the failure. I don't think there's a lot a of code that depends on > this, but it's definitely a change I was pondering whether I should "fake" the method names as they pretty much map: listdir instead of fwalk and unlink instead of unlink at… what do you all think about that? I’ve incorporated all the feedback (I hope). I had to refactor the tests slightly, but we have 100% code coverage for both versions of rmtree. Speaking of: I’ve renamed the default version of rmtree to _default_rmtree and _safe_rmtree to _safe_fwalk_rmtree as we’ll need more _safe versions for OS X and Windows. Also, that way the default version isn’t lost. (this time both docs and code are in one patch, sorry for the experiment) This might not be the final patch though as I’m waiting on feedback for the backward compatibility question (<>). That might simplify the tests again a bit if we decide to "fake". Have a nice Sunday everyone. :) A. > Martin proposed > <> to > re-implement os.fwalk inside of rmdir which I’m -1 > <> on. I agree that it isn't worth the hassle. I don't think that doing direct flistdir/fstatat calls would be more complex. We already have directory walking implemented (in default_rmtree), and I think the fd-based calls could nicely integrate with that. I'll provide a patch. Martin, are you still committed to this? I still think code duplication is bad (especially for security related code) but I’d be willing to write a fwalk-less version so it doesn’t look like I’m just defending my code here. > Martin, are you still committed to this? Yes, I'll provide a patch RSN. I doubt that there will be that much code duplication. Here is a patch with just the shutil changes. Compared to rmtree-with-fwalk-v3.diff, this changes 90 lines of rmtree, whereas the fwalk version changes only 70 lines. On the plus side, it's much more obvious in this version that the *at variant has the same algorithm as the non-*at version. Fair?) I still plan to work on this, but I'm also really really short on time. I still favor my own approach (obviously), so if you want to bring it into shape - that would be appreciated. I'll try to get it in before beta1 then. Here). New changeset c910af2e3c98 by Hynek Schlawack in branch 'default': #4489: Add a shutil.rmtree that isn't suspectible to symlink attacks New changeset 53fc7f59c7bb by Hynek Schlawack in branch 'default': #4489: Fix usage of fd-based functions to new api introduced earlier today Can I suggest setting a “safe” attribute on the rmtree function object instead of adding another name to the module? I thought about that too but couldn't find a precedent (I didn't look very long though :)) where we've done that before so I went for an attribute. I'd change it immediately if others agree. I'm in the process of updating the LBYL support to use a "rmtree.avoids_symlink_attacks" function attribute rather than the "rmtree_is_safe" module level attribute. As I said in the hmac.secure_compare function discussion, the words "safe" and "secure" are too vague to ever make for good API design. Much better to tell people exactly what they're safe against (rmtree_is_safe -> rmtree.avoids_symlink_attacks), or designed to be appropriate for (hmac.secure_compare -> hmac.compare_digest). Excellent Nick! I discussed the very same thing with David yesterday but somehow we didn't come up with a good name. So we kept it on "safe" (which predates the secure discussion). Bikeshedding: (os.unlink in os.supports_dir_fd and os.open in os.supports_dir_fd) could be rewritten as { os.open, os.unlink } <= os.supports_dir_fd As you were! The) :) New changeset c2be81151994 by Nick Coghlan in branch 'default': Issue #4489: Rename the feature marker for the symlink resistant rmtree and store it as a function attribute > I guess it’s too late to propose “os.open.supports_dir_fd and > os.unlink.supports_dir_fd” (and I don’t know if that is feasible > with C functions) :) Where were you when "is_implemented" was being savagely torn apart last week? ;-) I was at work, and moving out of my apartment, and desperating at the subthreads spawned by my mail about packaging, and agreeing with the people being -1 on is_implemented on Signature objects :-) Éric - there's almost certainly going to be a PEP for 3.4 about doing this kind of feature advertisement in a cleaner and more consistent way. Yep, that is promising. At worst we’ll have a new cool API and three obsolete sets in the os module, not a big deal. Okay everyone, let's call it day – after 3,5 years. :) Further enhancement requests please in separate tickets. Thanks to everybody who took part! The fix for this issue broke support for bytes in shutil.rmtree: $ mkdir -p /tmp/a/b $ python3.2 -c 'import shutil; shutil.rmtree(b"/tmp/a")' $ mkdir -p /tmp/a/b $ python3.3 -c 'import shutil; shutil.rmtree(b"/tmp/a")' Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib64/python3.3/shutil.py", line 444, in rmtree _rmtree_safe_fd(fd, path, onerror) File "/usr/lib64/python3.3/shutil.py", line 381, in _rmtree_safe_fd fullname = os.path.join(path, name) File "/usr/lib64/python3.3/posixpath.py", line 78, in join if b.startswith(sep): TypeError: startswith first arg must be str or a tuple of str, not bytes $ > The fix for this issue broke support for bytes in shutil.rmtree: What platform? Windows, or non-Windows? It'll probably be obvious regardless, but that might help. Tinkering with os.path.join, that traceback means that "name" is a str instance, while "path" is a bytes instance. The culprit actually appears to be the fact that the type returned by os.listdir (et al) when handed a file descriptor is always a string (this is not explicitly documented, a problem in itself, but that's the behaviour I see here on linux). One way to handle this would be to use the filesystem encoding with surrogateescape to decode any bytes path passed in to shutil.rmtree (at least in the _rmtree_safe_fd case) and handle the actual removal with Unicode throughout. So long as the original encoding of the supplied bytes path is compatible with that of the underlying filesystem, surrogateescape should ensure that everything round trips correctly. Your deduction is correct. listdir can't tell what the original argument type was based on the output--path_converter abstracts away those details. So it separately tests the type of the first argument. Staring at it again it's about as clear as mud, but the goal was, the output is always strings unless the user specified "path" as bytes. I'll make a separate issue regarding making the code easier to read and adding a clarification to the documentation. We should spare future programmers from having to guess at this behavior :) New changeset 2e2329aeb5c1 by Hynek Schlawack in branch 'default': #4489 Make fd based rmtree work on bytes The fix (c910af2e3c98 + 53fc7f59c7bb) for this issue broke deletion of directories, which contain symlinks to directories. (Directories with symlinks to regular files or symlinks to nonexistent files are unaffected.) $ mkdir -p /tmp/a/b $ ln -s b /tmp/a/c $ python3.2 -c 'import shutil; shutil.rmtree("/tmp/a")' $ mkdir -p /tmp/a/b $ ln -s b /tmp/a/c $ python3.3 -c 'import shutil; shutil.rmtree("/tmp/a")' Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib64/python3.3/shutil.py", line 447, in rmtree _rmtree_safe_fd(fd, path, onerror) File "/usr/lib64/python3.3/shutil.py", line 395, in _rmtree_safe_fd _rmtree_safe_fd(dirfd, fullname, onerror) File "/usr/lib64/python3.3/shutil.py", line 406, in _rmtree_safe_fd onerror(os.rmdir, path, sys.exc_info()) File "/usr/lib64/python3.3/shutil.py", line 404, in _rmtree_safe_fd os.rmdir(path) NotADirectoryError: [Errno 20] Not a directory: '/tmp/a/c' $ New changeset f9f798f1421e by Hynek Schlawack in branch 'default': #4489: Don't follow ever symlinks in rmtree Thanks you for catching that! It seems we did something really stupid: followed symlinks. I’ve fixed that and added regression tests. This one is a facepalm gentlepeople. I'm not a security guy, but: shouldn't the os.unlink call when it isn't a directory specify follow_symlinks=False? And wouldn't it be safer if the os.rmdir() call also used dir_fd=?. > I'm not a security guy, but: shouldn't the os.unlink call when it isn't a directory specify follow_symlinks=False? os.unlink has no follow_symlinks argument. Imagine what would happen if you‘d do a os.unlink() on a link and it would just remove the link destination. :) > And wouldn't it be safer if the os.rmdir() call also used dir_fd=? Unfortunately, os.rmdir('.', dir_fd=topfd) doesn’t work. As in the worst case it could delete only an empty directory, I think it’s fine. > Interestingly, os.listdir is not in os.supports_dir_fd although it works: False Will you fix it right away or shall I open a ticket? > I'd spell that > _use_fd_functions = ({os.listdir, os.open, os.rmdir, os.stat, os.unlink} < > os.supports_dir_fd and > {os.stat, os.unlink} <= os.supports_follow_symlinks) It would be: _use_fd_functions = ({os.listdir, os.open, os.stat, os.unlink} <= os.supports_dir_fd and os.stat in os.supports_follow_symlinks) But currently can’t do. > Finally, up to you, but I'd be tempted to change the "lstat" "and "fstat" calls to "stat" calls using the relevant parameters. That's not 3.3 fodder IMHO, feel free to open an enhancement ticket. I'm pretty busy right now, please open a ticket for listdir. . > I'm pretty busy right now, please open a ticket for listdir. done > . Okay I looked into it and it seems okay. IIRC, when Martin wrote the code (and I the fwalk version before), there was no known fd-based rmdir function. New changeset 9134bb4d0578 by Hynek Schlawack in branch 'default': #4489: Use dir_fd in rmdir in _rmtree_safe_fd()
http://bugs.python.org/issue4489
CC-MAIN-2016-36
refinedweb
3,884
68.16
#include <stdio.h> #include <stdlib.h> int main() { char a,b; printf("enter the firstkeyword n"); a = getchar(); printf("enter your second keyword n"); b = getchar(); if(a>b) { printf("it is '%c' greater than '%c' as i expected n",a,b); } else if (b>a) { printf("here'%c'is greater than '%c' n",b,a); } else { printf("dont type the same character twice in next session n"); } return(0); } after compiling the program the o/p is: enter the first keyword I entered '$' and used ctrl+z to eof and 'enter' to continue the program. But even without entering the second keyword the compiler printing the output as enter your second keyword it is '$' greater than '->' as i expected Can anyone help with this program? Sorry if any grammatical or phrase errors. The problem is that your newline gets buffered and passed onto the next getchar call. You need to deal with the buffered newline in perhaps the following way: printf("enter the firstkeyword n"); scanf(" %c", &a); printf("enter your second keyword n"); scanf(" %c", &b); The space before %c is a common idiom that tells scanf to ignore any space before the following character which in our case also includes the newline. It is not necessary in the first instance in this particular case but vital in the second. You also don't need the stdlib include and you can return without the brackets, like return 0; Actually, if you feel like experimenting and you are on a Linux terminal, you can set the terminal in raw mode which will remove any buffer and parsing abilities that the terminal would provide for you. To do that run /bin/stty raw in the terminal. This way there will be no buffering and you won't have to worry about any buffered newlines. The output on the console will look funny though (I've entered here a and b) unless you also regulate that with placing strategically carriage returns ( r): $ ./a.out enter the firstkeyword aenter your second keyword bhere'b'is greater than 'a' I've used your original code for the above. To restore it, just run /bin/stty cooked
https://www.dowemo.com/article/70310/the-tell-me-how-to-get-the-right-output
CC-MAIN-2018-26
refinedweb
363
62.51
Support » Qik 2s9v1 User’s Guide View document on multiple pages. You can also view this document as a printable PDF. - 1. Overview - 2. Contacting Pololu - 3. Connecting the Qik - - 4. Serial Interface - - 5. Serial Commands - - 6. Cyclic Redundancy Check (CRC) Error Detection - - 7. Troubleshooting - 8. Arduino Library from 1200 bps to 38.4 kbps; - Two on-board indicator LEDs (status/heartbeat and serial error indicator) for debugging and feedback. -.. 2. Contacting Pololu You can check the qik 2s9v1! 3. Connecting the Qik Connecting to the qik can be as simple as hooking up logic and motor power, your motors, and RX. Many applications can leave the jumpers off and the remaining logic connections—TX, ERR, and RESET—disconnected. The qik connections are shown above, and most of the pins are labeled on the back side of the motor controller. All square pads are ground.; 3.b. Logic Connections Serial Lines The qik requires a logic-level (0 – Vcc), non-inverted serial input connected to its serial receive line, RX, and it can handle baud rates from 1200 – 38,400 bps. This type of serial is often referred to as TTL and is an interface method commonly used by microcontrollers. The voltage on this pin should not exceed the supplied logic power voltage, Vcc. The qik provides logic-level, non-inverted serial output on its serial transmit line, TX, in response to commands that request information. Information requests always result in the transmission of a single byte per request. If you aren’t interested in receiving feedback from the qik, you can leave this line disconnected. Note that these lines are not compatible with RS-232 serial, which is inverted and uses voltages that would be out of spec (e.g. -12V to 12V). To connect the qik to an RS-232 port, you must use a converter such as our 23201a serial adapter, or a level shifter and inverter. Reset The reset line, RST, is an active-low input, which means that it resets the qik when driven low. This pin is internally pulled to Vcc, so many applications can leave this pin disconnected. Error The error line, ERR, is an output that is connected to the red error LED and drives high (Vcc).b. If you don’t care about error detection, you can leave this pin disconnected.. -. 3.f. Board Dimensions and Mounting Information The qik 2s9v1 measures 0.7" x 1.2" x 0.28" (17.8 x 30.5 x 7.1 mm) and weighs 0.07 oz (2.0 g) without the header pins installed. It has two mounting holes, one in each top corner. The holes have a diameter of 0.086" and are designed for #2 or M2 screws.. 4.a. TTL Serial The qik requires a logic-level (0 – Vcc, or “TTL”), non-inverted serial input connected to its serial receive line RX. The serial interface is asynchronous, meaning that the sender and receiver each independently time the serial bits; asynchronous serial is available in computer serial ports (though at non-TTL levels) and as hardware modules called “UARTs” on many microcontrollers. Asynchronous serial output can also be “bit-banged” by a standard digital output line under software control. The data format is 8 data bits, one stop bit, with no parity. also requires start and stop bits, each byte takes 10 bit times to transmit, so the fastest possible data rate in bytes per second is the baud rate divided by ten. At the maximum baud rate of 38,400 bits per second, the maximum realizable data rate, with a start bit coming immediately after the preceding byte’s stop bit, is 3,840 bytes per second. The voltage on the RX pin should not exceed Vcc. The qik will provide logic-level serial output on its serial transmit line TX in response to commands that request information. Information requests aways result in the transmission of a single byte per request. If you aren’t interested in receiving feedback from the qik, you can leave this line disconnected. Note: These lines are not compatible with RS-232 serial, which is inverted and uses voltages that would be out of spec (e.g. -12V to 12V). To connect the qik to an RS-232 device, you will need to use a converter such as our 23201a serial adapter, or a level shifter and inverter. 4.b. Baud Rates The qik can handle baud rates between 1200 and 38,400 bps. In its default state, the qik will start up in an automatic baud detection phase, where it waits for you to send it the byte 0xAA (170). The qik will detect the baud rate you are using from this byte and proceed to the normal operation phase. If you have the fixed-baud jumper in place, the qik will skip the autodetect phase and will instead immediately begin normal operation at a baud rate of 38,400 bps. Please see Section 3.d for more information. 4.c. Command Protocols Once the qik has entered the normal operation phase, you can control it by issuing serial commands. If your qik is set to automatically detect the baud, you must first send it the byte 0xAA (170). range from 128 – 255) while data bytes always have their most significant bits cleared (i.e. range from 0 – 127). This means that each data byte can only transmit seven bits of information. One significant improvement over earlier Pololu serial controllers is the qik’s error handling, which allows the user to specify responses to serial errors (which include bad commands, incorrectly formatted commands, or even hardware-level serial errors). The qik has a configuration parameter that, if set, will shut down the motors if a serial error occurs, but the qik itself will continue running and accepting commands. This is a safety precaution taken in case the serial error occurred during a command that was intended to stop the motors. The qik responds to two sub-protocols: Compact Protocol: will start with 0x8_ when using the compact protocol. Pololu 9, but this is a configuration parameter you can change. Any qik on the line whose device number matches the specified device number will accept the command that follows; all other Pololu devices will 9, we could send the following byte sequence: in hex: 0xAA, 0x09, 0x0D, 0x7F in decimal: 170, 9, 13, 127 Note that 0x0D is the command 0x8D with its most significant bit cleared. Since all compact-protocol command bytes start with 0x8n, these bytes will all turn into data bytes 0x0n. The qik will respond to both the Pololu and Compact protocols on the fly; you do not need to use a jumper or configuration parameter to identify which protocol you will be using. Procedure for Daisy-Chaining Daisy-chaining multiple qiks together on the same serial line is simple. Individually assign each qik a different device ID using the set configuration parameter command (see Section 5.c), and then connect your TTL serial transmit line to each qik’s RX line. If you wish, you can connect all of the qiks’ ERR lines to a single input on your controlling module. When you issue your first Pololu-protocol command, the qiks will all automatically detect the baud from the initial 0xAA byte. Connecting multiple serial outputs to one serial input is more complicated. Each device will only transmit. 5. Serial Commands 5.a. 0x81: Get Firmware Version Compact protocol: 0x81 Pololu protocol: 0xAA, device ID, 0x01 This command returns the a single ASCII byte that represents the version of the firmware running on the qik. All qiks produced so far have firmware version ‘1’ or ‘2’. Firmware version 2 makes a slight change to the LED feedback used during the automatic baud detection phase. If a serial byte other than 0xAA is received in this phase, or if 0xAA is transmitted at an invalid baud rate, firmware version 2 turns the red error LED on and keeps it on until the automatic baud detection phase ends. Firmware version 1 flashes the red LED very briefly if a serial byte other than 0xAA is received in this mode, which can make it difficult to tell that the qik detected any serial activity.). 5.c. 0x83 & 0x84: Get & Set Configuration Parameter The qik has four configuration parameters that are saved in non-volatile memory, and uses commands 0x83 and 0x84 to read and write these parameter values, respectively. The parameters are numbered as follows: Configuration Parameters - 0: Device ID This parameter determines which device ID the unit will respond to when the Pololu protocol is used. It has a default value of 9 (0x09 in hex) and can be set to any value from 0 – 127. When setting this parameter, you should only have one qik on your serial line at a time. - 1: PWM Parameter This parameter determines frequency and resolution of the pulse width modulation (PWM) signal used to control motor speed. Note that setting this parameter while the motors are running causes them to stop. The least significant bit (bit 0) selects for 7-bit resolution when cleared (i.e. full motor speed is 127) and 8-bit resolution when set (i.e. full motor speed is 255). A PWM with 7-bit resolution has twice the frequency of one with 8-bit resolution. Bit 1 of this parameter selects for high-frequency mode when cleared and low-frequency mode when set. Using high-frequency mode puts the PWM frequency outside the range of human hearing if you are also in 7-bit mode (or very close to it if you are in 8-bit mode), which can help you decrease motor noise. Using low frequency mode has the benefit of decreasing power losses due to switching. The default value for this parameter is 0 (high-frequency 7-bit mode, resulting in a PWM frequency of 31.5 kHz). Valid values for this parameter are: - 0 = high-frequency, 7-bit mode (PWM frequency of 31.5 kHz, which is ultrasonic) - 1 = high-frequency, 8-bit mode (PWM frequency of 15.7 kHz) - 2 = low-frequency, 7-bit mode (PWM frequency of 7.8 kHz) - 3 = low-frequency, 8-bit mode (PWM frequency of 3.9 kHz) - 2: Shutdown Motors on Error When this parameter has a value of 1, both motors M0 and M1 are stopped as a safety precaution whenever an error occurs; otherwise, if this parameter has a value of 0, errors will not affect the motors. For more information on the various types of errors that can occur, see Section 5.b. This parameter has a default value of 1 (shut down the motors on any error) and valid values for this parameter are 0 or 1. - 3: Serial Timeout When this parameter has a value of 0, the serial timeout feature is inactive. Otherwise, the value of this parameter controls how much time can elapse between receptions of valid command packets before a serial timeout error is generated. This can be used as a general safety feature to allow the qik to identify when communication with the controlling device is lost and shut down the motors as a result (assuming the shutdown motors on error parameter set to a value of 1). The timeout duration is specified in increments of 262 ms (approximately a quarter of a second) and is calculated as the lower four bits (which are interpreted as a number from 0 – 15) times two to the upper three bits (which are interpreted as a number from 0 – 7). If the lower four bits are called x and the upper three bits are called y, the equation for the length of the timeout duration would be: timeout = 0.262 seconds * x * 2y For example, if the timeout parameter is set as 0x5E (01011110 in binary), we have that x = 1110 (binary) = 14 (decimal) and y = 101 (binary) = 5 (decimal), which results in a timeout duration of 0.262s * 14 * 25 = 117 seconds. The maximum timeout duration (arising from a parameter value of 0x7F, or 127 in decimal) is 8.32 minutes and the minimum timeout duration (arising from a parameter value of 1) is 262 ms. This parameter has a default value of 0 (serial timeout disabled) and can be set to any value from 0 – 127. Command 0x83: Get Configuration Parameter Compact protocol: 0x83, parameter number Pololu protocol: 0xAA, device ID, 0x03, parameter number This command lets you request the current value of any of the four configuration parameters detailed above. This command will cause the qik to transmit a single byte that represents the requested parameter value. If you request an invalid parameter (i.e. if parameter number ≥ 4), the value transmitted by the qik should be 0xFF (255 in decimal) and a format error will be generated. Command 0x84: Set Configuration Parameter Compact protocol: 0x84, parameter number, parameter value, 0x55, 0x2A Pololu protocol: 0xAA, device ID, 0x04, parameter number, parameter value, 0x55, 0x2A This command lets you set the value of any of the four configuration parameters detailed above. The final two bytes of the command packets are format bytes that make it more difficult for this command to be unintentionally or accidentally sent, as might result from a noisy serial connection or buggy code. If either of the format bytes differs from the expected value, the command is ignored and a format error is generated. It takes the qik approximately 4 ms to finish processing this command, at which point the qik will transmit a single return byte that contains information about whether the process was successful. You should not send commands to the qik until you have received this return byte, or until at least 4 ms have elapsed. The return byte can have the following values: - 0: Command OK (success) - 1: Bad Parameter (failure due to invalid parameter number) - 2: Bad value (failure due to invalid parameter value for the specified parameter number) Failure will result in a format error. Once you have set the value of a configuration parameter, that value will be saved even if the unit is unplugged or reset.. 5.e. 0x88 - 0x8F: Set Motor Forward/Reverse The qik can independently control two bidirectional brushed DC motors, driving each either forward or reverse with either 7- or 8-bit speed resolution. In 7-bit mode, motor speed ranges from stopped to full speed as the speed parameter ranges from 0 to 127. In 8-bit mode, motor speed ranges from stopped to full speed as the speed parameter ranges from 0 – 255. The speed resolution can be controlled by the PWM configuration parameter (see Section 5.c). The motor direction convention used in this document is that “forward” corresponds to grounding the – pin while PWMing the + pin between VMOT and ground. “Reverse” corresponds to grounding the + pin while PWMing the – pin between VMOT and ground. Notions of “forward” and “reverse” are somewhat arbitrary. See Section 3.a for information about motor and power connections. Motor M0 Commands Commands 0x88 – 0x8B apply to motor M0. In 8-bit mode, commands 0x89 and 0x8B will set the motor speed to 128+motor speed; in 7-bit mode, command 0x89 is identical to command 0x88 and command 0x8B is identical to command 0x8A. For example, in 8-bit mode, the command packet 0x88, 0x7F will set motor M0 speed to 127 out of a maximum of 255, which will result in the motor’s turning at half speed. The command packet 0x89, 0x7F will set motor M0 speed to 127+128 = 255, which will result in the motor’s turning at full speed. In 7-bit mode, both commands will set motor M0 speed to 127 out of a maximum of 127, which will result in the motor’s turning at full speed. Command 0x88: Motor M0 Forward Compact protocol: 0x88, motor speed Pololu protocol: 0xAA, device ID, 0x08, motor speed Command 0x89: Motor M0 Forward (speed + 128; used in 8-bit mode) Compact protocol: 0x89, motor speed Pololu protocol: 0xAA, device ID, 0x09, motor speed Command 0x8A: Motor M0 Reverse Compact protocol: 0x8A, motor speed Pololu protocol: 0xAA, device ID, 0x0A, motor speed Command 0x8B: Motor M0 Reverse (speed + 128; used in 8-bit mode) Compact protocol: 0x8B, motor speed Pololu protocol: 0xAA, device ID, 0x0B, motor speed Motor M1 Commands Commands 0x8C – 0x8F apply to motor M1. In 8-bit mode, commands 0x8D and 0x8F will set the motor speed to 128+motor speed; in 7-bit mode, command 0x8D is identical to command 0x8C and command 0x8F is identical to command 0x8E. For example, in 8-bit mode, the command packet 0x8C, 0x7F will set motor M1 speed to 127 out of a maximum of 255, which will result in the motor’s turning at half speed. The command packet 0x8D, 0x7F will set motor M1 speed to 127+128 = 255, which will result in the motor’s turning at full speed. In 7-bit mode, both commands will set motor M1 speed to 127 out of a maximum of 127, which will result in the motor’s turning at full speed. Command 0x8C: Motor M1 Forward Compact protocol: 0x8C, motor speed Pololu protocol: 0xAA, device ID, 0x0C, motor speed Command 0x8D: Motor M1 Forward (speed + 128; used in 8-bit mode) Compact protocol: 0x8D, motor speed Pololu protocol: 0xAA, device ID, 0x0D, motor speed Command 0x8E: Motor M1 Reverse Compact protocol: 0x8E, motor speed Pololu protocol: 0xAA, device ID, 0x0E, motor speed Command 0x8F: Motor M1 Reverse (speed + 128; used in 8-bit mode) Compact protocol: 0x8F, motor speed Pololu protocol: 0xAA, device ID, 0x0F, motor speed some possible errors, such as an extra zero byte, that would not affect a checksum. When jumper B is in place, cyclic redundancy checking is enabled. In CRC mode, the qik expects an extra byte to be added onto the end of every command packet. The lower seven bits of this byte must be the 7-bit CRC for that packet, or else the qik will set its CRC Error bit in the error byte and ignore the command. The qik does not append any CRC information. 6.a. CRC Computation in C The following example program shows how to compute a CRC in the C language. The idea is that the CRC of every possible byte is stored in a lookup table, so that it can be quickly loaded when computing the CRC of a longer message. The individual CRC bytes are XORed together with the C operator ^ to get the final CRC of the message. In the example main() routine, this is applied to generate the CRC byte in the message 0x83, 0x01, that was used in Section 6. #include <stdio.h> const unsigned char CRC7_POLY = 0x91; unsigned char CRCTable[256]; unsigned char GetCRC(unsigned char val) { unsigned char j; for (j = 0; j < 8; j++) { if (val & 1) val ^= CRC7_POLY; val >>= 1; } return val; } void GenerateCRCTable() { int i, j; // generate a table value for all 256 possible byte values for (i = 0; i < 256; i++) { CRCTable[i] = GetCRC(i); } } unsigned char CRC(unsigned char message[], unsigned char length) { unsigned char i, crc = 0; for (i = 0; i < length; i++) crc = CRCTable[crc ^ message[i]]; return crc; } int main() { unsigned char message[3] = {0x83, 0x01, 0x00}; int i,j; GenerateCRCTable(); message[2] = CRC(message,2); for(i=0;i<sizeof(message);i++) { for(j=0;j<8;j++) printf("%d",(message[i]>>j)%2); printf(" "); } printf("\n"); return 0; }. 8. Arduino Library We have written a basic Arduino library for the qik dual serial motor controllers that makes it simple to interface the qik 2s9v1.
https://www.pololu.com/docs/0J25/all
CC-MAIN-2015-40
refinedweb
3,292
59.33
This article introduces a simple yet flexible way of creating a splash screen for Silverlight applications. One of my projects is to migrate a Windows Forms application to Silverlight. The business owners want to include a splash screen in it. Searching the internet, I found an article, "Navigating and passing values between XAML pages in Silverlight 2", by Nipun Tomar, discussing how to navigate among XAML pages in Silverlight. Based on this navigation method, a splash screen can easily be implemented. The following is a step by step introduction to adding a simple yet flexible splash screen to Silverlight applications. In Visual Studio 2008, follow the Microsoft instructions on how to "Create a New Silverlight Project" to create an empty Silverlight application, with a website to host the Silverlight application, and name the Silverlight project "SplashDemoApplication". By default, a solution is created, which is also named "SplashDemoApplication". In this solution, two projects are created by the wizard. One is the Silverlight project, and the other is the hosting website project called "SplashDemoApplicationWeb". By default, the "SplashDemoApplicationWeb" project is set as the Start Up project for running in Debug mode by Visual Studio. In order to have a web page run the Silverlight application in Debug mode in the Visual Studio environment, we can right click on the file "SplashDemoApplicationTestPage.aspx" in the Solution Explorer and set it as the start page. If we run the Silverlight application in Debug mode now, a web browser window will be launched, showing a blank screen, since we have not yet added anything to the Silverlight application. Since this article is not intended to discuss how to program WPF and XAML, we will add only a new XAML file called "Splash.xaml" to the project beyond the default files created by Visual Studio, which will be the splash screen in our demonstration. The "MainPage.xaml" added by default in Visual Studio 2008 will be the main Silverlight application page for the demonstration purpose. After adding "Splash.xaml" to the project, we will add a folder called "images" and put two pictures "NiagaraFalls.jpg" and "Dock.jpg" in the folder. Each picture will be embedded in one of the XAML pages. To make the XAML pages show something, we will add a picture in each of them. We will need to edit the two XAML files. We first add "NiagaraFalls.jpg" in the "Splash.xaml" file. <UserControl x:Class="SplashDemoApplication.Splash" xmlns="" xmlns: <Grid x: <Image Source="images/NiagaraFalls.jpg" Width="750" /> </Grid> </UserControl> And then, add "Dock.jpg" and some text in "MainPage.xaml". <UserControl x:Class="SplashDemoApplication.MainPage" xmlns="" xmlns: <Grid x: <Grid.RowDefinitions> <RowDefinition Height="60"/> <RowDefinition Height="42"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <TextBlock Grid. <TextBlock Grid.Row="1" Text="This is the main Silverlight user control displayed after the splash screen" HorizontalAlignment="Center" FontFamily="Verdana" FontSize="20" Foreground="Green" VerticalAlignment="Top" /> <Image Grid. </Grid> </UserControl> The starting point of the Silverlight application is the code-behind file of "App.axml". We will be modifying the default "App.xaml.cs" to let Silverlight load "Splash.axml" first and then switch to "MainPage.axml" after a short wait time, to achieve the splash effect. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SplashDemoApplication { public partial class App : Application { private Grid root; public void Navigate(UserControl NewPage) { root.Children.Clear(); root.Children.Add(NewPage); } public App() { this.Startup += this.Application_Startup; this.Exit += this.Application_Exit; this.UnhandledException += this.Application_UnhandledException; InitializeComponent(); } private void Application_Startup(object sender, StartupEventArgs e) { root = new Grid(); root.Children.Add(new Splash()); this.RootVisual = root; System.Threading.Thread Worker = new System.Threading.Thread( new System.Threading.ThreadStart(BackgroundWork)); Worker.Start(); } private void BackgroundWork() { System.Threading.Thread.Sleep(2000); Deployment.Current.Dispatcher.BeginInvoke(() => Navigate(new MainPage())); } } } In the above C# code, we added a private variable "root" of type "Grid", and a method "Navigate" in the "App" class. In the "Application_Startup" method, instead of directly adding the start up XAML page to the "RootVisual" like how Visual Studio created it for us by default, we first add it to the "root" Grid and then add the Grid to the "RootVisual". By doing this, we can navigate among different XAML pages simply by calling the "Navigate" method. Details about this navigation method can be found in "Navigating and passing values between XAML pages in Silverlight 2". root Grid Navigate App Application_Startup RootVisual When the Silverlight application runs, "Splash.xaml" will be first loaded and shown in the browser. The application will then start a background thread to call the BackgroundWork method. In this demonstration project, I just let this thread sleep for a while and then call "Navigate" to load "MainPage.xaml" to achieve the splash screen effect. BackgroundWork Compile and run the application. We can see that the "Splash.xaml" page is first loaded and the application then switches to "MainPage.xaml" after the thread sleeping time. The splash effect is achieved. Besides the navigation method introduced by Nipun Tomar, there are two things of interest. This is the first edition.
http://www.codeproject.com/Articles/47342/A-Simple-Flexible-Silverlight-Splash-Screen/?fid=1554358&df=90&mpp=10&sort=Position&tid=4073038
CC-MAIN-2015-22
refinedweb
871
52.05
Question: I am reading data from another system that returns XML that provides the following information for each field: "Field Name", "Data Type", and "Size". The "Data Type" returned is either: Alpha, LAlpha, RAlpha, CAlpha, or Numeric. Sometimes there are other attributes returned as well, such as Casing. I would like to create objects to model the data returned and also have to generate xml with element values formatted according to the given data type to send back to the other system to perform transactions. I started off creating an object that would represent each property on the object like: //Type T represents the data type of the Value property public class OtherSystemField<T> : IOtherSystemField{ public string OtherSystemFieldName { get; set;} public OtherSystemDataTypeEnum OtherSystemDataType { get; set;} public int Size { get; set;} public T Value { get; set;} public string ToOtherSystemString() { ....}; } //Class using the data field public OtherSystemEntityClass { public OtherSystemField<string> f1 { get; set; } public OtherSystemEntityClass () { f1 = new OtherSystemField<string>() { OtherSystemFieldName = "x", Size = 4, OtherSystemDataType = ...}; f1.Value = "DefaultStringValue"; } } The question is does this representation of the other system's data fields make the most sense, using this type of object to model a field from the other system instead of a .Net data type property that is associated with some meta-data?. Any opinions on, say, having the property have attributes containing these values like: public OtherSystemEntityClass { [OtherSystemFieldName("SomeFieldName", 5, OtherSystemDataTypeEnum.RAlpha)] public string f1 { get; set; } } Here is an example of the XML: <COLUMNS> <COLUMN header="FieldX" dspname="FieldX" dbname="FIELDX" type="NUMERIC" size="4" /> <COLUMN header="FieldY" dspname="FieldY" dbname="FIELDY" type="ALPHARIGHT" size="14"/> </COLUMNS> <COLS> <COL><![CDATA[ 1000]]></COL> <COL><![CDATA[ 102]]></COL> </COLS> I look forward to everyone's feedback - I have no doubts I will hear good perspectives. Performance is not of a huge concern, as the number of fields is relatively small. Also, this is implemented in .Net 3.5 Solution:1 I'm not sure what the "Alpha" types are, but the newly-added XML snippet is clearly describing a table schema. If you can pull off a mapping, I might actually use a DataTable instead of creating any custom classes at all. I wouldn't be too surprised to find out that the XML is literally serialized directly from something similar to a .NET DataSet/ DataTable but in a different language/platform. Those CDATA tags are not consumer-friendly. But if you can map Alpha values to some enum type (most likely a custom one you create), then you can just add a column of that type to a DataTable. Solution:2 Do you already know the Field Name, Data Type, Size, etc of your fields or is this something that you need to determine at run time? If you already know all the information about the fields at design time, then I like the attribute approach. I've done the very same when dealing with incoming Xml from old systems. You can then deserialize the Xml to your objects, and you're good to go. If you do not know the format of the Xml at design time, that is, you need to set the attribute values at run time, then using attributes will be more difficult than your first approach. You would need to set the attributes with reflection, which would be more work than just setting a property in the first solution. Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com EmoticonEmoticon
http://www.toontricks.com/2019/02/tutorial-recommended-implementation-for.html
CC-MAIN-2019-09
refinedweb
581
50.97
Git Commands Tutorial - Part 1 Git Commands Tutorial - Part 1 In this post, we introduce the basic git commands you need to know to successfully work with git. Read on to learn how to use git from the terminal! Join the DZone community and get the full member experience.Join For Free There are many different ways to use Git. The most common are the original command line tools and GUI ( Graphical User Interfaces). Here, we will cover the most important commands you should know about when you are working with Git. The command line is the only place you can run all Git commands. If you know how to run the command-line version you can probably also figure out how to run the GUI version. Also, while your choice of graphical client is a matter of personal taste, all users will have the command-line tools installed and available. You can read more on git's official online book. Before we start, be sure to know how to use the Terminal in Mac or Command Prompt or Powershell in Windows and have git installed on your system. Introduction First, you might ask yourself what is Git actually and what can you do with it? Git is a fast, scalable, distributed revision control system with a rich command set that provides both high-level operations and full access to internals. At Kolosek (where I work), we use Git for every application we create, including Ruby on Rails projects, to make it easier to work as a team and achieve our goal. You can learn a lot about individual Git commands by the running $git help command in the terminal. This should appear: Everything can be added to your git repositories, even your Controller tests! Git Options We will cover the most commonly used command lines, starting from Git options. This will explain everything you need to know about Git on your local machine: usage: git [--version] [--help] [-C <path>] [-c name=value] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p | --paginate | --no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] <command> [<args>] $git --version: Find out your current Git suite version using this command. $git --help: Every good programmer should know about this option, it will show you the most used Git Commands, and it can also print all available commands with --allor -a. $git -C <path>: Instead of running Git from the current working directory, you can run it from the given <path>instead. -C <path>command affects other options that expect path names like --git-dirand --work-treebecause their path names would be made relative to the working directory caused by the -Coption. $git -c <name>=<value>: You can very easily override values from your configuration files. The <name>has to be in the same format as listed by git config, while the <value>is your new parameter value. $git --exec-path[=<path>]: This command helps you find the path where your core Git programs are installed. Another way to do this is by setting the GIT_EXEC_PATHenvironment variable. $git --git-dir=<path>: Always use this option, whenever you need to set a path to the repository or set the GIT_DIRenvironment variable. And, that's it! For now, at least. This was only the first part of the tutorial! In the next one, we will cover all the other Git commands, be sure to stay tuned. }}
https://dzone.com/articles/git-commands-tutorial-part-1?fromrel=true
CC-MAIN-2019-35
refinedweb
575
61.56
Overview Introduction In Python, when building a framework or code generation tool, you might need to programmatically build a string representing the name of a module you want to import. How would you import a module if you have it's name as a string? Here's how to do it with importlib! Note that this feature was introduced in Python 3.1 but there is a 2.7 version of importlib though less featured. Learn more about how Python searches for imports, how the `PYTHONPATH` environment variable is used, and how to use `sys.path` in my Python import, sys.path, and PYTHONPATH Tutorial. Learn more about Python virtual environments which allow you to create isolated Python environments with different import paths with my Python Virtual Environments Tutorial. Use importlib to programmatically import modules The importlib provides a simple import_module function that accepts a string name with dot separators. It works just like a normal import except it uses a string to store the name. On import, the file is executed and the module object is returned. If you only need the code run on import it is not necessary to store the returned module. import importlib # Contrived example of generating a module named as a string full_module_name = "mypackage." + "mymodule" # The file gets executed upon import, as expected. mymodule = importlib.import_module(full_module_name) # Then you can use the module like normal mymodule.func1() mymodule.func2() Conclusion You should now know how to dynamically import modules using a module name stored in a string.
https://www.devdungeon.com/content/import-python-module-string-name
CC-MAIN-2021-04
refinedweb
253
57.77
Why does Python allow function calls with wrong number of arguments? Python is my first dynamic language. I recently coded a function call incorrectly supplying a wrong number of arguments. This failed with an exception at the time that function was called. I expected that even in a dynamic language, this kind of error can be detected when the source file is parsed. I understand that the type of actual arguments is not known until the function is called, because the same variable may contain values of any type at different times. But the number of arguments is known as soon as the source file is parsed. It is not going to change while the program is running. So that this is not a philosophical question To keep this in scope of Stack Overflow, let me phrase the question like this. Is there some feature, that Python offers, that requires it to delay checking the number of arguments in a function call until the code actually executes? Python cannot know up-front what object you'll end up calling, because being dynamic, you can swap out the function object. At any time. And each of these objects can have a different number of arguments. Here is an extreme example: import random def foo(): pass def bar(arg1): pass def baz(arg1, arg2): pass the_function = random.choice([foo, bar, baz]) print(the_function()) The above code has a 2 in 3 chance of raising an exception. But Python cannot know a-priori if that'll be the case or not! And I haven't even started with dynamic module imports, dynamic function generation, other callable objects (any object with a __call__ method can be called), or catch-all arguments ( *args and **kwargs). But to make this extra clear, you state in your question: It is not going to change while the program is running. This is not the case, not in Python, once the module is loaded you can delete, add or replace any object in the module namespace, including function objects. ★ Back to homepage or read more recommendations:★ Back to homepage or read more recommendations: From: stackoverflow.com/q/34567770
https://python-decompiler.com/article/2016-01/why-does-python-allow-function-calls-with-wrong-number-of-arguments
CC-MAIN-2019-26
refinedweb
359
70.84
- Some Google in Your Apps - Getting Started - A .NET Google Fight - Viewing Cached Pages in Java - Displaying a Cached Page - Just That Easy Viewing Cached Pages in Java For the Java example, let's delve a little deeper into the Google API with an application that presents the user with search results in a list, providing the ability to restrict the search between a set of dates. In addition, the user will be able to double-click any of the results and view a cached version of the page. This example uses another simple GUI (see Figure 3), this time written in Swing. Figure 4 shows an example of a simple search. Now let's take a look at the code to run the search: protected void doSearch() { String searchString = getSearchBox().getText(); int startJulDate = -1; int endJulDate = -1; DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy"); Date startDate = null; Date endDate = null; Calendar startCal = null; Calendar endCal = null; int month = -1; int day = -1; int year = -1; //Returns true if the checkbox is ticked if(getUseDates()) { //Attempt to parse the provided dates try { startDate = dateFormat.parse(getFromDateBox().getText()); } catch(Exception e) { error("The start date entered (" + getFromDateBox().getText() + ") is not a valid date"); } try { endDate = dateFormat.parse(getToDateBox().getText()); } catch(Exception e) { error("The end date entered (" + getToDateBox().getText() + ") is not a valid date"); } //If we were able to parse the dates, append them onto the search if((startDate != null) && (endDate != null)) { //Google requires that all dates be in the Julian // form, i.e. days since 4713 B.C. startCal = new GregorianCalendar(); startCal.setTime(startDate); endCal = new GregorianCalendar(); endCal.setTime(endDate); startJulDate = getJulian(startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH)+1, startCal.get(Calendar.DAY_OF_MONTH)); endJulDate = getJulian(endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH)+1, endCal.get(Calendar.DAY_OF_MONTH)); //Use the "daterange:" keyword to searchString += " daterange:" + startJulDate + "-" + endJulDate; } else { return; } }); } } There's a lot going on here, including some logic to parse the dates and convert them to Julian format. A Julian counts the number of days since January 1, 4713 B.C. Converting a Gregorian date to Julian is somewhat complicated, but the formula is readily available online. Here's a method that does it: public int getJulian(int year, int month, int date) { int a, b, c, e, f; a = year / 100; b = a / 4; c = 2 - a + b; e = (int)(365.25 * (year + 4716)); f = (int)(30.6001 * (month + 1)); return (int)(c + date + e + f - 1524.5); } Once you have the numeric representation of the date, you can just concatenate daterange: startDate-endDate onto the end of your search string. Let's go back to the doSearch() method. The last try/catch block is where much of the work happens:); } The getSearch() method returns the global GoogleSearch instance, which encapsulates the Google API calls. The query string in this case is the text that was entered in the text box, plus the optional date qualification. We set the string in the GoogleSearch instance; we also store it in a global variable, as we may need it later. The doSearch() method performs the search, returning a GoogleSearchResult object that contains an array of GoogleSearchResultElements we can drop directly into our JList. By default, the JList displays an ugly textual representation of the GoogleSearchResultElement, but creating a custom ListCellRenderer will display the URL instead. The final task is to store the index of the last GoogleSearchResultElement that's displayed, in this case 10. We'll need to start here to retrieve the next set of search results if the user clicks the >>> button. As mentioned earlier, you can only retrieve 10 search results at a time; retrieving the next 10 requires another search. This is the method that the >>> button calls when clicked: protected void shiftRight() { try { //Search with the last string getSearch().setQueryString(getLastSearchString()); //Indicate to start at the last result getSearch().setStartResult(getSearchIndex()); setLastResult(getSearch().doSearch()); getResultsList().setListData(getLastResult().getResultElements()); setSearchIndex(getLastResult().getEndIndex()); } catch(Exception e) { error("Exception from Google: " + e); } } We're using the same search string here as before, but now we're specifying setStartResult() to be the value of the last index of the last search, so our new set of results will begin with the next result. We update the JList again with the new results, and set our new index. The shiftLeft() method looks very similar, subtracting 10 from the index before running the search. If you're familiar with Swing, you know that its single-threaded nature can make your GUI stop responding when something is happening in the background. Since the Google searches generally take a second or two to complete, you'd do well to use something like XXX!!! to handle multithreading, to prevent your application from hanging while the search is in process. Additionally, a simple cache of GoogleSearchResultElements would make navigating through the list much faster.
http://www.peachpit.com/articles/article.aspx?p=381390&seqNum=4
CC-MAIN-2015-18
refinedweb
811
53.81
reverse a string - word by word It says the solutiojn can be achieved by first reversing the string normally, and then just reversing each word. Can anybody share their C implentation for this? For example using recusion, using induction etc. Also can it handle adjacent (multiple) spaces between words? Thx Gerald Wednesday, September 18, 2002 Why? So we can do your homework for you? :) Michael H. Pryor Wednesday, September 18, 2002 I would also be VERY interested in a C program capable of doing induction, and applying _that_ to manipulating pointers :-) Yo Friday, September 20, 2002 Once you have the whole string, you can do this: 1. Go to the start of the string. 2. Skip all leading whitespace. 3. when you encounter the first non-whitespace character, save the pointer to the beginning of the word. 4. go until you find the end of the word. 5. save the end of the string in a temp var 6. pass the pointer to the begin of the word and the pointer to the end of the word and the pointer to the string to your reversestring() function. 7. your string should now have the first word in the correct order. 8. repeat from step 2 on, using the pointer saved in step 5 as your new beginning ptr. And repeat until you get to '\0' Tim Tuesday, September 24, 2002 Not being a C programmer, I have little insight into pointers cetera. But look at the Python code I have pasted below. Great language to express algorithms like these... # my own little reversing fn def reverse1(str): front = 0 back = len(str) - 1 s = list(str) while front < back: s[front],s[back] = s[back],s[front] front, back = front + 1, back - 1 return string.join(s,'') # reversing string, word by word def reverse3(str): str = reverse1(str) words = string.split(str) revwords = [] for w in words: revwords.append(reverse1(w)) return string.join(revwords) # same thing, using Python fns def reverse4(str): wordlist = string.split(str) wordlist.reverse() return string.join(wordlist) Anirudh Moudgal Monday, October 28, 2002 Reversing a string can also be expressed recursively: the reverse of a string is got be appending the reverse of the 1..n characters with the 0th character. So it's an interesting question you can ask after asking the interviewee an algorithm for calculating the factorial of an integer. Here is some Python code that does that: def reverse(str): """Recursively reverse a string""" if len(str)==1: revstr=str else : revstr=reverse(str[1:])+str[0] return revstr Recent Topics Fog Creek Home
https://discuss.fogcreek.com/techinterview/846.html
CC-MAIN-2020-05
refinedweb
434
65.62
18 May 2007 13:44 [Source: ICIS news] TAIPEI (ICIS news)--Rohm and Haas will restart its 790m lbs/year (358,337 tonne/year) methyl methacrylate (MMA) facility in ?xml:namespace> The facility was initially scheduled for a four-week annual maintenance until 11 May, but unexpected minor mechanical issues delayed its start-up by one week. “In addition, one of our reactors was damaged by a heavy thunderstorm late last week,” said the official at the sidelines of the Asia Petrochemicals Industry Conference. Although the plant was ready to resume commercial production in the next one or two days, total production loss over the entire time period was estimated at 7,000-8,000 tonnes. The impact on MMA prices in the US MMA contract prices for the second quarter were stable at up to 117.5 cents/lb FD (free delivered) railcar, and 119.5 cents/lb FD tank truck during the week ended 11 May, according to global chemical market intelligence service ICIS pricing. Other suppliers said they believed that Rohm and Haas would face some difficulties in fulfilling contractual cargoes to its customers in Asia. The US producer declined to comment on
http://www.icis.com/Articles/2007/05/18/9030346/apic-07-rohm-haas-to-restart-deer-park-mma.html
CC-MAIN-2014-35
refinedweb
196
51.07
== For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object. Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared. ValueType However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version. To illustrate that, here's an example: using System; public class Test { static void Main() { // Create two equal but distinct strings string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); Console.WriteLine (a==b); Console.WriteLine (a.Equals(b)); // Now let's see what happens with the same tests but // with variables of type object object c = a; object d = b; Console.WriteLine (c==d); Console.WriteLine (c.Equals(d)); } } The results are: True True False True The third line is False because the compiler can only call the non-overloaded version of == as it doesn't know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false. False c d So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly. For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with. [Author: Jon Ske _
http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx?PageIndex=2
CC-MAIN-2014-52
refinedweb
413
59.13
"The" It then says I should use - Code: Select all // my first program in C++ #include <iostream> using namespace std; int main () { cout << "Hello World!"; return 0; } And then it explains line by line what each thing does. But the problem is I know absolutely no C++ yet and so all the explanations went over my head. I figured if I understood why instead of just how I would become a much better programmer. So first, what do I need to download to write in c++? The tutorial seems to say I have to have a compiler to write c++ code but I thought a complier is essentially a code translator, so that some high level code can be ran in some lower level language. Is there something equivalent to IDLE for python, but for C++? Second, what is a C++ console? Lastly, could you explain what each line in "my first program" does, and more importantly, why it's needed to get the end result? Like, what would happen and why if "#include <iostream>" (for example) was taken out? Also, if it helps at all I have some python experience and I'm using a mac. Thanks a lot in advance --thty
http://www.hackthissite.org/forums/viewtopic.php?f=102&t=10232
CC-MAIN-2015-40
refinedweb
203
79.8
I've been kicking the Spiceworks wheels on my home network for a while, now I'm testing at the office. During my initial inventory scan, I'm getting this message for my primary domain controller (2003): Authentication failed for user [domain admin] This user doesn't have the proper credentials required to access this machine. FWIW, before SW I tried doing a quick scan with SYDI server (a VBScript tool), and it also had issues scanning this server. Any suggestions?! 10 Replies Jan 18, 2012 at 8:23 UTC Step 3 of this how-to, test your credentials against a machine, http:/ See what it returns. You may need to try a different combo like username or try domain\username -Jay Jan 18, 2012 at 8:55 UTC I used the same credentials for every other machine - this is the only one with a problem.... but I'll try different combinations and see what happens. In the meantime... I went through http:/ wmic /user:domain\administrator /password:password /node:domaincontroller systemclosure get serialnumber systemclosure - Alias not found. I'll continue working through these suggestions as I find time today. Thanks!! Jan 18, 2012 at 5:19 UTC No other password combination works... This is the primary domain controller for the domain - and I'm using the domain admin credentials. I'm concerned about the "Alias not found" message... but am going to work through the remainder of the How To link you shared. Jan 19, 2012 at 5:58 UTC Sounds good Brian, let me know if you run into any snags. -Jay Jan 19, 2012 at 6:08 UTC I didn't have any luck getting it working yesterday. But we have scheduled some server reboots today anyway, so I figured I'd see if that made any difference and continue troubleshooting if it doesn't. Jan 19, 2012 at 3:02 UTC WMIDiag returned this error, but I'm not clear exactly how to resolve it: 33421 12:39:47 (1) !! ERROR: Actual trustee 'NT AUTHORITY\NETWORK SERVICE' DOES NOT match corresponding expected trustee rights (Actual->Default) 33422 12:39:47 (0) ** - ACTUAL ACE: 33423 12:39:47 (0) ** ACEType: &h0 33424 12:39:47 (0) ** ACCESS_ALLOWED_ACE_TYPE 33425 12:39:47 (0) ** ACEFlags: &h12 33426 12:39:47 (0) ** CONTAINER_INHERIT_ACE 33427 12:39:47 (0) ** INHERITED_ACE 33428 12:39:47 (0) ** ACEMask: &h13 33429 12:39:47 (0) ** WBEM_ENABLE 33430 12:39:47 (0) ** WBEM_METHOD_EXECUTE 33431 12:39:47 (0) ** WBEM_WRITE_PROVIDER 33432 12:39:47 (0) ** - EXPECTED ACE: 33433 12:39:47 (0) ** ACEType: &h0 33434 12:39:47 (0) ** ACCESS_ALLOWED_ACE_TYPE 33435 12:39:47 (0) ** ACEFlags: &h12 33436 12:39:47 (0) ** CONTAINER_INHERIT_ACE 33437 12:39:47 (0) ** INHERITED_ACE 33438 12:39:47 (0) ** ACEMask: &h33 33439 12:39:47 (0) ** WBEM_ENABLE 33440 12:39:47 (0) ** WBEM_METHOD_EXECUTE 33441 12:39:47 (0) ** WBEM_WRITE_PROVIDER 33442 12:39:47 (0) ** WBEM_REMOTE_ACCESS 33443 12:39:47 (0) ** 33444 12:39:47 (0) ** => The actual ACE has the right(s) '&h20 WBEM_REMOTE_ACCESS' removed! 33445 12:39:47 (0) ** This will cause some operations to fail! 33446 12:39:47 (0) ** It is possible to fix this issue by editing the security descriptor and adding the removed right. 33447 12:39:47 (0) ** For WMI namespaces, this can be done with 'WMIMGMT.MSC'. 33448 12:39:47 (0) ** 33449 12:39:47 (0) ** WMI namespace security for 'ROOT/ASPNET': ........................................................................... MODIFIED. 33450 12:39:47 (1) !! ERROR: Actual trustee 'NT AUTHORITY\LOCAL SERVICE' DOES NOT match corresponding expected trustee rights (Actual->Default) 33451 12:39:47 (0) ** - ACTUAL ACE: 33452 12:39:47 (0) ** ACEType: &h0 33453 12:39:47 (0) ** ACCESS_ALLOWED_ACE_TYPE 33454 12:39:47 (0) ** ACEFlags: &h12 33455 12:39:47 (0) ** CONTAINER_INHERIT_ACE 33456 12:39:47 (0) ** INHERITED_ACE 33457 12:39:47 (0) ** ACEMask: &h13 33458 12:39:47 (0) ** WBEM_ENABLE 33459 12:39:47 (0) ** WBEM_METHOD_EXECUTE 33460 12:39:47 (0) ** WBEM_WRITE_PROVIDER 33461 12:39:47 (0) ** - EXPECTED ACE: 33462 12:39:47 (0) ** ACEType: &h0 33463 12:39:47 (0) ** ACCESS_ALLOWED_ACE_TYPE 33464 12:39:47 (0) ** ACEFlags: &h12 33465 12:39:47 (0) ** CONTAINER_INHERIT_ACE 33466 12:39:47 (0) ** INHERITED_ACE 33467 12:39:47 (0) ** ACEMask: &h33 33468 12:39:47 (0) ** WBEM_ENABLE 33469 12:39:47 (0) ** WBEM_METHOD_EXECUTE 33470 12:39:47 (0) ** WBEM_WRITE_PROVIDER 33471 12:39:47 (0) ** WBEM_REMOTE_ACCESS Jan 19, 2012 at 3:03 UTC Also - I've seen several references to scripts and such that delete the WMI repository. I'm leery to attempt this, as numerous references from MS (TechNet, etc.) say that it can be dangerous and should be a last resort. This *is* a production domain controller.! Jan 19, 2012 at 3:08 UTC lol, no worries, the link I posted at top in step 5 has two scripts that will attempt to repair WMI issues if you see anymore or still suspect it is a problem. -Jay Jan 19, 2012 at 3:14 UTC Thanks for your help! I'm the new sysadmin here, and am slowly getting up to speed (this is day 13). I've got a bunch more inventory issues to work through, so I'll probably be back. :)
https://community.spiceworks.com/topic/191559-initial-inventory-authentication-failed-for-user-domain-admin
CC-MAIN-2017-22
refinedweb
864
56.29
- Training Library - DevOps - Courses - Introduction to Knative Knative Serving: Welcome back. In this lesson I'm going to introduce you to the Knative Serving component, explaining how it works and how and when to use it. Knative Serving provides flexible features for application scaling and routing. With the Knative Serving component installed you'll have the ability to: One, automatically deploy applications with public routes in one hit. Two, maintain point in time snapshots of deployments. Three, configure automatic pod scaling, including scale to zero and four, perform traffic splitting enabling blue green deployments. The Knative Serving component provides the following resources, service, route, configuration and revision. These resources work together to ease the burden of setting up and managing Nubrik routes to your serverless workloads. A Knative Service is distinct and different to the standard Kubernetes Service. Installing the Knative Serving component results in another resource named Service, which provides a different perspective on the concept of a service. The Service defines the container image to run, how it should scaled, and can even define routing and traffic splitting options. When you create a Knative Service, multiple resources get created as displayed in this diagram. Creating a service resource creates both Route and Configuration resources, both of which are directly managed by the Service itself. The Configuration resource maintains a history of Revisions with the Route resource being configured to route traffic to by default, the latest revision, although this routing behavior can be altered. Every time you modify the Service a new revision of the configuration is automatically snap-shotted, providing a point in time record of the configuration. Revisions are immutable objects that exist indefinitely or until such time that they are no longer of use. The following Service resource illustrates just how easy it is to create a new service which when deployed into your Kubenetes cluster wires up all of the networking including making it externally callable by default. Expanding on the previous Service resource, we could for example add in some traffic splitting to split traffic across two named revisions like so: with the traffic splitting capabilities exposed directly within the Service resource, it now becomes trivial to perform blue/green deployments. To do so you would simply start off by deploying two revisions of the service, and having 100% of the traffic going to the blue revision. You can then update the routing configuration on the Service to spit the traffic 50/50 across both revisions. This will allow you to test and observe the behavior before committing all traffic to the green revision. Once confirmed that the green revision is behaving as expected, you can again update the Service routing to split traffic 100% exclusively to the green revision. If the green version did not accomplish what it was designed to do, roll backing to the previous version is simple, with 100% of the traffic being delivered back to the blue version. The key point here to highlight is that this blue/green traffic splitting capability exposed within the Knative Service can be leveraged directly by developers themselves, which is extremely useful when it comes to rolling out updates to production. It removes all the pain points and administration burden involved with running side-by-side versions of production. Knative services are by default setup with publicly accessible HTTP endpoints and routes. When a Knative service is deployed, it will be immediately available to use from anywhere outside of the cluster over the Internet. Each deployed Knative service is given its own FQDN, Fully Qualified Domain Name, which follows the following format. For example, if our Knative setup is configured with the custom domain cloudacademydevops.com, and we install two Knative services, named ShoppingCart and Payment into the CloudacAdemy namespace within the cluster, then both services would be contactable with the following HTTP endpoints. Each deployed service can additionally be tagged such that the tag also becomes part of the service's FQDN. For example, if we deployed the following payment service which has two revisions: payment-v1, tagged as prod, and payment-v2 tagged as staging, then both revisions can be contacted directly using the Fully Qualifies Domain Format tag-servicename.namespace.domain. Keep in mind that when using the tag expanded FQDN Traffic splitting will not in effect which makes sense. Knative serving can be easily set up to serve using a custom domain. To do so, you need to update the domain within the config domain config map located in the Knative serving namespace. For example, if we wanted to configure the domain to be the custom domain cloudacademydevops.com, then the following configmap setting would be applied. Next, you need to determine the public IP address for the Kubernetes cluster. To do so, you can query the address by interrogating the istio ingress gateway service located within the istio system namespace. The following example uses a jsonpath to navigate within the response to the ingress's assigned public IP address. Finally, you need to add a new wildcard A, record into your DNS zone for the domain in question. The wildcard needs to be setup to include the cluster namespace. Therefore, if our cluster's namespace were to be CloudAcademy, then the following wildcard A record would be entered, where 52.188.75.20 is the public IP address assigned to the istio ingress gateway, and as determined by the previous commands. Another extremely useful feature that Knative Serving brings to the table is the concept of scale to zero. Scaling to zero is the idea that when your serverless application has no demand on it, then the serverless components should scale themselves all the way back to zero. In the Knative world, this would result in all pods for a particular service being removed from the cluster. Scaling to zero in a Kubernetes cluster has the advantage of freeing up cluster resources for other applications and workloads, and in the serverless world you don't waste money on running idle processes. At the other end of the scaling spectrum you may have unpredictable bursts of activity and that requires your serverless application to scale upwards. To accomplish automatic pod scaling in either direction, Knative introduces the Knative PodAutoscaler, KPA, which is designed to automatically scale pods in either direction, and provides fast request-based auto scaling capabilities out of the box. Now, Knative can be configured to use the Kubernetes default horizontal pod auto scaler, HPA, if you prefer to run with that one. And beyond this it even provides a plug and play option for custom-created pod auto scalers. The following example shows how to configure a Service with a scale to zero policy. This example will use concurrency request-based routing behavior provided by the Knative Pod Autoscaler. When sustained bursts of activity come in, the Service will scale out the pods to a maximum of 20. As activity begins to drop off, pods will start to be removed one-by-one, all the way back down to zero if all activity has stopped. Okay, that concludes this lesson. In summary, you learnt that the Knative Serving component provides a number of middleware primitives that collectively help to route and scale your Kubernetes hosted serverless workloads. Go ahead and close this lesson and I.
https://cloudacademy.com/course/introduction-to-knative/knative-serving/
CC-MAIN-2021-17
refinedweb
1,220
50.97
OpenShift cluster tests 05/08/18 We subject our clusters to a lot of automated tests in the widest sense – monitoring, health checks, load tests, penetration tests, vulnerability scans, the list goes on – but every so often I come across test cases that are not well served by any of them. They are usually specific to the way a cluster is used, or how the organisation operating it works. Sometimes there is no objectively correct or incorrect answer, no obvious expected value to specify in our assert statements. I will look at three examples to explain why I think these tests are worth your while. The first test concerns the OpenShift default of letting all authenticated users create (or, more accurately, request) projects. Let’s say we want to deny non-admin users this power. How do we make sure we have complied with this rule? Second, our architecture may require an application scaled to three pods to be distributed across three data centre zones for high availability. We need a test that shows that the built infrastructure matches the architectural requirement. Third, let’s assume we have just experienced an unplanned downtime. Communication between two projects has failed. Clearly remediation comes first, but how would the administrator go about writing a test that makes sure the pod network is configured correctly? The three scenarios have a number of things in common. Each requires direct access to the cluster state held in the master’s etcd database. That interaction alone ensures that these are not inexpensive tests in performance terms. Broadly speaking, these tests should run daily, preferably at a time of reduced load, not every hour of the day. Running them is perhaps most useful after cluster maintenance or upgrades. We will look at sample implementations of these tests in just a moment. How much work will creating tests like these involve? Thankfully, very little. If we are unsure what to test, a quick glance at our operational guidelines or architecture documentation will help us get started. Writing tests will come naturally to anyone familiar with OpenShift, and should take no more than five minutes in most cases. Kubernetes gives us all the tools we need to implement our test runner. Test setup The CronJob object triggers nightly test runs. The payload is a lightweight single-container pod with Kate Ward’s unit test framework shUnit2, oc client, and assorted tools ( curl, psql, mysql, jq, awk). All test data is taken from a ConfigMap mounted at launch. The ConfigMap in turn is generated from a folder of test scripts in Git. We will return to the scripts in just a moment. For now the CronJob object waits for the appointed hour, then triggers a test run. shunit2 processes the test suite (consisting of all test scripts in /etc/openshift-unit.d) and then reports results. Due to a limitation of the CronJob API prior to Kubernetes 1.8, the pod reports success (zero) even in case of errors as returning an error leads to constant redeployments and considerable load on the cluster. From a permissions point of view, administrator access is required to create the project initially, but from that point onward the service account is read-only and the container runs with the ‘restricted’ security context constraint and a non-privileged security context. Logs are written to standard output and so managed by the existing log server. Using only the default suite of tests, the test pod reports the following: test_nodes_ready test_nodes_no_warnings test_project_quotas test_cluster_admin_bindings test_container_resources test_security_context_privileged test_high_availability test_anyuid test_self_provisioner Ran 9 tests. OK These tests are just placeholders, however. The tests that matter are the ones that reflect your organisation’s individual rules, guidelines and decisions. Roles and permissions Let’s return to the first example mentioned in the introduction, that is, the self-provisioner rule. It ensures that the administrator has taken the corresponding cluster role from the groups system:authenticated and system:authenticated:oauth, which usually means that an administrator has issued the following command: $ oc adm policy remove-cluster-role-from-group \ self-provisioner \ system:authenticated system:authenticated:oauth cluster role "self-provisioner" removed: ["system:authenticated" "system:authenticated:oauth"] Using the oc tool, verifying that this has not been forgotten or reversed at a later point, is as straightforward as asking who is entitled to create (the verb) projectrequests (the resource): test_self_provisioner() { count_self_provisioner=`oc adm policy who-can \ create projectrequests | \ grep -c system:authenticated` assertEquals " non-admin users may not create project requests;" \ 0 ${count_self_provisioner} } suite_addTest test_self_provisioner The shUnit2 framework intrudes only very slightly on the code here. The utility function suite_addText allows the framework to combine many files in a test suite with a single return value. The test code must reside in a function whose name contains the word test. The writer also needs to be familiar with the framework’s assert functions, assertEquals in this case. Placing a space at the start of the string and a semicolon at the end are conventions that make error messages more legible: test_self_provisioner ASSERT: non-admin users must not create project requests; expected:<0> but was:<1> Whereas most infrastructure tests strive for objectivity and test coverage, cluster tests like this one are unrepentantly subjective and selective. A comparison with rspec-puppet tests is instructive. Here is a brief excerpt from a Puppet manifest with matching rspec-puppet test: class bastion::install { file { '/home/ec2-user/config.json': ensure => file, owner => 'ec2-user', mode => '0644', content => template('bastion/config.json.erb'), } } The test asserts the following: context 'in class Install' do it { should contain_file('/home/ec2-user/config.json') .with_ensure('file') .with_owner('ec2-user') .with_mode('0644') } end This approach makes it much harder to argue that some properties (e.g. users with basic-user credentials are allowed to create projects) are more important than others (e.g. there’s a JSON file which is read-only unless you are the owner). If we place the two tests side by side, we are reminded that rspec-puppet strives for full map coverage, whereas we are focused on points of interest. These points of interest may seem arbitrary, but so, perhaps, are the decisions and operational guidelines they support and reinforce. Architecture How to test for high availability, the second example outlined in the introduction? Anti-affinity rules give us fine-grained control over placement on nodes, but unless we only have one node per zone, we cannot rely on the scheduler alone here. One alternative approach is to identify the nodes and examine the zone label: test_high_availability() { for svc in docker-registry router do nodes=`oc get po --all-namespaces -o wide | grep ${svc} | \ awk '{ print $8 }'` zones="" for node in ${nodes}; do zones="${zones} `oc get node/${node} -L zone | awk '{print $6}' | tail -n +2`" done zone_count=`echo ${zones} | tr ' ' '\n' | sort -u | wc -l` ha=false if [ "${zone_count}" -gt "2" ]; then ha=true fi assertTrue " ${svc} must be distributed across three zones;" ${ha} done } suite_addTest test_high_availability As before, we start with plain oc requests and refine the output using basic command line tools. The label zone expresses anti-affinity, the label region affinity: services are spread out across zones and concentrated in regions. We fetch the nodes first (note the use of the wide switch), then extract the zone from the node definition before counting the number of unique zones. The expected number is three. Post-incident review So far, operational guidelines and architectural decisions have directed our test selection. Incidents are another valuable guide. Making sure they occur only once trumps trying to anticipate weaknesses in our infrastructure. For example, our multi-tenant cluster might contain a project alice which accesses a project bob using a pod network join: $ oc adm pod-network join-projects --to=bob alice Let’s assume that the join between the two projects has been lost. Perhaps an additional join from alice to eve was created. The fact that one (the original join is gone) does not intuitively follow from the other (an apparently unrelated new join was created) makes this all the more likely. Affected services then run into timeouts and stop processing requests. The problem is quickly diagnosed and fixed, but having suffered one service failure, we really ought to write a test that alerts us should the join disappear again: test_join_alice_bob() { count_net_ids=`oc get netnamespace | \ grep 'alice\|bob' | \ awk '{ print $2 }' | \ sort -u | \ wc -l` assertEquals " join between alice and bob is broken;" \ 1 ${count_net_ids} } suite_addTest test_join_alice_bob To follow the test, we need to appreciate what happens when oc adm pod-network join-projects is called: the source project’s network ID is changed to that of the destination project. Once the two projects share a network ID, they can communicate with each other. (Hence the unfortunate side-effect of creating an additional join from project alice to eve: alice receives the network ID of eve and can no longer reach services in project bob.) The test only has to fetch the network IDs of alice and bob, de-duplicate and count lines. If the join is still in place, the line count will be one. Choosing a language In case you are wondering why this is not a Go application, I have to confess to some library envy. Clearly the command line component would have been much more elegant, for example, and there is more repetition in the tests than I would like. The exports script seeks to address this by bundling frequently used queries such as ‘list all projects created by users’, but that does not make up for the fact that we give up the luxury of one-line web servers, Bootstrap reports adorned with canvas charts, parallel execution for oc and non- oc test cases, and so on. Those quibbles, however, hardly justify switching to a different language. If we were to do so, which language should we choose? Go? JavaScript? Python? Ruby? Each of these choices would exclude many users who happen to have prioritised other languages. Shell scripting is familiar to most OpenShift users and a natural extension of the way they interact with OpenShift anyway. Nearly everything of substance in our tests, moreover, relies on oc calls; no standard library can abstract away the fundamental awkwardness of building an application around system calls. They only feel entirely natural in a shell environment. Shorter paths, fewer destinations Many tests are essential. The ones we have considered here, strictly speaking, are not. It comes down to an individual assessment of risk and usefulness. Personally, I am much more willing to grant anyuid powers to a service account if I know the next nightly test will fail should I forget to remove them later. Sometimes safety nets get in the way, but they can also have a liberating effect. This approach allows us to specify test conditions at the appropriate level and above all quickly, with minimal investment in infrastructure and training. The goal is the shortest path to a small number of valuable points of interest, not comprehensive map coverage: sightseeing, not cartography. You may also find that there is nothing that colleagues cannot express more succinctly and elegantly than you thought possible, especially in the world of Bash. Learning from other people’s tests may be, for me, the most enjoyable aspect of it all. For those still undeterred, log into your administrator’s account and set the timer: $ git clone $ make -C openshift-unit
https://blog.codecentric.de/en/2018/05/openshift-cluster-tests/
CC-MAIN-2018-39
refinedweb
1,907
51.07
91 Downloads Updated 01 Sep 2016 This package contains a guide that explains, in a step-by-step fashion, how to develop device driver blocks (blocks that perform target-specific functions when executed on a target platform). Example drivers for: -) Arduino digital output -) Arduino digital input -) Arduino analog output -) Arduino encoder read are included. While the examples are built using the Arduino as the hardware platform (specifically relying on the Simulink Support Package for Arduino), the method applies to any other supported target. In this guide, the first method to develop device drivers is based on the S-Function Builder block. Following chapters also describe different methods based respectively on the Legacy Code tool, the MATLAB function block, and the System Object block. Advantages and disadvantages of each method are discussed in the guide. Finally, note that for MATLAB 2013b you will need to apply a fix for the S-Function builder to develop blocks with no input. To do so, go to the following page: , scroll down to the bottom, and follow the instructions therein.) Hello, Thanks for the great job Giampiero! I've tried the samples on Uno with 2015a and it works perfectly. Now I try to write a CAN driver for the CAN-BUS shield. First, I'd like to make an init function to set the CAN speed with a Matlab system block. This block has no I/Os, but when I try to update the model, I get: MATLAB System block 'can_test/MATLAB System' error occurred when invoking 'isOutputFixedSizeImpl' method of 'CANSetup'. The error was thrown from ' 'C:\Program Files\MATLAB\R2015aSP1\toolbox\simulink\simulink\+SLStudio\ToolBars.p' at line 1175'. Reported by CANSetup: Incorrect number of outputs for the isOutputFixedSize method; 1 were requested, but the method returns 0, as specified by the getNumOutputs method. I don't understand, since I've put num = 0 for both getNumOutputsImpl and getNumInputsImpl functions. Then I need to include the CAN and SPI libraries. How can I do that with the system block method? Thank you. Giampiero Campa (view profile) Ok, great ! Thanks ! I'm going to try too then, at some point (maybe in a few weeks or so) just out of curiosity... Thanks again. G. Marcell (view profile) Thanks for you response. I tried it before I wrote the comment and it worked normally without the need to rebuild the S-Function every time the sample time or the parameters are changed. However, just to make sure I checked it again right now but it works for me. Giampiero Campa (view profile) Hi Marcell, thanks for the feedback. You can certainly place the S-Function Builder block in a subsystem and write a mask for it, and you can use it to pass "normal" parameters (the ones defined as such in the data properties pane). This will work as these parameters are read from the mask and passed down to the S-Function before each execution. However, I'm pretty sure that both the Sample Time and the initial conditions, which are defined in the initialization pane, are hardcoded in the executable (and the TLC file) every time you press the "Build" button in the S-Function builder. Therefore, if you encapsulate the S-Function Builder block in a subsystem, build a mask for it, and change the sample time in this mask, I am afraid that the change will NOT get propagated down until you rebuild the S-function (so you - or the user - have to look under the mask, double click the S-Function Builder block, and click on "Build". I think that doing so is misleading for the user, who might think that the sample time gets propagated down without any problem every time it gets changed from the upper level mask. Now, that being said, I haven't explicitly checked this in the last 2 or 3 years at least, so, just in case I'm wrong (which I don't think it's the case, but still), I invite you to try and double check for yourself, (and let me know). Giampiero Marcell (view profile) Wonderful package thank you it helped me a lot with my work. I just wanted to point out, that one can actually use the S-function approach with user defined sample times from the mask. One just have to place the S-function block into a subsystem and define a sample time parameter in the subsystem’s mask. Then specify a parameter with the value of the name of the sample time parameter of the subsystem’s mask. Then write the parameter’s name in the sample time value field inside the initialization tab of the S-function. This method also eliminates the need to right click the S-function in order to change the mask parameters. lays25 (view profile) I also tried using the method suggested earlier by Phil and MathWorks Classroom Resources Team (referencing to page 20 of the Guide) - adding "extern "C"" and renaming the wrapper file to .cpp but then I get another problem. The model is built and downloaded to my Arduino and... nothing happens. There is no communication, TX/RX diodes are off and I get the following error: Unable to connect to the 'Arduino Due' target for 'encoder_slsp'. Alexandre Poisson (view profile) arman sani (view profile) Mohsen Omrani (view profile) The detail of the walk-through is exquisite. Thank you very very much. Robert Noble (view profile) Hi, To start, excellent package, great info, lots of detail A+++. I'm using R2013a, with Windows XP, Microsoft SDK 7.1, Arduino MEGA 2560. I have been working on a LCD block using an S-function builder block. I spent a long time trying to get it to work but struggling due to an error. The start of the error is shown below. After trawling the internet searching and finding very little I tried changing the LiquidCrystal.h and .cpp files I had in my working directory to the ones from the MATLAB support package folder. This fixed the problem, briefly. On shut down, my computer did a Windows update. The day after, I had a go at adding more to the block, on opening the model file I got a load of warning messages about File I/O from "arduino.h" (I don't have the message to hand). Now my LCD block won't build and I get a java error to do with getting ports. So, started again, and it worked, added some inports to the S-function, and crash. I now get intermittent java errors when trying to build, or I get the realtime_make_rtw hook error shown below. Again. This is extremely frustrating and I am running out of ideas. Any info/ help would be fantastic. Thanks in advance. Rob The call to realtime_make_rtw_hook, during the after_make hook generated the following error: The build failed with the following message: "C:/MATLAB/SupportPackages/R2013a/arduino-1.0/hardware/tools/avr/bin/avr-gcc" -I"C:/ArduinoStuff/arduinoMEGA2560_LCD_02_rtt" -I"C:/ArduinoStuff" -I"C:/Program Files/MATLAB/R2013a/extern/include" -I"C:/Program Files/MATLAB/R2013a/simulink/include" -I"C:/Program Files/MATLAB/R2013a/rtw/c/src" -I"C:/Program Files/MATLAB/R2013a/rtw/c/src/ext_mode/common" -I"C:/Program Files/MATLAB/R2013a/rtw/c/ert" -I"C:/MATLAB/SupportPackages/R2013a/arduino-1.0/hardware/arduino/cores/arduino" -I"C:/MATLAB/SupportPackages/R2013a/arduino-1.0/hardware/arduino/variants/mega" -I"C:/MATLAB/SupportPackages/R2013a/arduino/include" -I"C:/MATLAB/SupportPackages/R2013a/arduino-1.0/libraries/Servo" -mmcu=atmega2560 -std=gnu99 -Wall -Wstrict-prototypes -g -Os -D"MODEL=arduinoMEGA2560_LCD_02" -D"NUMST=1" -D"NCSTATES=0" -D"HAVESTDIO=" -D"ONESTEPFCN=0" -D"TERMFCN=1" -D"MAT_FILE=0" -D"MULTI_INSTANCE_CODE=0" -D"INTEGER_CODE=0" -D"MT=0" -D"CLASSIC_INTERFACE=0" -D"TID01EQ=0" -D"F_CPU=16000000" -D"_RUNONTARGETHARDWARE_BUILD_=" -D"_ROTH_MEGA2560_=" -D"_RTT_NUMSERVOS_=0" -c -x none ./arduinoMEGA2560_LCD_02.c ./arduinoMEGA2560_LCD_02_data.c ./ert_main.c ./sfcn_LCD_wrapper.cpp ./HardwareSerial.cpp ./Print.cpp ./WInterrupts.c ./WMath.cpp ./WString.cpp ./new.cpp ./wiring.c ./wiring_analog.c ./wiring_digital.c ./io_wrappers.cpp In file included from ./ert_main.c:18: C:/MATLAB/SupportPackages/R2013a/arduino-1.0/hardware/arduino/cores/arduino/Arduino.h:24:1: warning: "true" redefined In file included from ./arduinoMEGA2560_LCD_02.h:23, from ./ert_main.c:17: ./rtwtypes.h:158:1: warning: this is the location of the previous definition In file included from ./ert_main.c:18: C:/MATLAB/SupportPackages/R2013a/arduino-1.0/hardware/arduino/cores/arduino/Arduino.h:25:1: warning: "false" redefined In file included from ./arduinoMEGA2560_LCD_02.h:23, from ./ert_main.c:17: ./rtwtypes.h:154:1: warning: this is the location of the previous definition cc1plus.exe: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++ cc1plus.exe: warning: command line option "-std=gnu99" is valid for C/ObjC but not for C++ In file included from ./sfcn_LCD_wrapper.cpp:40: C:/ArduinoStuff/LiquidCrystal.cpp:6:22: error: WProgram.h: No such file or directory In file included from ./sfcn_LCD_wrapper.cpp:39: C:/ArduinoStuff/LiquidCrystal.h:82: error: conflicting return type specified for 'virtual void LiquidCrystal::write(uint8_t)' C:/MATLAB/SupportPackages/R2013a/arduino-1.0/hardware/arduino/cores/arduino/Print.h:48: error: overriding 'virtual size_t Print::write(uint8++ ./io_wrappers.cpp: In function 'void Serial_read(int, int, uint8_t*, int*)': ./io_wrappers.cpp:40: warning: 'libFcnOutput' may be used uninitialized in this function make: *** [arduinoMEGA2560_LCD_02.o] Error 1 The build process will terminate as a result. Robert Noble (view profile) Rusty Boyd (view profile) Hi, I'm having a problem with the LCT method. In both the example, I have problems with the 'DNO_OP=//' directive in the instruction, legacy_code('compile', def, '-DNO_OP=//') In the dout example, it only generates a warning. In my code, it generates a fatal error (the two warnings make sense in context of the error): Error using mex /Users/BOYD/Documents/Atmel_Studio/6.2/sl_TC_varfvarduty/sl_dd_tc1/src/tc1_sfun.c:168:9: error: expected expression NO_OP(); ^ /Users/BOYD/Documents/Atmel_Studio/6.2/sl_TC_varfvarduty/sl_dd_tc1/src/tc1_sfun.c:190:10: warning: expression result unused [-Wunused-value] NO_OP( *u1, *u2); ^~~ /Users/BOYD/Documents/Atmel_Studio/6.2/sl_TC_varfvarduty/sl_dd_tc1/src/tc1_sfun.c:190:15: warning: expression result unused [-Wunused-value] NO_OP( *u1, *u2); ^~~ Error in legacycode.LCT/compile (line 375) Error in legacycode.LCT.legacyCodeImpl (line 84) Error in legacy_code (line 87) [varargout{1:nargout}] = legacycode.LCT.legacyCodeImpl(action, varargin{1:end}); In the dout example, it generates only 3 warnings. I've tried bypassing LCT and using mex directly with the exact same results. I've tried both 2015a and 2015b - no diff. I'm using OS X 10.10.5 (14F27) and Xcode Version 6.4 (6E35b). I hope someone can help. -Rusty Mohsen Omrani (view profile) A bit complicated for a novice programmer but the detail the go through is amazing. Thanks. Barza Nisar (view profile) Petru Tarabuta (view profile) Excellent tutorial, thank you! Suytry KY (view profile) Hi everyone, I use the s-function encoder block in the model to read encoder pulses. If i use only one encoder, it is fine. But the simulink stop working when i use 2 or 3 encoder to read from my robot motors. Can anyone help me to solve this problem because i am supposed to use simulink with arduino to read encoder for my thesis project. NOTE: I do as external mode for real-time test. Thanks in advance!) I bumped into the following error message and found a solution:. The issue was that I was building the model from a directory where the path was too long. i.e. C:/abcdefghijklmnopqrstuvwxyz/abcdefghijklmnopqrstuvxyz/ When I built the model in directory with a shorter path i.e. C:/Documents, I no longer experienced this error.) Thanks a lot Giampiero, That helped a lot. How do I go about declaring global variables/ functions/ libraries? I know in the libraries pane there are 3 sections, 1. Library / Object / Source file 2. Includes 3. External Function Declarations Can you make an example? Alternatively, would you mind taking a quick look at my simple model? I can email it to you. Cheers, Sina Giampiero Campa (view profile) Hi Sina, well, you can't just copy and paste all your code in the output pane, remember that the initialization and global variable and function definitions must go into the Library->Includes pane, the initialization code (that is the part contained in the "setup" function below) must go into the Discrete Update pane, and only the part contained into the "loop" function, which needs to be executed at every time step, must go into the Output pane. I'd suggest you have another look at the guide, and start building up things gradually from a simple example that works. Giampiero Sina (view profile) Hi Giampiero and Everyone, I have a question, I used this guide and built a block to be able to read some input numbers from simulink and pass the numbers to an arduino code so that using motor driver and encoder library it can run the motor. I have written this as my output: /* wait until after initialization is done*/ if (xD[0]==1){ /*don't do anything for the Mex-file generation */ #ifndef MATLAB_MEX_FILE /* MYCODE which is normally run on arduino and uses two libraries: Encoder and DualVNH5019MotorShield */ #include <Encoder.h> #include <DualVNH5019MotorShield.h> unsigned int DEBUG = 1; unsigned int ms_delay = 200; // setup pin variables const int encoderChanA = 2; // pin2 for interrupt0 on timer2 const int encoderChanB = 3; // pin3 for interrupt1 on timer2 Encoder motorEncoder(encoderChanA,encoderChanB); // setup pins for motor control and current sense unsigned char INA1 = 8; // sets motor direction unsigned char INB1 = 10; // sets motor direction unsigned char EN1DIAGA = 5; // sets motor speed, pin5 for PWM on timer0 (to avoid problems with interrupts on timer2) unsigned char CS1 = A1; DualVNH5019MotorShield mdriver(INA1,INB1,EN1DIAGA,CS1,INA1,INB1,EN1DIAGA,CS1); // repeat arguments to simulate second driver (part of API but not actually used) // setup global variables float currentMotorSpeed = 0; long currentEncoderPosition = 0; int currentMotorCurrent = 0; float desiredSpeed = 0; int u = 0; // placeholder input variable 0-9 // Function declaration void setup() { // setup code here pinMode(encoderChanA, INPUT); pinMode(encoderChanB, INPUT); digitalWrite(encoderChanA, HIGH); digitalWrite(encoderChanB, HIGH); mdriver.init(); } void loop() { // 2) read encoder position, and motor current currentEncoderPosition = motorEncoder.read(); currentMotorCurrent = mdriver.getM1CurrentMilliamps(); // 3) Set speed for motor 1, speed is a number betwenn -400 and 400 mdriver.setM1Speed(in[0]); } #endif } This code uses functions that are declared in the included libraries. and I did include those in the supported libraries pane and added the libraries to current matlab folder. It builds the block but the model cannot be built on my Arduino Uno. (there are some errors) Would you please elaborate? Thanks. Sina) 6050 3.3V VCC GND GND A5 SCL A4 SDA DIGITAL 2 INT GND AD0 any help will be appreciated thanks, I built an own arduino Stepper library for arduino uno and now i want to embed it into simulink. The problem i have is that i use: main() { } instead of the common: setup(){} loop(){} structure, because the init() function in the common structure interferes my library functions. I tried to use the s-function builder instruction with my library and i had the same issues as i had when writing functions of my library into the common(setup(),loop()) structure. My question: Is there a way to use the main() structure instead of the void(),loop() structure using the s-function builder {with arduino uno and the simulink support package of matlab}? What i tried so far: - deleting the init() function call in the main function of the s-function builder block created modelname_rtt folder. - changing the init(){as a part of the wiring.c} so that it executes the setup for my library. By the way thanks for your great tutorials. Best Regards, Simon Giampiero Campa (view profile) For Daniel and other interested, Nancy was able to solve the issue by doing 3 things: 1) Copying the utilities folder to the current directory In addition to copying its content in the same folder. 2) Including the SD.h in addition to the SD.cpp 3) Transfering the whole directory to a file path that has no spaces. Note that #3 is always necessary to make things work due to the use of GCC. In this case i think #1 (and perhaps also #2) made the trick. Giampiero Campa (view profile) Minho, i don't know how to make it work with external mode and i am sure is not easily doable with this method. It might be not even feasible. I'll let you know more if i find anything. Also, if i don't know what error it is that you are finding, it's hard for me to have a clue :)) I'm trying to use the SD card library , I get this error when I build the model;. Any help will be appreciated. -Nancy zhubo (view profile) 1 MAMADOU (view profile) Hello i started with arduino (uno) and matlab by modeling a blinking model. But i have a problem to run the model with my arduino uno card. I go to the tools menu for 1st time for to Prepare to Run the model and at the 2nd time, i don't see the option : Run. That is my problem. Is someone can help me. Thanks German (view profile) Nice work, very helpful JimC (view profile) This is a great help to get started. I've been able to tweak the encoder block for speeds. I can't seem to create a driver block that uses the serial comms commands though. I tried including the HardwareSerial.h and .cpp files in the library pane and ran renc2cpp. Any trick needed? EDUARDO (view profile) Tomas (view profile) Interrupt block and some more is now here: phil (view profile) Has anybody been able to make an interrupt block? uavc (view profile)]); } } Mehmet (view profile) Hi, I wonder,how overruns on Arduino Hardware affect software . Because all example drivers give ovverruns error without input and output drivers. Regards Mehmet Neil (view profile) Hello thank you for the reply. I have finally got it working with much success. I'm still not sure where the "inlined" error came from but now it's gone. I have a question for you. I'm trying to use global variables throughout the simulink model. It works if I call the variable within the same s-function as your guide said. However, if I call that variable in another S-function it gives me an error " error: <variable> undeclared (first use in this function)" pertaining to the wrapper file. I find this strange since all my calls to functions within the "#includes" headers work. For example, my includes section looks as shown below: # ifndef MATLAB_MEX_FILE #include <unistd.h> #include <fcntl.h> #include <termios.h> int uart0_filestream = -1; # endif I can call all functions within the first 3 headers, however, if I call uart0_filestream in another block I get the error. Neil (view profile) Neil (view profile) I have not been able to get this to work at all. I'm using MATLAB 2013a Student version. I generate C code using the steps provided. However, when I try to download it to the Arduino, it gives me an error that the function is not in-lined and therefore cannot be downloaded to the target. It tells me to go into the configurations->Simulink Coder and turn in-lining off but since I'm using the student version I don't see this option. Has anyone gotten this error before? I see no where in the documentation phil (view profile) phil (view profile). Giampiero Campa (view profile). uavc (view profile) uavc (view profile) found the problem. the libraries I had to include in the simulink s-function builder was # ifndef MATLAB_MEX_FILE # include <Arduino.h> # endif in that order. I accidentally put the second line first as I thought these were just regular includes, without recognizing that the include was running an if loop (ifndef.... end if) to check: #ifndef The #ifndef operator checks whether something has not been defined using the #define keyword. It must be followed by#endif. Problem solved. XD uavc (view profile) SITUATION: I'm trying to build the output block according to the tutorial. I'm sure this is a basic question but I couldn't quite build the S-function. EXACT ERROR: sfcn_exout_slsp_wrapper.c c:\docs\avr/io.h(330) : fatal error C1021: invalid preprocessor command 'warning' C:\PROGRA~1\MATLAB\R2013A\BIN\MEX.PL: Error: Compile of 'sfcn_exout_slsp_wrapper.c' failed. EXPLANATION IN DETAIL: I had earlier problems that the s-function builder wasn't compiling because it couldn't find Arduino.h, inttypes.h avr/io.h, avr/pgmspace.h, avr/sfr_defs Arduino.h is the only .h file that is called directly from the s-function builder library so I guess the other files are being called by Arduino.h etc. I included the entire path of the Arduino library on the stock c:\program files(x86) directory but it didn't compile still. Hence, I just copied the whole folder into my working directory, still wouldn't work. What made it work was that I had to copy every single .h file (mentioned above) into the working directory (the answer to MATLAB command "pwd") before it would compile and then it led to this error above. I think it's an include error, so how do I ask the s-function builder to look everywhere within my working directory (which is especially important for the avr/xxx.h files. any idea how to solve it? thanks! Juan Jimenez (view profile) Great introduction to learn how to build custom driver blocks. Congrats! Joshua Hurst (view profile) Hi Christian, If you were looking specifically for I2C, MPU6050, or other I2C devices/hardware I posted a simple C-based I2C solution using WirnigPiI2C and you can find this here: Let me know if this helps you! Josh, I have tried a number of different things to try and get the wrapper.cpp file included into the source_files listed in the .mk (make) file, rather than it being skipped. This has included editing the rtwmakecfg and trying to find the toolchain that is used to compile the .mk file. Editing the rtwmakecfg was unsuccessful. I did edit a Linux tool chain located in the "coder" directory. But I don't think it is the one that is used. The toolchain that is listed in the .mk file I cannot find - gmake, LinuxRemoteBuild. Glen (view profile) Hi, I have been trying again to get the MPU6050/HMC5883L model to build on the RPi. In the make file (.mk) which is included in the (_rtt) folder, when I rename the _wrapper.cpp file it is listed as a "SKIPPED_FILE". When I do not rename the wrapper.c is included in the "SOURCE_FILES". I have tried to get it included by editing the SFB.mat file but still no luck. Joshua Hurst (view profile) Hi Glen, I have a student working on the mpu6050 code for RasPi right now - getting it work in C and Python first. Then I will be porting it to Simulink most likely next week. Feel free to send me an email directly and I can try to look at your files when I start start porting my students code: hurstj2@rpi.edu In general for the Rpi you have to make sure the c-code compiles and on its own. If you look at the RPi examples I posted you have to make sure the #includes reference the local directory structure on the RPi - not your box. Just look at the Quadrature Encoder example for the RPi and you will see I had use: #include </home/pi/wiringPi/wiringPi/wiringPiI2C.h>. Which is where the files are on the RPi, not my actual computer. And don't forget to include the actual C files as well: #include </home/pi/wiringPi/wiringPi/wiringPi.h> #include </home/pi/wiringPi/wiringPi/wiringPi.c> Let me know if this helps! Josh Glen (view profile) Hi Giampiero, Many thanks for your reply. I should explain more. I am trying to incorporate the libraries for the MPU6050 and HMC5883L. The code I have previously compiled on the PI. I used the Arduino MPU6050 S-Function Builder Example from Joshua Hurst as a Starting point and replaced the Arduino Libraries with the Libraries I have for the PI - including the I2Cdev. The S-function builds successfully. I then change the _wrapper from .c to .cpp and apply the extern "C" changes. However, when I run on target hardware - using the MATLAB Pi Support Package - it does not include the wrapper .cpp or any .cpp file in the folder (_rtt) it downloads to the PI to compile and run. If I leave the wrapper.c unchanged it does get incorporated into the _rtt folder but then I have unreferenced .cpp files not included. I can send you my work so far if it helps. Many thanks for your support. Best Wishes Glen MathWorks Classroom Resources Team (view profile) Hi Glen, there are several RasPi drivers, i believe with external libraries too, linked in the Acknowledgement section of this page. I (Giampiero) would suggest trying them first to see if you can make them work, if so, start from them to see if you can build your driver. That being said i'll investigate further this case to see if anyone has any idea. Glen (view profile) Hi Giampiero, I am trying build a model incorporating an S-Function Builder for my RaspPi. Because it includes C++ files I change the wrapper file extension to .cpp and at extern "C" infront of the Outputs and Update wrapper. However, when I run the model a further file is built with the extension _rtt and it does not include my wrapper file and other .cpp files within the file that gets downloaded to the RaspPi, hence I get undefined references. I have tried a number of things but starting to go around in circles. Any help would be appreciated.) Hi, Thank you for your step by step explanation. I have tried to create my own servo and I am getting the following error when I have changed the name of the wrapper file generated to .cpp from .c The call to realtime_make_rtw_hook, during the after_make hook generated the following error: The specified file "servornd_wrapper.c" does not exist on the IDE and MATLAB paths. Could you help me resolve this error. Thanks in advance.) Nathan, if you include a .cpp file then you should rename the generated wrapper function from .c to .cpp, and also open it and write: ' extern "C" ' before the two function calls. Please have a look at page 20 of the guide, which explains how to do this, and let me know if it works. phil (view profile) @ Nathan... did you put the included files in the current matlab folder? Nathan Crosty (view profile) Hello, I tried to follow your example and it worked great for interfaces that are in Arduino.h such as digital and analog IO. I ran into problems when trying to include other Arduino Libraries. I noticed that you had included "AFMotor.cpp" and "AFMotor.h" in your examples, which I guess is similar what I am attempting with "DS1307RTC.h" and "DS1307RTC.cpp" which are libraries for keeping time. I can build the sfunction with the sfunction builder when it is structured like you have it in your examples. When I go to build the applicaiton, however, I run into an issue that seems to be related to cpp code when the compiler is expecting c code. I am using the Arduino integration package found here The compiler message I get when it attempts to build the header file with a class definition is this: C:/ARDUIN~1.3/hardware/tools/avr/bin//avr-gcc -c -mmcu=atmega2560 -I. -DF_CPU=16000000 -Os -Wall -Wstrict-prototypes -std=gnu99 -I. -I.. -IC:/PROGRA~1/MATLAB/R2011a/rtw/c/ert -IC:/PROGRA~1/MATLAB/R2011a/extern/include -IC:/PROGRA~1/MATLAB/R2011a/simulink/include -IC:/PROGRA~1/MATLAB/R2011a/rtw/c/src -IC:/PROGRA~1/MATLAB/R2011a/rtw/c/src/ext_mode/common -Ic:/OU_SYSTEMS_ENG/GH/gh-dev/Simulink_Models/Drivers/GH_TopLevel_Test_arduino -Ic:/OU_SYSTEMS_ENG/GH/gh-dev/Simulink_Models/Drivers -Ic:/OU_SYSTEMS_ENG/GH/gh-dev/Simulink_Models -Ic:/OU_SYSTEMS_ENG/GH/gh-dev/Simulink_Models/Custom_Includes -Ic:/OU_SYSTEMS_ENG/GH/gh-dev/Simulink_Models/ArduinoML/blocks -IC:/arduino-1.0.3/hardware/arduino/variants/mega2560 -IC:/arduino-1.0.3/hardware/arduino/cores/arduino -IC:/arduino-1.0.3/libraries/Time -IC:/arduino-1.0.3/libraries/DS1307RTC -Ireferenced_model_includes -I../slprj/arduino/_sharedutils -IC:/ARDUIN~1.3/hardware/arduino/cores/arduino ../sfun_systime_get_wrapper.c -o sfun_systime_get_wrapper.o In file included from ../sfun_systime_get_wrapper.c:39: C:/arduino-1.0.3/libraries/DS1307RTC/DS1307RTC.h:12: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'DS1307RTC' ../sfun_systime_get_wrapper.c:40: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'sysTime' Please let me know if you have any thoughts. I am wondering if this is still an issue with the newer Arduino support in later versions of ML/Simulink.) ./io_wrappers.cpp: In function 'void Serial_read(int, int, uint8_t*, int*)': ./io_wrappers.cpp:40: warning: 'libFcnOutput' may be used uninitialized in this function cc1plus.exe: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++ cc1plus.exe: warning: command line option "-std=gnu99" is valid for C/ObjC but not for C++ ./DDvers1_wrapper.cpp: In function 'void DDvers1_Outputs_wrapper(const boolean_T*, const real_T*, const real_T*, int_T)': ./DDvers1_wrapper.cpp:73: error: 'lcd' was not declared in this scope ./DDvers1_wrapper.cpp:77: error: 'lcd' was not declared in this scope In file included from ./ert_main.c:18: C:/MATLAB/Targets/R2012b/arduino-1.0/hardware/arduino/cores/arduino/Arduino.h:24:1: warning: "true" redefined In file included from ./DisplayDriverv1.h:23, from ./ert_main.c:17: ./rtwtypes.h:158:1: warning: this is the location of the previous definition In file included from ./ert_main.c:18: C:/MATLAB/Targets/R2012b/arduino-1.0/hardware/arduino/cores/arduino/Arduino.h:25:1: warning: "false" redefined In file included from ./DisplayDriverv1.h:23, from ./ert_main.c:17: ./rtwtypes.h:154:1: warning: this is the location of the previous definition) NOTE: If you are working with external libraries and you get an “undefined reference” error that means that your code references objects defined elsewhere (in other files) and, at linking time, the linker cannot find where they are. In this case you need to make sure that all the .c and .cpp files of the library you are using are in the current MATLAB folder and that they are all included in the "Includes" field of the "Libraries" pane of the S-Function Builder (include the .c and .cpp files directly not the .h files). Also, make sure that you read the last section (i.e. the last 2 pages) of the driver guide, entitled: "Working with external libraries".) This is a good introduction to making all the device code I need inside blocks so that I can just drag and drop blocks and get all the processor-specific code. Say I need to add a new encoder. Copy and paste the block and change the pin numbers. Done. Thanks, Giampiero!
https://se.mathworks.com/matlabcentral/fileexchange/39354-device-drivers
CC-MAIN-2019-43
refinedweb
5,235
64.81
Firstly, in the following code what I am trying to do is find the length of a 2D byte array by using 'byteBuffer[0].length', but it is actually not working. When I am printing 'byteBuffer[0].length' it is giving the output as 4 instead of 882000, which (latter) should be the correct output according to the parameters I had passed. So how do I iterate it in my loop? Secondly, I want to pass 'byteBuffer' in 'ByteArrayInputStream', but in 'ByteArrayInputStream' we cannot pass a 2D array. So is there a way of appending the values and use it there? And I also need to pass the values of 'Frequency1' and 'Frequency2' alternatively and save them in .wav format, so that I can play them accordingly in my media player. For example: an Ambulance's siren. import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.Scanner; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; public class AudioPlay { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); final double SAMPLING_RATE = 44100; // Audio sampling rate int time = in.nextInt(); //Time specified by user in seconds int frequency1 = in.nextInt(); //Frequency specified by the user in hz int frequency2 = in.nextInt(); //Size of buffer, in case time is 10 seconds it will be [2][441000] float buffer[][] = new float[2][(int) (time * SAMPLING_RATE)]; for (int sample = 0; sample < buffer[0].length; sample++) { double cycle = sample / SAMPLING_RATE; //Fraction of cycle between samples buffer[0][sample] = (float) (Math.sin(2 * Math.PI * frequency1 * cycle)); //Storing value at every index of 1st row buffer[1][sample] = (float) (Math.sin(2 * Math.PI * frequency2 * cycle)); //Storing value at every index of 2nd row } //Size of byteBuffer, in case time is 10sec it will be [2][882000] byte byteBuffer[][] = new byte[2][(int)(buffer.length * 2)]; System.out.println(byteBuffer[0].length); // Giving wrong output int count = 0; for (int j = 0; j < byteBuffer.length; j++) { for (int i = 0; i < byteBuffer[0].length; i++) { final int x = (int) ((buffer[j][count++]) * Short.MAX_VALUE); byteBuffer[j][i++] = (byte) x; byteBuffer[j][i] = (byte) (x / 256); //Total Value of Byte } } File out = new File("E:/RecordAudio7.wav"); //The path where user want the file data to be written //Construct an audio format, using 44100hz sampling rate, 16 bit samples, mono, and big // endian byte ordering AudioFormat format = new AudioFormat((float) SAMPLING_RATE, 16, 1, true, false); // It uses bytebuffer as its buffer array that contains bytes that may be read from the stream. ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer[0]); //Constructs an audio input stream that has the requested format and length in sample frames, using audio data //from the specified input stream. AudioInputStream audioInputStream = new AudioInputStream(bais, format, buffer.length); //Writes a stream of bytes representing an audio file of the specified file type to the external file provided. AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out); audioInputStream.close(); //Closes this audio input stream } declaring byteBuffer is not correct you are using buffer.length which is 2 that's why output is 4 use buffer[0].length * 2 instead of buffer.length * 2 as below: byte byteBuffer[][] = new byte[2][(int)(buffer[0].length * 2)]; for the second part, (passing 2D array into ByteArrayInputStream) you can put the 2D elements into a 1D longer array where it's length will equals byteBuffer[0].length*byteBuffer.length you can use System.arraycopy() something like this: int newArrayLength = byteBuffer.length*byteBuffer[0].length; byte oneArray[] = new byte[newArrayLength]; //arraycopy(Object src, int srcPos, Object dest, int destPos, int length) for(int b=0;b<byteBuffer.length;b++){ System.arraycopy(byteBuffer[b], 0, oneArray, (b*byteBuffer[b].length), byteBuffer[b].length) } what this code do is converting this byteBuffer (2D) 0-[ ][ ][ ][ ][ ][ ][ ]... 1-[ ][ ][ ][ ][ ][ ][ ]... 2-[ ][ ][ ][ ][ ][ ][ ]... into this: oneArray (1D) [][][][][][][]...[][][][][][][]...[][][][][][][]... And use oneArray for your ByteArrayInputStream P.S: if your app will continue running after this step, it's good to release memory allocated for byteBuffer as it's not needed anymore, because you will work with oneArray, you can release memory by un-referencing it. byteBuffer=null;
https://codedump.io/share/6Cx78n0tK7kA/1/how-to-find-length-of-a-2d-byte-array-and-to-how-use-that-2d-byte-array-in-bytearrayinputstream
CC-MAIN-2017-26
refinedweb
699
51.04
rpc_clnt, callrpc, clnt_broadcast, clnt_call, clnt_create, clnt_control, clnt_destroy,_bufcreate, clntudp_create - library routines for client ONC remote procedure calls #include <rpc/rpc.h> callrpc( char *host, u_int prognum, u_int versnum, u_int procnum, xdrproc_t inproc, char *in, xdrproc_t outproc, char *out ); enum clnt_stat clnt_broadcast( u_int prognum, u_int versnum, u_int procnum, xdrproc_t inproc, char *in, xdrproc_t outproc, char *out, resultproc_t eachresult ); eachresult( char *out, struct sockaddr_in *addr ); enum clnt_stat clnt_call( CLIENT *clnt, u_int procnum, xdrproc_t inproc, char *in, xdrproc_t outproc, char *out, struct timeval tout ); clnt_destroy( CLIENT *clnt ); CLIENT * clnt_create( char *host, u_int prog, u_int vers, char *proto ); bool_t clnt_control( CLIENT *cl, int req, char *info ); clnt_freeres( CLIENT *clnt, xdrproc_t outproc, char *out ); void clnt_geterr( CLIENT *clnt, struct rpc_err *errp ); void clnt_pcreateerror( char *s ); void clnt_perrno( enum clnt_stat stat ); clnt_perror( CLIENT *clnt, char *s ); char * clnt_spcreateerror( char *s ); char * clnt_sperrno( enum clnt_stat stat ); char * clnt_sperror( CLIENT *rpch, char *s ); CLIENT * clntraw_create( u_int prognum, u_int versnum ); CLIENT * clnttcp_create( struct sockaddr_in *addr, u_int prognum, u_int versnum, int *sockp, u_int sendsz, u_int recvsz ); CLIENT * clntudp_bufcreate( struct sockaddr_in *addr, u_int prognum, u_int versnum, struct timeval wait, int *sockp, u_int sendsz, u_int recvsz ); CLIENT * clntudp_create( struct sockaddr_in *addr, u_int prognum, u_int versnum, struct timeval wait, int *sockp );. Calls the remote procedure associated with prognum, versnum, and procnum on the machine host. The in parameter is the address of the procedure's argument(s), and out is the address of where to place the result(s); inproc is used to encode the procedure's parameters, and outproc is used to decode the procedure's results. This routine returns zero if it succeeds, or the value of enum clnt_stat cast to an integer if it fails. The clnt_perrno() routine is handy for translating failure statuses into messages. Warning: Calling remote procedures with this routine uses UDP/IP as a transport; see clntudp_create() for restrictions. You do not have control of timeouts or authentication using this routine. Like callrpc(), except the call message is broadcast to all locally connected broadcast nets. Each time it receives a response, this routine calls the eachresult() routine. The out parameter is the same as the out parameter passed to clnt_broadcast(), except that the remote procedure's output is decoded there; addr points to the address of the machine that sent the results. If eachresult() returns zero, clnt_broadcast() waits for more replies; otherwise, it returns with appropriate status. If eachresult() is NULL, clnt_broadcast() returns without waiting for any replies. Warning: Broadcast sockets are limited in size to the maximum transfer unit of the data link. For Ethernet, the caller's argument size should not exceed 1400 bytes. A macro that calls the remote procedure procnum associated with the client handle, clnt, which is obtained with an RPC client creation routine such as clnt_create(). The in parameter is the address of the procedure's argument(s), and out is the address of where to place the result(s); inproc is used to encode the procedure's parameters, and outproc is used to decode the procedure's results; tout is the time allowed for results to come back. A macro that destroys the client's RPC handle. Destruction usually involves deallocation of private data structures, including clnt itself. Use of clnt is undefined after calling clnt_destroy(). If the RPC library opened the associated socket, it will close it also. Otherwise, the socket remains open. Generic client creation routine. The host parameter identifies the name of the remote host where the server is located. The proto parameter indicates which kind of transport protocol to use. The currently supported values for this field are "udp" and "tcp". Default timeouts are set, but can be modified using clnt_control(). Warning: Since UDP-based RPC messages can only hold up to 8 Kbytes of encoded data, this transport cannot be used for procedures that take large arguments or return huge results. A macro that is used to change or retrieve various information about a client object. The req parameter indicates the type of operation, and info is a pointer to the information. For UDP and TCP, req has the following supported values, argument types, and purposes: CLSET_TIMEOUT struct timeval Set total timeout CLGET_TIMEOUT struct timeval Get total timeout CLGET_FD int Get associated socket CLSET_FD_CLOSE void Close socket on clnt_destroy() CLSET_FD_NOCLOSE void Leave socket open on clnt_destroy() Note If you set the timeout using clnt_control(), the timeout parameter passed to clnt_call() will be ignored in all future calls. CLGET_SERVER_ADDR struct sockaddr Get server's address The following operations are valid for UDP only: CLSET_RETRY_TIMEOUT struct timeval Set the retry timeout CLGET_RETRY_TIMEOUT struct timeval Get the retry timeout The retry timeout is the time that UDP RPC waits for the server to reply before retransmitting the request. A macro that frees any data allocated by the RPC/XDR system when it decoded the results of an RPC call. The out parameter is the address of the results, and outproc is the XDR routine describing the results. This routine returns one (1) if the results were successfully freed, and zero (0) otherwise. A macro that copies the error structure out of the client handle to the structure at address errp. Prints a message to standard error indicating why a client RPC handle could not be created. The message is prepended with string s and a colon. Used when a clnt_create(), clntraw_create(), clnttcp_create(), or clntudp_create() call fails. Prints a message to standard error corresponding to the condition indicated by stat. Used after callrpc(). Prints a message to standard error indicating why an RPC call failed; clnt is the handle used to do the call. The message is prepended with string s and a colon. Used after clnt_call(). Like clnt_pcreateerror(), except that it returns a string instead of printing to the standard error. Note Returns pointer to static data that is overwritten on each call. Takes the same arguments as clnt_perrno(), but instead of sending a message to the standard error indicating why an RPC call failed, returns a pointer to a string that contains the message. The string ends with a NEWLINE. clnt_sperrno() is used instead of clnt_perrno() if the program does not have a standard error (as a program running as a server quite likely does not), or if the programmer does not want the message to be output with printf, or if a message format different than that supported by clnt_perrno() is to be used. Note Unlike clnt_sperror() and clnt_spcreaterror(), clnt_sperrno() does not return pointer to static data so the result will not be overwritten on each call. Like clnt_perror(), except that, like clnt_sperrno(), it returns a string instead of printing to standard error. Note Returns pointer to static data that is overwritten on each call. Creates a toy RPC client for the remote program prognum, version versnum. The transport used to pass messages to the service is actually a buffer within the process's address space, so the corresponding RPC server should live in the same address space; see svcraw_create(). This allows simulation of RPC and acquisition of RPC overheads, such as round-trip times, without any kernel interference. This routine returns NULL if it fails. Creates an RPC client for the remote program prognum, version versnum; the client uses TCP/IP as a transport. The remote program is located at Internet address addr. If addr->sin_port is zero, it is set to the actual port that the remote program is listening on (the remote portmap service is consulted for this information). The parameter sockp is a socket; if it is RPC_ANYSOCK, this routine opens a new socket and sets sockp. Since TCP-based RPC uses buffered I/O , the user may specify the size of the send and receive buffers with the sendsz and recvsz parameters; values of zero choose suitable defaults. This routine returns NULL if it fails. Like clntudp_create(), except that this routine allows the size of the maximum UDP packet that can be sent or received to be specified. If sendz or recvsz is set to 0, a default maximum size is used. Creates an RPC client for the remote program prognum, version versnum; the client uses use UDP/IP as a transport. The remote program is located at Internet address addr. If addr->sin_port is zero, then it is set to actual port that the remote program is listening on (the remote portmap service is consulted for this information). The parameter sockp is a socket; if it is RPC_ANYSOCK, this routine opens a new socket and sets sockp. The UDP transport resends the call message in intervals of wait time until a response is received or until the call times out. The total time for the call to time out is specified by clnt_call(). Warning: Since UDP-based RPC messages can only hold up to 8 Kbytes of encoded data, this transport cannot be used for procedures that take large arguments or return huge results. rpc_misc(3), rpc_svc(3), rpc_xdr(3), xdr(3) Remote Procedure Calls: Protocol Specifications -- RFC 1050 rpc_clnt(3)
http://nixdoc.net/man-pages/Tru64/man3/rpc_clnt.3.html
CC-MAIN-2019-26
refinedweb
1,492
59.33
Related How To Deploy Python Web Applications with the Bottle Micro Framework on Ubuntu 14.04 Introduction Python is an excellent language for web programming due to its flexibility and high-level functionality. Web frameworks can make programming web applications much simpler because they connect many of the components necessary for a robust web interface. While some web frameworks attempt to provide everything, others try to stay out of the way while taking care of the important, difficult to implement issues. Bottle is a Python framework that falls into the second category. It is extremely lightweight, but also makes it easy to develop applications quickly. In this guide, we will cover how to set up and use Bottle to create simple web applications on a Ubuntu 14.04 server. Prerequisites Before you begin this guide you’ll need the following: - A Ubuntu 14.04 Droplet - A working knowledge of how to edit text files from the command line - A sudo user Step 1 — Install a Virtual Environment for Python Python, the programming language that Bottle is built for, comes installed on Ubuntu by default. We will install the python-virtualenv package to isolate our Python project from the system’s Python environment. The virtualenv software allows us to create a separate, contained environment for our Python projects that will not affect the entire OS. Update your package lists: - sudo apt-get update Install python-virtualenv from the repositories: - sudo apt-get install python-virtualenv We are going to create a projects folder in our home directory, and then create a virtual environment within this folder: - mkdir ~/projects - cd ~/projects - virtualenv --no-site-packages venv This creates a directory called venv within the projects directory. It installs some Python utilities within this folder and created a directory structure to install additional tools. Step 2 — Activate the Virtual Environment for Python We must activate the virtual environment before beginning to work on our project: - source venv/bin/activate The command prompt will change to reflect the fact that we are operating in a virtual environment now. If you need to reconnect later, make sure you activate the environment again with these commands: - cd ~/projects - source venv/bin/activate If you need to exit the virtual environment, you can type this at any time: - deactivate Do not deactivate your virtual environment at this point. Step 3 — installing the Bottle package: - pip install bottle After the process completes, we should have the ability to use the Bottle framework within our applications. Step 4 — favorite text editor, create a Python application called hello.py: - nano ~/projects/hello.py We’ll show you each line one a time, and include the final file at the end of this section. Within this file, the first line we will add imports some functionality from the Bottle package. This will allow us to use the framework tools within our application: from bottle import route, run This line tells our program that we want to import the route and run modules from the Bottle package. - The runmodule that we are importing can be used to run the application on a development server, which is great for quickly seeing the results of your program - The routemodule pattern /hello. Add one new line at the bottom of the file: from bottle import route, run @route('/hello') This route decorator matches the URL /hello, so when that path is requested on the server, the function that directly follows will be executed. Add two more lines at the end of the file:. Add the final line, and now your file is complete:parameter specifies the port that this will be using Save and close the file. We can run this application with this command: - python ~/projects/hello.py You can visit this application in your web browser by going to your IP address, followed by the port we chose to run on (8080), followed by the route we created (/hello): It will look like this: You can stop the server at any time by typing: - CTRL-C Step 5 — Create a Bottle Model We have now implemented our first application. It was simple, but it didn’t really implement MVC principles, or do anything particularly interesting. Let’s create a slightly more sophisticated application this time. We’ll. Install SQLite with this command: - sudo apt-get install sqlite We also need to download and install the Bottle plugin that will allow us to use these databases: - pip install bottle-sqlite Now that we have the components, we will create a Python file that will generate a SQLite database with some data. We could do this in the Python interpreter, but making a file makes it easy to repeat. Create the file: - nano ~/projects/picnic_data.py Add this content to the file. It will create a database filled with picnic inventory items:() In this file, we: - Import the SQLite package - Execute a command that creates our table and inserts data - Finally, we commit the changes Save and close the file. Execute the file, which will create a database file called picnic.db within our current directory: - python ~/projects/picnic_data.py If you’d like, you can ls the directory to confirm that the database file was created. The model portion of our program is now fairly complete. We can see that our model will dictate a little bit how our control portion must function to interact with our data. 6 — Create a Bottle Controller Now that we have a database, we can start to develop our main application. This will mainly implement our controller functionality. It will also be the file that most closely resembles our first application. Create a file called picnic.py to store our main application: - nano ~/projects/picnic.py Just like before, we’ll explain the file line by line, and show the completed file at the end of the step.. import sqlite3 from bottle import route, run, template @route('/picnic') def show_picnic(): db = sqlite3.connect('picnic.db') c = db.cursor() c.execute("SELECT item,quant FROM picnic") data = c.fetchall() c.close() output = template('bring_to_picnic', rows=data) return output - The command that connects to the database_to_picnic.tplto format the data. It passes the datavariable as the template variable rows - Finally, it returns formatted output to our user Finally, we need to add will create this template file bring_to_picnic.tpl in the next section. Step 7 — Create a Bottle in the output line in the previous script: - nano ~/projects/bring_to_picnic.tpl In this file, we can mix HTML and programming. Ours will be very simple. It will use a loop to create a table, which we will populate with our model data. Add all of these lines to the file: <h1>Things to bring to our picnic</h1> <table> <tbody> <tr><th>Item</th><th>Quantity</th></tr> %for row in rows: <tr> %for col in row: <td>{{col}}</td> %end </tr> %end <tbody> </table> This will render our page in HTML. - The templating language that we see here is basically Python - The rowsvariable that we passed to the template is available to use when designing the output - We can type lines of Python by preceding them with % - We can access variables within the HTML by using the {{var}}syntax. Save and close the file. Step 8 — Start the Bottle Application Our application is now complete. We can start the program by calling Python on the main file: - python ~/projects/picnic.py We can see the results by visiting our IP address and port, followed by the URL route we created: Your web page should look like this: CTRL-C to stop the application. ( CTRL-Z is a stronger stop signal.) (Optional) Step 9 — Upload Your Own Application To upload your own Bottle application, you’ll want to copy all the project files to this directory: ~/projects/ For example: - scp myproject.py sammy@your_server_ip:~/projects/ Upload all the files associated with this project in a similar way. SFTP is a different way to upload files, if you’re not familiar with scp. (Optional) Step 10 — Start Your Own Application Activate your virtual environment (if you haven’t done so already). - cd ~/projects/ - source venv/bin/activate We’ll use the python command to start the application. We’ll make it slightly less rudimentary by starting the process in the background, which means you can close your terminal and the app will keep running: - nohup python ~/projects/myproject.py & In the output, you should see your process ID number and the following message: [1] 20301 (venv)[sammy@bottle projects]$ nohup: ignoring input and appending output to ‘nohup.out’ Once you’re ready for production, we highly recommend making a more robust startup plan for your app. (Just starting it in the background means your app will stop after a server reboot.) Ubuntu 14.04 uses Upstart.. For example, one easy way to find Bottle-compatible plugins is by using the pip search bottle command. This will give you an idea of some of the more popular options.
https://www.digitalocean.com/community/tutorials/how-to-deploy-python-web-applications-with-the-bottle-micro-framework-on-ubuntu-14-04
CC-MAIN-2020-05
refinedweb
1,505
60.75
u post ur errors for installating,deployment and configuration.... C:\Sun\AppServer\jdk\bin>j :\Sun\AppServer\docs\api error: cannot read: e:\temp\JRunHttpSessionLis 1 error C:\Sun\AppServer\jdk\bin>j WEB-INF\classes\JRunHttpSe C:\JRun4\servers\default\d Listener.java:3: package javax.servlet does not exist import javax.servlet.*; ^ C:\JRun4\servers\default\d Listener.java:4: package javax.servlet.http does not exist import javax.servlet.http.*; ^ C:\JRun4\servers\default\d Listener.java:6: cannot resolve symbol symbol : class HttpSessionListener location: class jrun.support.JRunHttpSessi public class JRunHttpSessionListener implements HttpSessionListener ^ C:\JRun4\servers\default\d Listener.java:8: cannot resolve symbol symbol : class HttpSessionEvent location: class jrun.support.JRunHttpSessi public void sessionDestroyed( HttpSessionEvent session ) ^ C:\JRun4\servers\default\d Listener.java:10: cannot resolve symbol symbol : class HttpSession location: class jrun.support.JRunHttpSessi HttpSession objSession = session.getSession(); ^ 5 errors Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface. The best way to avoid these errors is .. The following instruction will make to create the war file and it also avoid all servlet/jsp related compile errors also u can add exteral jars too..to automatically set the classpath. pls follow.... then after choosing the tomcat project ..now write click to create a new class..e.g JRunHttpSessionListener (ur code) if u want to add external jars ..just right click on ur project the click the propties then select the javabuild path (left frame) then select the libraries tab the click the add external jars button ..browse to get the jar then click OK. After finish coding -->click project menu-->and select the Rebuild All. It will compile successfully and put all the classes in under WEB-INF/classes directory. if u want to create a war of this project just right click on the project and select TOmcat project the select the Export the WAR file sets in project properties.. u can the specify the path where u need to put ur war file.. right click ur project select properties then select the tomcat node and select the Export to War settings tab..there u can browse to select ... Hope this will help to solve all ur compilation issues ..It will be the best way to do..without any help also it will point out the errors and it will give the possible solutions..A Good IDE All the best ANy doubts u ask me.. Experts Exchange Solution brought to you by Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial I agree with vikraman_b. Eclipse is the best IDE for Java/Tomcat use that I ever tried. However focusing in your questions, more especifically the third: You have to create an enviromental variable that is CLASSPATH, in this variable we put all the paths to our classes to compile ours .java and do the imports correctly. If you want, you can use packages. These are subdirs that have classes in it or more subdirs with classes. To use packages you have also to put the paths in the CLASSPATH. Hope this solve the compilation errors. -tom PS: give Eclipse a try... I love it! Another comment... do not worry at all... app servers are not the basic stuff... they are a pain in the a.. hard to configure at the beginning, and also hard to understand. One piece of advice, be patient, read a lot and try everything!!! Welcome to Java, hope you enjoy! -tom Ant and its build.xml file replace the command "make" and his makefile for java ... Here are some instructions on how to do J2EE in a lightweight way - but still with all the power of real enterprise app. If you don't know about Spring () now is the time to look at it. It covers all things that you are looking for - easy db integration, transaction handling, UI, configuration, documentation, forums, ... It has steep lurning curve, but all this stuff mentioned really helps and once you master it, there's no limit to what you can do :-). All things below are already integrated with Spring: - db integration (db independent - only jdbc driver limitations): - simple sql mapping: iBatis () - more advanced ORM tool: Hibernate () - user interface: - most widely spread: Struts (struts.apache.org/) - easy usage: WebWork () - component oriented: Tapestry (jakarta.apache.org/tapest - integrated: Spring MVC ()
https://www.experts-exchange.com/questions/21211043/Newbie-Questions-so-be-gentle.html
CC-MAIN-2018-30
refinedweb
768
60.11
Let's start 2 async functions at the same time and wait until they both will finish: import asyncio import time def write(msg): print(msg, flush=True) async def say1(): await asyncio.sleep(1) write("Hello 1!") async def say2(): await asyncio.sleep(1) write("Hello 2!") write("start") loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.gather( say1(), say2() )) write("exit") loop.close() Read it carefully. If you will run this, you will see that Hello 1! and Hello 2! appeared at the same time after 1 second, not after 2. Note: we wraped all writefunction which disables flush buffer to ensure prints are coming to terminal at a time of call and our experiment is not affected by stdout buffering Awaiting vs waiting Asyncio is not multithreading or multiprocessing, but it runs code in parallel🤯 The thing is next: When run_until_complete runs say1 function, the interpreter executes it line by line, and when it sees await, it starts asynchronous operation which later will be finished with some internal callback to loop (such callback hidden from us, developers). But now, after the start, it immediately returns control to the event loop. So it starts asynchronous sleep and our loop has control, so the loop is actually ready to start the next function say2. When first async sleep is finished, it makes an internal callback to loop (hidden from us) and loop resumes execution of say1 coroutine: next operation is printing Hello 1!. After printing it returns again to the event loop. At the same time, from the second sleep, the loop receives an event about finishing the second sleep (if 2 events will come at the same time they will not be lost, they will be just queued). So now Hello 2! printed and second method also returned. run_until_complete(gather(l1,l2,l3)) will block until all l1, l2, l3 coroutines will be done. It can be displayed as next (assume that all red lines are at 0s time point, and all blue at 1s): Note that 7 and 9 events may become swapped - if you run code several times you may notice that first Hello printed after second. ☝ BTW: async deffunctions are named coroutines. They could be awaited Why it is cool Now just imagine that you can do any blocking IO operations like sleep here (call HTTP methods, work with files, executing database queries) - just start as many as you want and wait. You would use server hardware with maximum efficiency without spawning processes or threads which have a lot of overhead. And it is a reality with Python 3.6+ asyncio! When you will not able to use it When you need multiple CPU operations in parallel. Coroutines should be used only for IO operations, like some HTTP client like aiohttp calls server. Blocking old libraries like requests would block your thread when aiohttp allows doing something else when you are waiting for server response. CPU operations like machine learning, some hard math, looping over huge arrays will still block your thread even if you wrap it in a coroutine. Because your CPU is busy, it can't even exit to event loop while you calculate something. If you need to speed up CPU calculations look at batch processing explanation and example Also, check out: - FastAPI for building REST services: - AIO-libs powered by great community - libraries for Databases, Redis, and amny many more with async coroutine interface Did you know? Asynchronous execution is supported in javascript from the beginning (browsers, nodejs, electron, etc). At early versions they just used callback functions to run something else after async operation finishes. But it created callback-hell issue in javascript, so after sometime in previous decade they implemented same async await interface which we have in python 3.6+. This interface looks for user like sequential execution, with same parallel IO efficiency
https://hinty.io/ivictbor/parallel-execution-of-asyncio-functions/
CC-MAIN-2022-27
refinedweb
643
61.56
The Epochs data structure: discontinuous data¶ This tutorial covers the basics of creating and working with epoched data. It introduces the Epochs data structure in detail, including how to load, query, subselect, export, and plot data from an Epochs object. For more information about visualizing Epochs objects, see Visualizing epoched data. For info on creating an Epochs object from (possibly simulated) data in a NumPy array, see Creating MNE’s data structures from scratch. Page contents As usual we’ll start by importing the modules we need: import os import mne Epochs objects are a data structure for representing and analyzing equal-duration chunks of the EEG/MEG signal. Epochs are most often used to represent data that is time-locked to repeated experimental events (such as stimulus onsets or subject button presses), but can also be used for storing sequential or overlapping frames of a continuous signal (e.g., for analysis of resting-state activity; see Making equally-spaced Events arrays). Inside an Epochs object, the data are stored in an array of shape (n_epochs, n_channels, n_times). Epochs objects have many similarities with Raw objects, including: They can be loaded from and saved to disk in .fifformat, and their data can be exported to a NumPy arraythrough the get_data()method or to a Pandas DataFramethrough the to_data_frame()method. Both Epochsand Rawobjects support channel selection by index or name, including pick(), pick_channels()and pick_types()methods. SSP projector manipulation is possible through add_proj(), del_proj(), and plot_projs_topomap()methods. Both Epochsand Rawobjects have copy(), crop(), time_as_index(), filter(), and resample()methods. Both Epochsand Rawobjects have times, ch_names, proj, and infoattributes. Both Epochsand Rawobjects have built-in plotting methods plot(), plot_psd(), and plot_psd_topomap(). Creating Epoched data from a Raw object¶ The example dataset we’ve been using thus far doesn’t include pre-epoched data, so in this section we’ll load the continuous data and create epochs based on the events recorded in the Raw object’s STIM channels. As we often do in these tutorials, we’ll crop() the Raw data to save memory: sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file, verbose=False).crop(tmax=60) As we saw in the Parsing events from raw data tutorial, we can extract an events array from Raw objects using mne.find_events(): events = mne.find_events(raw, stim_channel='STI 014') Out: 86 events found Event IDs: [ 1 2 3 4 5 32] Note We could also have loaded the events from file, using mne.read_events(): sample_data_events_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw-eve.fif') events_from_file = mne.read_events(sample_data_events_file) See Reading and writing events from/to a file for more details. The Raw object and the events array are the bare minimum needed to create an Epochs object, which we create with the mne.Epochs class constructor. However, you will almost surely want to change some of the other default parameters. Here we’ll change tmin and tmax (the time relative to each event at which to start and end each epoch). Note also that the Epochs constructor accepts parameters reject and flat for rejecting individual epochs based on signal amplitude. See the Rejecting Epochs based on channel amplitude section for examples. epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7) Out: 86 matching events found Applying baseline correction (mode: mean) Not setting metadata Created an SSP operator (subspace dimension = 3) 3 projection items activated You’ll see from the output that: all 320 events were used to create epochs baseline correction was automatically applied (by default, baseline is defined as the time span from tminto 0, but can be customized with the baselineparameter) no additional metadata was provided (see Working with Epoch metadata for details) the projection operators present in the Rawfile were copied over to the Epochsobject If we print the Epochs object, we’ll also see a note that the epochs are not copied into memory by default, and a count of the number of epochs created for each integer Event ID. Out: <Epochs | 86 events (good & bad), -0.299693 - 0.699283 sec, baseline [None, 0], ~3.7 MB, data not loaded, '1': 20 '2': 20 '3': 20 '32': 4 '4': 18 '5': 4> Notice that the Event IDs are in quotes; since we didn’t provide an event dictionary, the mne.Epochs constructor created one automatically and used the string representation of the integer Event IDs as the dictionary keys. This is more clear when viewing the event_id attribute: print(epochs.event_id) Out: {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '32': 32} This time let’s pass preload=True and provide an event dictionary; our provided dictionary will get stored as the event_id attribute and will make referencing events and pooling across event types easier: event_dict = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3, 'visual/right': 4, 'face': 5, 'buttonpress': 32} epochs = mne.Epochs(raw, events, tmin=-0.3, tmax=0.7, event_id=event_dict, preload=True) print(epochs.event_id) del raw # we're done with raw, free up some memory Out: 86 matching events found Applying baseline correction (mode: mean) Not setting metadata Created an SSP operator (subspace dimension = 3) 3 projection items activated Loading data for 86 events and 601 original time points ... 1 bad epochs dropped {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3, 'visual/right': 4, 'face': 5, 'buttonpress': 32} Notice that the output now mentions “1 bad epoch dropped”. In the tutorial section Rejecting Epochs based on channel amplitude we saw how you can specify channel amplitude criteria for rejecting epochs, but here we haven’t specified any such criteria. In this case, it turns out that the last event was too close the end of the (cropped) raw file to accommodate our requested tmax of 0.7 seconds, so the final epoch was dropped because it was too short. Here are the drop_log entries for the last 4 epochs (empty lists indicate epochs that were not dropped): print(epochs.drop_log[-4:]) Out: [[], [], [], ['TOO_SHORT']] Note If you forget to provide the event dictionary to the Epochs constructor, you can add it later by assigning to the event_id attribute: Basic visualization of Epochs objects¶ The Epochs object can be visualized (and browsed interactively) using its plot() method: epochs.plot(n_epochs=10) Notice that the individual epochs are sequentially numbered along the bottom axis; the event ID associated with the epoch is marked on the top axis; epochs are separated by vertical dashed lines; and a vertical solid green line marks time=0 for each epoch (i.e., in this case, the stimulus onset time for each trial). Epoch plots are interactive (similar to raw.plot()) and have many of the same interactive controls as Raw plots. Horizontal and vertical scrollbars allow browsing through epochs or channels (respectively), and pressing ? when the plot is focused will show a help screen with all the available controls. See Visualizing epoched data for more details (as well as other ways of visualizing epoched data). Subselecting epochs¶ Now that we have our Epochs object with our descriptive event labels added, we can subselect epochs easily using square brackets. For example, we can load all the “catch trials” where the stimulus was a face: Out: <Epochs | 4 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~10.6 MB, data loaded, 'face': 4> We can also pool across conditions easily, thanks to how MNE-Python handles the / character in epoch labels (using what is sometimes called “tag-based indexing”): Out: <Epochs | 40 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~72.6 MB, data loaded, 'auditory/left': 20 'auditory/right': 20> <Epochs | 39 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~70.9 MB, data loaded, 'auditory/left': 20 'visual/left': 19> You can also pool conditions by passing multiple tags as a list. Note that MNE-Python will not complain if you ask for tags not present in the object, as long as it can find some match: the below example is parsed as (inclusive) 'right' or 'bottom', and you can see from the output that it selects only auditory/right and visual/right. Out: <Epochs | 38 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~69.2 MB, data loaded, 'auditory/right': 20 'visual/right': 18> However, if no match is found, an error is returned: Out: Tag-based selection with no matches raises a KeyError! Selecting epochs by index¶ Epochs objects can also be indexed with integers, slices, or lists of integers. This method of selection ignores event labels, so if you want the first 10 epochs of a particular type, you can select the type first, then use integers or slices: Out: <Epochs | 10 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~20.9 MB, data loaded, 'auditory/left': 2 'auditory/right': 3 'visual/left': 3 'visual/right': 2> <Epochs | 4 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~10.6 MB, data loaded, 'visual/left': 2 'visual/right': 2> <Epochs | 4 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~10.6 MB, data loaded, 'buttonpress': 4> <Epochs | 4 events (all good), -0.299693 - 0.699283 sec, baseline [None, 0], ~10.6 MB, data loaded, 'buttonpress': 4> Selecting, dropping, and reordering channels¶ You can use the pick(), pick_channels(), pick_types(), and drop_channels() methods to modify which channels are included in an Epochs object. You can also use reorder_channels() for this purpose; any channel names not provided to reorder_channels() will be dropped. Note that these channel selection methods modify the object in-place (unlike the square-bracket indexing to select epochs seen above) so in interactive/exploratory sessions you may want to create a copy() first. epochs_eeg = epochs.copy().pick_types(meg=False, eeg=True) print(epochs_eeg.ch_names) new_order = ['EEG 002', 'STI 014', 'EOG 061', 'MEG 2521'] epochs_subset = epochs.copy().reorder_channels(new_order) print(epochs', 'STI 014', 'EOG 061', 'MEG 2521'] del epochs_eeg, epochs_subset Changing channel name and type¶ You can change the name or type of a channel using rename_channels() or set_channel_types(). Both methods take dictionaries where the keys are existing channel names, and the values are the new name (or type) for that channel. Existing channels that are not in the dictionary will be unchanged. epochs.rename_channels({'EOG 061': 'BlinkChannel'}) epochs.set_channel_types({'EEG 060': 'ecg'}) print(list(zip(epochs.ch_names, epochs.get_channel_types()))[-4:]) Out: [('EEG 058', 'eeg'), ('EEG 059', 'eeg'), ('EEG 060', 'ecg'), ('BlinkChannel', 'eog')] # let's set them back to the correct values before moving on epochs.rename_channels({'BlinkChannel': 'EOG 061'}) epochs.set_channel_types({'EEG 060': 'eeg'}) Selection in the time domain¶ To change the temporal extent of the Epochs, you can use the crop() method: shorter_epochs = epochs.copy().crop(tmin=-0.1, tmax=0.1, include_tmax=True) for name, obj in dict(Original=epochs, Cropped=shorter_epochs).items(): print('{} epochs has {} time samples' .format(name, obj.get_data().shape[-1])) Out: Original epochs has 601 time samples Cropped epochs has 121 time samples However, if you wanted to expand the time domain of an Epochs object, you would need to go back to the Raw data and recreate the Epochs with different values for tmin and/or tmax. It is also possible to change the “zero point” that defines the time values in an Epochs object, with the shift_time() method. shift_time() allows shifting times relative to the current values, or specifying a fixed time to set as the new time value of the first sample (deriving the new time values of subsequent samples based on the Epochs object’s sampling frequency). # shift times so that first sample of each epoch is at time zero later_epochs = epochs.copy().shift_time(tshift=0., relative=False) print(later_epochs.times[:3]) # shift times by a relative amount later_epochs.shift_time(tshift=-7, relative=True) print(later_epochs.times[:3]) Out: [0. 0.00166496 0.00332992] [-7. -6.99833504 -6.99667008] del shorter_epochs, later_epochs Note that although time shifting respects the sampling frequency (the spacing between samples), it does not enforce the assumption that there is a sample occurring at exactly time=0. Extracting data in other forms¶ The get_data() method returns the epoched data as a NumPy array, of shape (n_epochs, n_channels, n_times); an optional picks parameter selects a subset of channels by index, name, or type: eog_data = epochs.get_data(picks='EOG 061') meg_data = epochs.get_data(picks=['mag', 'grad']) channel_4_6_8 = epochs.get_data(picks=slice(4, 9, 2)) for name, arr in dict(EOG=eog_data, MEG=meg_data, Slice=channel_4_6_8).items(): print('{} contains {} channels'.format(name, arr.shape[1])) Out: EOG contains 1 channels MEG contains 305 channels Slice contains 3 channels Note that if your analysis requires repeatedly extracting single epochs from an Epochs object, epochs.get_data(item=2) will be much faster than epochs[2].get_data(), because it avoids the step of subsetting the Epochs object first. You can also export Epochs data to Pandas DataFrames. Here, the DataFrame index will be constructed by converting the time of each sample into milliseconds and rounding it to the nearest integer, and combining it with the event types and epoch numbers to form a hierarchical MultiIndex. Each channel will appear in a separate column. Then you can use any of Pandas’ tools for grouping and aggregating data; for example, here we select any epochs numbered 10 or less from the auditory/left condition, and extract times between 100 and 107 ms on channels EEG 056 through EEG 058 (note that slice indexing within Pandas’ loc is inclusive of the endpoint): df = epochs.to_data_frame(index=['condition', 'epoch', 'time']) df.sort_index(inplace=True) print(df.loc[('auditory/left', slice(0, 10), slice(100, 107)), 'EEG 056':'EEG 058']) del df Out: channel EEG 056 ... EEG 058 condition epoch time ... auditory/left 2 100 18.814844 ... 16.245426 102 19.172632 ... 16.416629 103 20.186365 ... 17.215579 105 16.787378 ... 14.190982 107 12.970971 ... 11.337589 6 100 1.007473 ... 2.413561 102 -0.602573 ... 1.614611 103 -2.749302 ... 0.701525 105 -7.460178 ... -3.350294 107 -9.726169 ... -5.347669 10 100 4.922387 ... 1.976881 102 1.284874 ... -1.618394 103 0.807824 ... -1.390123 105 4.326073 ... 1.862746 107 5.220543 ... 2.262221 [15 rows x 3 columns] See the Exporting Epochs to Pandas DataFrames tutorial for many more examples of the to_data_frame() method. Epochs objects to disk¶ Epochs objects can be loaded and saved in the .fif format just like Raw objects, using the mne.read_epochs() function and the save() method. Functions are also available for loading data that was epoched outside of MNE-Python, such as mne.read_epochs_eeglab() and mne.read_epochs_kit(). epochs.save('saved-audiovisual-epo.fif', overwrite=True) epochs_from_file = mne.read_epochs('saved-audiovisual-epo.fif', preload=False) Out: Reading saved-audiovisual-epo.fif ... Read a total of 3 projection items: PCA-v1 (1 x 102) active PCA-v2 (1 x 102) active PCA-v3 (1 x 102) active Found the data of interest: t = -299.69 ... 699.28 ms 0 CTF compensation matrices available 85 matching events found Applying baseline correction (mode: mean) Not setting metadata Created an SSP operator (subspace dimension = 3) 3 projection items activated The MNE-Python naming convention for epochs files is that the file basename (the part before the .fif or .fif.gz extension) should end with -epo or _epo, and a warning will be issued if the filename you provide does not adhere to that convention. As a final note, be aware that the class of the epochs object is different when epochs are loaded from disk rather than generated from a Raw object: Out: <class 'mne.epochs.Epochs'> <class 'mne.epochs.EpochsFIF'> In almost all cases this will not require changing anything about your code. However, if you need to do type checking on epochs objects, you can test against the base class that these classes are derived from: print(all([isinstance(epochs, mne.BaseEpochs), isinstance(epochs_from_file, mne.BaseEpochs)])) Out: True Iterating over Epochs¶ Iterating over an Epochs object will yield arrays rather than single-trial Epochs objects: Out: <class 'numpy.ndarray'> <class 'numpy.ndarray'> <class 'numpy.ndarray'> If you want to iterate over Epochs objects, you can use an integer index as the iterator: Out: <class 'mne.epochs.Epochs'> <class 'mne.epochs.Epochs'> <class 'mne.epochs.Epochs'> Total running time of the script: ( 0 minutes 45.915 seconds) Estimated memory usage: 565 MB Gallery generated by Sphinx-Gallery
https://mne.tools/stable/auto_tutorials/epochs/plot_10_epochs_overview.html
CC-MAIN-2020-34
refinedweb
2,737
55.64
> Davide Libenzi <davidel@... on > 07/13/2001 12:41:44 PM > > Sent by: lse-tech-admin@... > > To: Larry McVoy <lm@...> > cc: linux-kernel@..., Andi Kleen <ak@...>, > lse-tech@..., Mike Kravetz <mkravetz@...> > Subject: [Lse-tech] Re: CPU affinity & IPI latency > > On 13-Jul-2001 Larry McVoy wrote: > > Be careful tuning for LMbench (says the author :-) > > > > Especially this benchmark. It's certainly possible to get dramatically > > better > > SMP numbers by pinning all the lat_ctx processes to a single CPU, because > > the benchmark is single threaded. In other words, if we have 5 > processes, > > call them A, B, C, D, and E, then the benchmark is passing a token from > > A. > > Agree. > > > > > This is a really hard area to get right but you can take a page from all > > the failed process migration efforts. In general, moving stuff is a bad > > idea, it's much better to leave it where it is. Everything scales better > > if there is a process queue per CPU and the default is that you leave the > > processes on the queue on which they last run. However, if the load > average > > for a queue starts going up and there is another queue with a > substantially > > lower load average, then and ONLY then, should you move the process. > > I personally think that a standard scheduler/cpu is the way to go for SMP. > I saw the one IBM guys did and I think that the wrong catch there is trying > always to grab the best task to run over all CPUs. > I think that this concept could be relaxed introducing less chains between > each > CPU scheduler. > A cheap load balancer should run, "time to time"(tm), to move tasks when a > certain level of unbalancing has been reached. > This will give each scheduler more independence and will make it more > scalable, > IMVHO. Davide, this is exactly what we do with the LoadBalancing extentions to the MQ scheduler. We subdivide into smaller sets, do the scheduling in there and from "time to time" (tm), we move tasks over from set to set in order to ensure loadbalancing. The frequency and loadbalancing is configurable (module). > > > > This is an area in which I've done a pile of work and I'd be interested > > in keeping a finger in any efforts to fix up the scheduler. > > We've, somehow, understood it :) > > - Davide > > _______________________________________________ > Lse-tech mailing list > Lse-tech@... > > On Fri, 13 Jul 2001 12:17:37 PDT, Davide Libenzi wrote: > > The problem, IMHO, is that we're trying to extend what is a correct > behaviour on the UP scheduler ( pickup the best task to run ) to SMP > machines. Global scheduling decisions should be triggered in response > of load unbalancing and not at each schedule() run otherwise we're > going to introduce a common lock that will limit the overall > scalability.. The code inside > kernel/sched.c should be reorganized ( it contains even not scheduler > code ) so that the various CONFIG_SCHED* will not introduce any messy > inside the code ( possibly by having the code in separate files > kernel/sched*.c ). > > - Davide. Config options means the user has to choose, I have too many important choices to make already when building a kernel. Others have proposed loadable scheduler modules, but the overhead doesn't seem to justify the separation. Config options mean more testing, more stable APIs for low level scheduling (or more times when one or the other is broken). gerrit On 13-Jul-2001 Gerrit Huizenga wrote: >. It's the concept of 'good enough' that seems to have different meanings for different people. Personally I could even think that the behaviour for the UP case is 'almost' the same but, as you can see by watching at the lk threads in the last years, it's pretty hard to try people to agree on the concept of 'good enough'. Config options will leave the current scheduler for UP ( or even for not heavy MP ) while will introduce an option to users that will suffer scheduler problems. > Config options means the user has to choose, I have too many important > choices to make already when building a kernel. Even when I go at the restaurant I've to chose, but I still prefer that instead of getting the 'menu du jour'. - Davide > Others have proposed loadable scheduler modules, but the overhead doesn't > seem to justify the separation. Config options mean more testing, more > stable APIs for low level scheduling (or more times when one or the other > is broken). Loadables are great for rapid prototyping or minimal change scenarios. () However, Linus has stated that he does not want loadable schedulers, due to variablility, reliablility, and benchmark issues. The best feature is the ability to patch your core OS/policies while jobs are still running, with no reboot. Clearly people who load stock distributions and never change are not the target of this technology, which is probably the reason this feature showed up under the "obscure" category in the FOLK project. () Loadables also have the distinct disadvantage of getting out of sync with the main kernel quite easily. The psets module developed a few reschedule quirks in the transition from 2.4.3 to 2.4.4 that I still haven't tracked down. The config options are also good for minimum change scenarios, where people get used to the old way or might not like something about the new. I see this affecting makefiles to generate new modules more than creating spaghetti logic. Most of these options are entirely orthogonal. At worst, we put the onus of ordering "with cheese" on the xconfig operator. We often use this for enterprise OS options that the average person may not need. If the option becomes common enough (like SMP) it gets into the default settings. David, > Global scheduling decisions should be triggered in response of load unbalancing > and not at each schedule() run otherwise we're going to introduce a common lock > that will limit the overall scalability. Thats correct. Though it beggars the question : who will define "load-imbalance" and at what granularity ? In the Loadbalancing extensions to MQ () load balancing is done at a frequency specified at the time the loadbalancing module is loaded. The parameter can be changed dynamically through a /proc interface. So we are providing a knob for the user/sysadmin to control the loadbalancing desired. >. Its certainly a challenge to provide SMP/NUMA scalability in the scheduler (and elsewhere in the kernel) without having to resort to an #ifdef. Shailabh On 13-Jul-2001 Shailabh Nagar wrote: >. Personally I hate #ifdef's inside the code more than my cat water, but something like : [sched.c] #ifdef CONFIG_SCHED_XXX #include "sched_xxx.c" #else #ifdef CONFIG_SCHED_YYY #include "sched_yyy.c" ... #endif looks pretty clean to me. - Davide Enclosed is a patch for the fixing the process bouncing problem a.k.a "PU affinity & IPI latency". The patch is again 2.4.5 (all I had last night), so Andi could you please test it on your stuff and see whether it works for you. It works on stock apps. Basic principle is as follows: When reschedule_idle(p) determines to IPI a task, it sets a pointer to <p> in schedule_data(target_cpu). We raise the <p->has_cpu> flag to indicate that p should not be considered for scheduling. In schedule(), we check after going to <still_running> whether, this call is based on an IPI, if so we always take this task. To be functionally correct, we also consider the reservation in reschedule_idle(), i.e., we first look for the reservation, then for idle and then cpu_curr to determine the best task. If indeed the decision is to "preempt" the reserving task, (actually, its not running yet), we simply lower the current reservation has_cpu=0) and replace it with <p>. -- Hubertus Franke (frankeh@...) diff -uwrbBN linux-2.4.5-van/kernel/sched.c linux-2.4.5-ca/kernel/sched.c --- linux-2.4.5-van/kernel/sched.c Fri Apr 20 21:26:16 2001 +++ linux-2.4.5-ca/kernel/sched.c Tue Jul 17 07:31:10 2001 @@ -97,12 +97,14 @@ static union { struct schedule_data { struct task_struct * curr; + struct task_struct * resched; cycles_t last_schedule; } schedule_data; char __pad [SMP_CACHE_BYTES]; -} aligned_data [NR_CPUS] __cacheline_aligned = { {{&init_task,0}}}; +} aligned_data [NR_CPUS] __cacheline_aligned = { {{&init_task,0,0}}}; #define cpu_curr(cpu) aligned_data[(cpu)].schedule_data.curr +#define cpu_resched(cpu) aligned_data[(cpu)].schedule_data.resched #define last_schedule(cpu) aligned_data[(cpu)].schedule_data.last_schedule struct kernel_stat kstat; @@ -208,7 +210,7 @@ { #ifdef CONFIG_SMP int this_cpu = smp_processor_id(); - struct task_struct *tsk, *target_tsk; + struct task_struct *tsk, *target_tsk, *rtsk; int cpu, best_cpu, i, max_prio; cycles_t oldest_idle; @@ -219,7 +221,9 @@ best_cpu = p->processor; if (can_schedule(p, best_cpu)) { tsk = idle_task(best_cpu); - if (cpu_curr(best_cpu) == tsk) { + if ((cpu_curr(best_cpu) == tsk) && + (cpu_resched(best_cpu) == NULL)) + { int need_resched; send_now_idle: /* @@ -244,13 +248,24 @@ */ oldest_idle = (cycles_t) -1; target_tsk = NULL; + best_cpu = 0; max_prio = 1; for (i = 0; i < smp_num_cpus; i++) { cpu = cpu_logical_map(i); if (!can_schedule(p, cpu)) continue; + /* first check whether there is an resched IPI + * reservation for that cpu. If so consider priority + * of the reservation instead of current. + * We do not have to set the need_resched flag again + * for the currently running task. It must have been + * signalled before + */ + tsk = cpu_resched(cpu); + if (tsk == NULL) tsk = cpu_curr(cpu); + /* * We use the first available idle CPU. This creates * a priority list between idle CPUs, but this is not @@ -268,19 +283,30 @@ if (prio > max_prio) { max_prio = prio; target_tsk = tsk; + best_cpu = cpu; } } } } tsk = target_tsk; if (tsk) { + rtsk = cpu_resched(best_cpu); + if (rtsk) { + rtsk->has_cpu = 0; /* return rtsk to scheduable */ + tsk->has_cpu = 1; /* can't schedule this one no more*/ + cpu_resched(best_cpu) = tsk; + return; + } if (oldest_idle != -1ULL) { best_cpu = tsk->processor; goto send_now_idle; } tsk->need_resched = 1; - if (tsk->processor != this_cpu) - smp_send_reschedule(tsk->processor); + if (tsk->processor != this_cpu) { + tsk->has_cpu = 1; + cpu_resched(best_cpu) = tsk; + smp_send_reschedule(best_cpu); + } } return; @@ -578,6 +604,15 @@ */ repeat_schedule: + /* we check whether we have a resched_IPI reservation: + * if so simply select the reserving task and next and + * go to switch to it. + */ + next = cpu_resched(this_cpu); + if (next) { + next = p; + goto found_next; + } /* * Default process to select.. */ @@ -604,6 +639,7 @@ * switching to the next task, save this fact in * sched_data. */ +found_next: sched_data->curr = next; #ifdef CONFIG_SMP next->has_cpu = 1;
http://sourceforge.net/mailarchive/forum.php?thread_name=3B5449A8.9FFC7010%40watson.ibm.com&forum_name=lse-tech
CC-MAIN-2013-48
refinedweb
1,691
62.68
I followed the instructions here: I clicked File -> New -> ActionScript Project Then I called my "project StartingStarling01" and made it a Web Application. I clicked Next -> Add SWC -> browse, then located my Starling.SWC file in the Program Files in my C drive that. I had downloaded the Game SDK from my Creative Cloud account: "C:\Program Files (x86)\Adobe Gaming SDK 1.4\Frameworks\Starling\Starling-Framework\starling\bin" I clicked Finish. I created these classes: import flash.display.Sprite; import starling.core.Starling; [SWF(width="400", height="300", frameRate="60", backgroundColor="#ffffff")] public class StartingStarling01 extends Sprite { private var _starling:Starling; public function StartingStarling01() { _starling = new Starling(Game, stage); _starling.start(); } } import starling.display.Sprite; import starling.text.TextField; public class Game extends Sprite { public function Game() { var textField:TextField = new TextField(400, 300, "Welcome to Starling!"); addChild(textField); } } But I get all these problems: And when I run the file it comes up with this in my browser: What have I done wrong and how do I fix it please? I don't know if you are still interested but if you clean Project > clean the project it fixed the errors I had. When learning a framework it is a good idea to link to the source folder of the framework, that way you benefit from viewing the source code in the package explorer. After you are ready for the release version use the swc files. To fix the error in the web browser you have to edit the index.templete.html in the root of your project. In the script tag inside the head element add the following params.wmode = "direct"; You will see other param values being set just insert the line there. Hope this help.
https://forums.adobe.com/thread/2092514
CC-MAIN-2018-09
refinedweb
291
75.3
Sorry, I missed pasting this part… and this part… Not sorry for the “crayon” writing… that was just for my fun Sorry, I missed pasting this part… and this part… Not sorry for the “crayon” writing… that was just for my fun 2.5 seconds of what? blynking! Well, I am wasting more time than that, which is “blocking” my own projects, while dealing with this senseless argument Program smarter or complain about the tools provided… I will leave you to your choices. Wow. Nice. To those who have read this far, thanks. I am a user, a client and a huge fan of Blynk and am motivated in my discussion only with its improvement. I created a useful wood stove controller that uses a stepper motor to open/close the air flow. I can set a target room temp, stove temp or just choose the air flow % manually. Here’s the motor, wearing a stainless hat that plugs the air intake: Now that it is freezing cold in New Hampshire, I dusted off the equipment added some minor code tweaks and reinstalled the controller. When I went to calibrate the actuator, the “Calibrate” button failed to work because of the change in the Blynk Library. I am sure of that and it’s no big deal - I easily could work around it. I was just looking for advice on the cause before I figured it out through my test script. What I found was somewhat interesting, more from an academic/design perspective than “Oh my god! Help me fix this!”. If you use a button to send an event to a device, let’s say “calibrate”, then you want to have another button (or the same button in my case) that sends an event to “confirm” (and then another event that says “goHigherUp”, etc), there are different ways to handle that sequence. One method is to call a calibrate() function right from the BLYNK_WRITE method on the button press. But while your code is twiddling around with the motor, it is not running Blynk.run()… so the device will never receive new events and the device will not get a new signal to “confirm”. So, let’s put Blynk.run() into the calibrate() loop, so it can get that “confirm” event (which is received through the same BLYNK_WRITE function and just flags that the button was pressed again). That worked perfectly well for me until the 0.5.* lib, now I see that Blynk.run() will only run a single BLYNK_WRITE at a time. I never got that confirmation button press, even while looping on Blynk.run(). So, the solution is to leave the BLYNK_WRITE methods in a hurry! You can do that by calling functions using the timer.setTimeout(10,calibrate) technique that I mentioned earlier. This will launch the function through a queue manager and the BLYNK_WRITE function is finished – no strings attached. Is this the “best practice”? Under these library conditions, I think it is. Can I live with the library change? Sure, now that I know what I am dealing with. Am I blocking? I don’t think so! Hope that helps others understand what happens “under the hood”. -Jamie OK, I am a bit bored… and loose focus too often sometimes, thus the movie is on pause Here is a nice little sketch with three simultaneously running BLYNK_WRITE() functions, each doing their own thing… Increment and display a number every 100ms on the Terminal if the White button is ON, reset when OFF. Flashing one of Blynk’s new large LED’s (BETA App at time of this post) depending on the frequency set by the Slider Widget (AKA my variable timer) 100ms-5000ms range. Increment/Decrement a number, based on the Step Widget… as fast as you can press. And as I kept recommending to avoid, wherever possible due to their blocking nature… not a single delay(), for() or while() is to be found… and only one Blynk.run() command required… thus no function is blocking the others. Small Disclaimer… I am messing heavily with Blynktimers here, and not really paying attention to giving each timed action enough ‘time’ to complete, so there can be some slight degradation (AKA slowdown) when running the variable timed function at fast rates. However, the BLYNK_WRITE() function containing the simple Step Widget and indicating Display widget is completely unaffected by these slight timer degradations. Yep, with smarter coding practice, multiple BLYNK_WRITE() functions working concurrently as normal #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> //Blynk setup char ssid[] = "SSID"; char pass[] = "PASS"; char auth[] = "AUTH"; long variableTime; int number; int varTimer; // Setup Timer ID int numTimer; // Setup Timer ID int flashTimer; // Setup Timer ID // WidgetTerminal blynkTerm(V1); // Not required as I am using direct Blynk.virtualWrite() commands to the terminal BlynkTimer timer; void setup() { Blynk.begin(auth, ssid, pass); // Blynk.begin() is a blocking function until connected, so no need to have extra connection check delays } void loop() { Blynk.run(); timer.run(); } BLYNK_CONNECTED() { Blynk.syncVirtual(V0); Blynk.syncVirtual(V3); } BLYNK_WRITE(V0) { // Switch Widget for incremental counting to terminal if (param.asInt() == 1) { //if button pressed down Blynk.virtualWrite(V1, 0); // Send number to Terminal // Timed Lambda Function - LED Flash numTimer = timer.setInterval(100L, []() { number++; // Increment number Blynk.virtualWrite(V1, "-"); // Send number to Terminal Blynk.virtualWrite(V1, number); // Send number to Terminal }); // END Timer Function } else { timer.deleteTimer(numTimer); // Cancel previous Timeout Timer number = 0; // Reset Number } } BLYNK_WRITE(V3) { // Slider Widget for interval timing timer.deleteTimer(varTimer); // Cancel previous Timeout Timer Blynk.virtualWrite(V2, 0); // Turn OFF LED variableTime = param.asInt(); // Get new interval time if (variableTime <= 100) { // prevents a timer from becoming 100 or less variableTime = 100; } Blynk.virtualWrite(V6, variableTime); timerLoop(); // Call your timed loop } BLYNK_WRITE(V4) { // Increment/Decrement a number, based on the Step Widget Blynk.virtualWrite(V5, param.asInt()); } void timerLoop() { // This is my, adjustable, variable timer setup flashing an LED timer.deleteTimer(varTimer); // Cancel existing Timeout Timer Blynk.virtualWrite(V2, 255); // Turn ON LED // Timed Lambda Function - LED Flash OFF flashTimer = timer.setTimeout(50L, []() { Blynk.virtualWrite(V2, 0); // Turn OFF LED }); // END Timer Function varTimer = timer.setTimeout(variableTime, timerLoop); // Set new Timeout timer and call this function again in X seconds } And for others to check out… I have also used various timer methods in many code examples - C++ Blynk - Code Examples for Basic Tasks (Work in Progress) Just because there’s a mess of crazy going on doesn’t mean any two BLYNK_WRITE’s are running concurrently. You do know that, right? Single core MCUs don’t actually multitask like real SOC or computers… they just calculate really fast and give that sense… You know that, right? My point is that your arguments blaming the library can be proven false when using proper programming methods recommended by Blynk. If it can calculate faster then I can push buttons, and quick enough to do the job (I have Rovers and other fast motor controlled projects that work just fine)… who cares how the library processes the code. So what were you try to prove then?! You’re just not following this thread. This is not about multitasking, but you could start a new thread if you want to discuss that instead. I’m examining the effect of a library update. That’s all. You’re getting all emotional – it’s kind of weird. I am not blaming anyone. Please, go enjoy your movie. You should close this thread before you embarrass yourself any further. One that is 11 months old… way to keep current Not as weird as you thinking you know my mood… I CAN (sometimes) multitask and was doing other stuff in-between typing as my thought processes came back to this non-issue… I enjoy the intellectual challenges… PS movie was great Not embarrassed at all… I have been doing this forum thing for a long time… and as indicated by the Blynk developers themselves, my explanations were more on-track than yours. Sorry if you can’t get it to work anymore, try some of my programming methods But good idea on the thread… it has reached a conclusion, so closing it as requested.
https://community.blynk.cc/t/concurrent-blynk-writes/29638?page=2
CC-MAIN-2022-21
refinedweb
1,363
71.75
fabric doesn't like fab_deploy.utils.IterableModule It seems fabric is not able to find tasks exposed as types.ModuleType subclass. My fabfile has the following: {{{ project = WebProject().expose_as_module('project') apps = define_apps( django = Django( Nginx(), Apache(), ) ) }}} "project" module is available at command-line, "apps" is not. After changing apps_module to be types.ModuleType('apps') in {{{fab_deploy.utils.define_apps}}} apps become available from console. I think this may be fixed by introducing {{{ def iter_public_attributes(module): return (getattr(module, attr) for attr in dir(module) if not attr.startswith('_')) }}} utility and removing IterableModule. see also: This is quite ugly but is seems there is no way to make module iterable by monkey-patching. Better ideas are welcome! I think the way to go is to wait for Fabric fix for this; it will be included in the next bugfix release.
https://bitbucket.org/kmike/django-fab-deploy/issues/48/fabric-doesnt-like
CC-MAIN-2017-51
refinedweb
139
52.66
. Akka HTTP provides a straight-forward model for this abstraction: /** * The ADT for WebSocket messages. A message can either be a binary or a text message. */ sealed trait Message extends akka.http.javadsl.model.ws akka.http.javadsl.model.ws.TextMessage with Message { /** * The contents of this message as a stream. */ def textStream: Source[String, _] /** } a Strict subclass for each kind of message which contains data as a strict, i.e. non-streamed, ByteString or String., use TextMessage.apply(text: String) to create a Strict message which is often the natural choice when the complete message has already been assembled. Otherwise, use TextMessage.apply(textStream: Source[String, Any]) to create a streamed, => TextMessage(Source.single("Hello ") ++ tm.textStream) :: Nil case bm: BinaryMessage => // ignore binary messages but drain content to avoid the stream being clogged bm.dataStream.runWith(Sink.ignore) Nil } the request was a WebSocket request. Otherwise, the directive rejects the request. Here’s the above simple request handler rewritten as a route: def greeter: Flow[Message, Message, Any] = Flow[Message].mapConcat { case tm: TextMessage => TextMessage(Source.single("Hello ") ++ tm.textStream ++ Source.single("!")) :: Nil case bm: BinaryMessage => //.
http://doc.akka.io/docs/akka-http/current/scala/http/websocket-support.html
CC-MAIN-2017-13
refinedweb
188
52.66
or Join Now! « back to Wood & Lumber forum Vrtigo1 home | projects | blog 434 posts in 2561 days 09-01-2010 10:57 PM I know there are tons of posts on the subject, but none specifically addressing my question that I could find. I have a whole mess of 2×4 shelving in my garage, and feel the time has come to rip it out and build something better. I want to build some wall cabinets, but am stuck on trying to figure out what to build them out of. 3/4 birch plywood seems like it would be my first choice, but at about $45/sheet, I wanted to see if there were any other good options. I’m not opposed to spending the money to do it right, but am trying to figure out what “right” is. I’ll probably just paint the cabinets, so I was thinking about using MDF, which is about $30/sheet, but I’m not sure if there would be any problems using it in an uninsulated garage in Florida, plus from my experience it doesn’t hold screws very well. I can also get BC pine plywood for about $35/sheet, but not sure if that would look good enough when painted, or if it would even be worth saving the $10/sheet over birch. Are there any other good options? I’m planning on making face frames and door frames out of pine and using MDF for door panels. Am I at least on the right track there? swirt 2154 posts in 2541 days #1 posted 09-02-2010 06:16 AM I’d avoid MDF in a Florida garage. Way too humid. -- Galootish log blog, Rick Dennington 5342 posts in 2764 days #2 posted 09-02-2010 06:41 AM Greetings,If you want to see what plywood cabinets look like in a woodshop, just go to my home, and look under my shop pixs. I build all of my cabinets out of 3/4” birch, put about 2 coats of a mixture of tung oil and mineral spirits on, and they look good…. It’s well worth it in the end to use good plywood… Not only looks nice, but will hold up a lot better than MDF for cabinets…...I think you’ll be a lot happier with the results…..... -- Here in the South, we say "down the road a piece"...and , "it's over yonder".....!! Greedo 470 posts in 2530 days #3 posted 09-02-2010 01:11 PM i have actually made mdf cabinets, with pine face frames in my projects.and i recently finished a wall tool cabinet with pine door frames and mdf raised panels and i am verry happy with the result. but with mdf it is important that that you threat the surface, preferably with acrylic laquer. or it can swell over the years. there also exists bathroom mdf that is green, only slightly more expensive but it resists humidity. i don’t like to use plywood, it’s expensive, it splinters, it has a grain direction wich looks silly when the grain goes across the length. and i find it’s more easy to make solid screwed glued joints in mdf than with ply. but mdf does look quite bland, you got to like it. #4 posted 09-02-2010 02:56 PM Hey Rick, those cabinets do look good. Bit confused though…why do you have two table saws with an outfeed table between them??? Looks like the setup for some kind of “I can cut wood faster than you” game. Heh. helluvawreck 24733 posts in 2436 days #5 posted 09-02-2010 03:10 PM I’d would use the birch plywood; however it would be nice if you can get some that is good and flat. You might do better getting some from a cabinet shop supplier than from the big box people. -- If a man does not keep pace with his companions, perhaps it is because he hears a different drummer. Let him step to the music which he hears, however measured or far away. Henry David Thoreau CharlieM1958 16258 posts in 3788 days #6 posted 09-02-2010 03:31 PM Definitely go with the birch ply. However, depending on ow you plan to construct them, you could save some money by using 1/2” for the sides. Using 3/4 for wall cabinet boxes is really overkill. -- Charlie M. "Woodworking - patience = firewood" TheDane 5056 posts in 3233 days #7 posted 09-02-2010 03:52 PM I used 3/4” birch ply and French cleats for the cabinets in my garage … thought about MDF, but I avoid that stuff like the plague for anything that needs to take hard use and abuse. -- Gerry -- "I don't plan to ever really grow up ... I'm just going to learn how to act in public!" #8 posted 09-02-2010 04:59 PM Greetings again, Vrtigo, Thanks for looking at the shop..thought it might give you some ideas of what the birch would look like.. The reason I have 2 tablesaws back to back is two-fold…The old Craftsman was my very first saw that bought in about 1985-86(?). I used it all those years in my shops, and being a contractor saw, it was a 3 hp. But I always wanted a cabinet saw (and Delta).. I bought a new Delta X5, 5 hp. last year, and this sucker is abeast…I now use it for all my main cutting of material, and decided to keep the old saw for dados and rabbits.A few months ago I built a new cabinet system for it(you can check it out on my blog( a new look for an old workhorse)moved it to the other side of the outfeed table I built for the new one, and have them back to back…Plus #9 posted 09-02-2010 05:28 PM Makes sense, Rick. I bet it’s nice not having to change out the stacked dado set. Everyone else, thanks for the replies. I think I will go with 3/4 birch for the backs and make the rest out of 1/2” birch. Lee Barker 2170 posts in 2420 days #10 posted 09-02-2010 06:07 PM Industry standard is 3/4 or 5/8 materials for the case, 1/4 for the back. I don’t think you’d get a good joint between the face frame and the case if you used 1/2 material for the case. Further, you’d likely have issues with whatever shelf support system you chose for the inside. Melamine products are a natural for this project. No painting, as has been noted, and the light colors will really contribute to the overall brightness in your garage, something that becomes more important as we age. Another beauty of MM and MDF is the lack of grain—it makes for more effiicient use of the material. The best way to deal with the exposed edges is edgebanding, which can be done low-tech with your basic thrift store Mary Proctor iron. Good matching paint is an option. If you apply the 1/4 back without a rabbet in the case, you have covered that edge; the faceframe covers the front, so all you need to edgeband is the top and bottom edges of the sides. I’d suggest you look for an alternative to the pine for faceframes. It doesn’t like to stay straight and is not fond of holding hinge screws. I am not sure what would be the right choice in your part of the country. Regarding the comments about particle board and mdf holding screws, the answer to that is don’t use them. Biscuits are a great way to joint the case pieces. (If you don’t have that facility, rabbet the sides (1/3 deep) and use pin nails.) Use Extend glue, slather the four pieces together, clamp, and then apply the already-built faceframe and clamp it. (You can also biscuit the ff on, but it’s not really necessary. If you do, cut just the bottom rail and one stile—let the rest land where they may and just glue them.) The 2 1/4 nailers go inside the back, top and bottom for uppers, and the 1/4 back (any material—you’ll never see it) over that. Done! My apologies for the windiness of this reply. -- "...in his brain, which is as dry as the remainder biscuit after a voyage, he hath strange places cramm'd with observation, the which he vents in mangled forms." --Shakespeare, "As You Like It" dbhost 5643 posts in 2802 days #11 posted 09-02-2010 06:25 PM I have had VERY bad experiences with MDF in coastal Texas. Florida can’t be much better. I know good quality plywood is a bit on the spendy side, but it is well worth it. Cheap plywood however, will have you cursing the day you walked into the lumber yard! Not sure if they are in Florida, but I have found Sutherlands to have good birch and oak cabinet grade plywood. -- My workshop blog can be found at, YouTube Channel TYT300 1 post in 187 days #12 posted 09-17-2016 02:25 AM I only have experience using plywood (Birch) but was considering MDF for a new garage cabinet project. I’m strongly leaning towards plywood. Don’t mind the cost, just want to be sure the project yields good results when it’s done…don’t want to have to re-invest later to replace. Since my project will be birch plywood instead of pine, I’m assuming my painted finish will have better results. MDF 0Plywood 1 woodbutcherbynight 2830 posts in 1979 days #13 posted 09-17-2016 03:00 AM How deep will the cabinets be? If you want solid wood gluing some together to your width might be an option. Now if you want something to look furniture grade this gets pricey but I just got done with three cabinets 18 inch deep for a neighbor out of HERE IT COMES…... white wood #2 from the Borg. Homeowner requested, not my choice. But they are flat, and took paint well. If not, spend money on some good birch ply and edge them with some wood of your choice and it should look good ad hold up for years. my 2 cents worth anyway I would admit most of my shop cabinets are recycled from older homes, back when they used wood not MDF or tree barf like they do now. (laughing) -- Live to tell the stories, they sound better that way. realcowtown_eric 581 posts in 1507 days #14 posted 09-17-2016 03:08 AM import shop birch 3/4” ply would be my choice, And although the “industry standard” metioned before is 1/4” back, I just always use 5/8 or 3/4” back. I’ve repaired a few too many of those “industry standard 1/4” back” failures to put any trust in them, and besides, by the time you get fussing around with 3 or 4 sheet stock sizes, setting up etc, you don’t use any space…. (EG 1/4” back plus a flimsy 1/2” nailing strip, yer at 3/4” anyway. So you can just use a 3/4” back and put as many screws as you want. One of my neighbours was injured when the uppers failed and fell on her and I have my own story to tell some other time If you use 5/8” material, 1/4” back. 1/2” nailing strips, ...you gotta make cut diagrams for each size, set up seperate dados/rabbets, and I could never figure out why folks would fuss like that. To me, cut to size, set up a dado and cutt all the dados at once….one size fits all and waste is minimized. And besides, if yer cutting square you don’t have the sloppy fit of that 1/4” back that allows racking of cabinets.Make em square, install them level and bob’s yer uncle. . Key is absolute squareness. Not hard to achieve If not square you got a mess! Price wise, import shop birch is sometimes even less than 5/8 mcp or 3/4 MDF. Watch the prices of small suppliers, and use the match and beat aspect of the bib borg pricing promises! Eric in calgary -- Real_cowtown_eric MT_Stringer 2954 posts in 2801 days #15 posted 09-17-2016 03:32 AM 3/4 birch for the sides. No back; 3/4 inch french cleats. Cabinets are 14 inches deep. --
http://lumberjocks.com/topics/19959
CC-MAIN-2017-13
refinedweb
2,128
78.18
LeagueAPI - Documentation It is designed to be easy to use, taking advantage of Swift enums. It also comes with some internal mechanisms, to handle any API key rate limit. Support League of Legends, Clash, Teamfight Tactics and League of Runnetera APIs 🚧 Installation 🚧 Carthage - Go in your project, in the folder where is located YourProject.xcodeproj. - Create a file named Cartfile and write github "Kelmatou/LeagueAPI"in it. - Run carthage bootstrap --platform iOSin Terminal. - Open YourProject.xcodeproj and go to target General settings. - Add LeagueAPI.framework in Embedded Binaries. - If you can write import LeagueAPIin your project without compiler error, you're done. Great job! If it is not the case, read the troubleshooting section below. CocoaPods - Go in your project, in the folder where is located YourProject.xcodeproj. - Run pod init. - Open Podfile for editing (do not use Textedit as it will insert invalid characters). - Right under "use_frameworks!", write pod 'LeagueAPI'. - Run pod install. - A YourProject.xcworkspace was created. From now, you should open this file instead of YourProject.xcodeproj. - If you can write import LeagueAPIin your project without compiler error, you're done. Great job! If it is not the case, you can open an issue so that I can look at your problem. Manual - Download a Release version here (or Github content but you may get a version with experimental changes). - Open LeagueAPI/LeagueAPI.xcodeproj. - Select LeagueAPI-Release scheme and build it (play button or cmd+b) for your desired platform (Simulator or iOS Generic Device). - In the Project Navigator, you'll find a folder Products with LeagueAPI.framework. Drag and drop it in your project general settings -> Embedded Binaries. - If you can write import LeagueAPIin your project without compiler error, you're done. Great job! If you encounter a problem on this step, check if you selected the same platform as LeagueAPI.framework in you project's destination target (Simulator or iOS device). If it does not solve your problem, read the troubleshooting section below. Troubleshooting This section lists the main solutions to be able to import LeagueAPI in your project. - Go back to your project, target settings -> Build Settings -> Framework Search Paths, then add the path to LeagueAPI.framework. If none of these helped you, open an issue describing your problem and I'll try to check it out as soon as possible. 📋 Requirements 📋 📦 Minimum versions 📦 📱 iOS 8.1 ⌚ WatchOS 2.0 📺 TvOS 9.0 💻 MacOS 10.9 (Mavericks) 🔑 Riot API Key 🔑 To use LeagueAPI, you'll require a Riot API Key. You'll get one by visiting. Create an account and on you dashboard, you'll be able to generate your key. By default, Riot will generate a 'Development Key', which expires in 24h. When your application is ready to be deployed and respects Riot API usage conditions, you can apply for a 'Production Key'. Please note that you should agree with Riot API usage policy 😈 First Blood 😈 Starting using this framework requires you to create an instance of LeagueAPI by writing: let league = LeagueAPI(APIToken: "*INSERT YOUR KEY HERE*") Now use this instance everywhere, you shouldn't recreate the LeagueAPI variable. 🧐 And then? 🧐 LeagueAPI is divided in 4 different APIs: - Riot API - League of Legends API - Team Fight Tactics API - Legends of Runnetera API Riot API Riot API returns information about Riot Games accounts for each player. It is accessible from league.riotAPI. From there you'll access the methods for: League of Legends API League of Legends API contains methods related to League of Legends game. It is accessible through league.lolAPI. From there you'll get information about: League of Legends - Summoners - Spectator/Live Game - Ranked/Leagues - Ranked/Leagues EXP - Match History - Champion Mastery - Champions - Server Status - Verification Code - Tournament Stub - Tournaments - Patch - Profile Icons - Items - Summoner Spells - Runes - Ranked Tier - Champions Detailed - deprecated from 3.0.0 Clash Teamfight Tactics Teamfight Tactics API contains methods related to Teamfight Tactics game. It is accessible through league.tftAPI. From there you'll find information for: Legends of Runnetera Legends of Runnetera API contains methods related to Leagueof Runnetera game. It is accessible through league.lorAPI. From there you'll get information about: Full documentation is available here. Note that only the last release will appear in the documentation. See previous revisions for older LeagueAPI versions. Make LeagueAPI Grow Up! If anything you wanted was missing, do not hesitate to open an issue or create a pull request. It could help future developers. If you found LeagueAPI helpful or cool to use don't hesitate to promote it by adding a ⭐️ 😉 Contributors Antoine Clop (Kelmatou) Ronan Cendrier (Hanoki) Ammon Parry (AmmonP) Sandi Karajic (SKarajic)
https://swiftpack.co/package/Kelmatou/LeagueAPI
CC-MAIN-2021-04
refinedweb
770
66.74
I thought I’d post a quick refresher for sorting Lists<> and generics since it will be used in the post about working with Sitecore Fast Query. There are a lot of ways of sorting items you get back from Sitecore, including even implementing a bubble sort in the code-behind aspx.cs file. That may work for a quick prototyping exercise; however, when working with enterprise class systems, why not leverage the tools C# gave you to create elegant and robust code by creating line-of-business model objects and using a C# List<T> that already comes with sort functionality (provided you define the rules on how to compare your objects)? IComparable If you want to your objects to be sortable, you have to make sure they implement the IComparable method, otherwise when you try to do a List<T>.Sort() on them, you will get an exception. To implement the IComparable class, you will need to implement the CompareTo() method, which essentially describes how to compare two objects. If you compare your objects alphabetically, you can take advantage of the String.CompareTo() method here. Take a look at the code example below using a Movie object. public class Movie : IComparable { public int YearReleased { get; set; } public string MovieTitle { get; set; } //need to implement this as a result //of declaring the IComparable interface int CompareTo(Movie otherMovie) { return MovieTitle.CompareTo(otherMovie.Title); } } IComparer When you implement the IComparable interface and the CompareTo method, that is the default sort method. When you want to create additional properties on which to sort, this is where the IComparer interface comes in. For every method on which you will want to sort, you will have to create a class that implements the IComparer interface. So, if you wanted to create two sorts – ascending and descending – on the year the movie was released, you will need two classes that implement the IComparer interface. With this particular example, we can create these classes as nested. public class Movie : IComparable //main class { public int YearReleased { get; set; } public string MovieTitle { get; set; } public class SortByYearReleasedAscending : IComparer { int Compare(Movie a, Movie b) { var compareResult = a.YearReleased - b.YearReleased; return ( (compareResult == 0) ? 0 : compareResult / Math.Abs(compareResult) ); } } public class SortByYearReleasedDescending : IComparer { } } In case I lost you in the Compare() method, I am all about C# shortcuts (thanks to ReSharper) and didn’t feel like writing this out: if (a.year > b.year) return 1; if (a.year < b.year) return -1; else return 0; Since the year is an integer, we can just take the difference. If the value on the left is bigger, the result will be positive, otherwise negative. At that point, we will need to return 1, -1, or if it’s the same, the result is 0. To get our result down to a 1 (positive or negative), we simply divide by the absolute value of the result, but not before we check if it’s 0 to bypass the divide by zero error. And that’s all there is to it. To piece it all together, if you have a List<movieList>, you can do a sort on it using movieList.Sort() which will use the default IComparable.CompareTo method, or you can specify how you want it sorted by passing in the IComparer component, like movieList.Sort(new movieList.SortByYearReleasedAscending()) Questions or comments – drop me a line. Really good post on a topic that I’m sure comes up a lot. I recently wrote a bunch of sort extension methods for one of my projects but I used some LINQ magic to use lambda expressions and delegate the comparisons to the actual fields I’m sorting on. E.g. to sort a list of author items alpha by last name: ... authors.Sort((a1, a2) => a1.LastName.CompareTo(a2.LastName)); ... Excellent point. Delegates and Predicates are definitely great for that. I don’t think I can fit that into this post, but it definitely deserves its own. Thanks for visiting!
http://blog.image0.com/sitecore/tutorial-refresher-on-sorting-generics-in-c-icomparable-icomparer/
CC-MAIN-2013-20
refinedweb
669
62.27
Pyrex 0.4.2 is now available: This version should fix the problem introduced in 0.4.1 that prevented extension classes from showing up in the module namespace. There is also a significant new language feature: C functions which don't return Python objects can now be declared so that they will propagate exceptions to their callers. See "Error Return Values" in the Language Overview. There are numerous other bug fixes and improvements. See the CHANGES file in the distribution for details. Pyrex is a new language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand python-announce-list@python.org
https://mail.python.org/archives/list/python-announce-list@python.org/thread/GMFZL4MSZDSSYDCHHWRSOGO5XV2DOTTJ/?sort=date
CC-MAIN-2020-40
refinedweb
130
57.87