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
> This will break that fix. Not that I actually agree, but in fact I > didn't think about the problem. Hopefully, it won't. I've moved the fix until later in the code, after the conversion to UTF8, so that I don't have to do so many string operations on a ByteBuf: +#ifndef XP_TARGET_COCOA + /*work around "helvetica" font name -replace it with "Helvetic"*/ + if (strcmp(fn[0], "helvetica") == 0) + { + fn[0][0] = 'H'; + } +#endif /* ! XP_TARGET_COCOA */ Best, R. Received on Sun Jun 12 07:04:10 2005 This archive was generated by hypermail 2.1.8 : Sun Jun 12 2005 - 07:04:10 CEST
http://www.abisource.com/mailinglists/abiword-dev/2005/Jun/0203.html
CC-MAIN-2015-22
refinedweb
105
66.74
49125/python-unicodeencodeerror-encode-character-position-ordinal I'm trying to write a to a csv file, I get the following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) Line causing error: df.to_csv('out.csv') use the sep argument of to_csv, to delimit by a tab: df.to_csv(file_name, sep='\t') To use a specific encoding (e.g. 'utf-8') use the encoding argument: df.to_csv(file_name, sep='\t', encoding='utf-8') I am sure this helped to answer your query, cheers! For more, join this course to Master Python programming. Thanks! import csv import sys reload(sys) sys.setdefaultencoding('utf8') data = [["a", "b", u'\xe9']] with open("output.csv", "w") as csv_file: writer = csv.writer(csv_file, quoting=csv.QUOTE_ALL) writer.writerows(data) Hi. I am getting the following error when I ran this script: NameError: name 'reload' is not defined Use the following line to import the module from importlib import reload In Python 2, this was in build but in python, you've to use importlib. You are getting this error because you ...READ MORE This error occurs because you are using ...READ MORE This is my code, i want python ...READ MORE import speech_recognition as sr r = sr.Recognizer() audio ='C\Users\Desktop\audiofile1.wav' with ...READ MORE You can also use the random library's ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE Enumerate() method adds a counter to an ...READ MORE You can simply the built-in function in ...READ MORE add the following line on top of ...READ MORE You have to use the encoding as latin1 ...READ MORE OR At least 1 upper-case and 1 lower-case letter Minimum 8 characters and Maximum 50 characters Already have an account? Sign in.
https://www.edureka.co/community/49125/python-unicodeencodeerror-encode-character-position-ordinal?show=50339
CC-MAIN-2022-21
refinedweb
304
68.57
Journal tools | Personal search form | My account | Bookmark | Search: ... verne country club score yardage card winston aluminum patio furniture business ...lexington fine homes anime black download episode jack richard alexander alias ...court india and population growth black bra woman gate indoor iron...future mark squires bb black white dress shoes all about dogs...center madison wisconsin tv party black flag dubois bookstore miami subros... ... qualifier c yellow chamber takagism black bros white hoe elizabeth horse ... or rental or chicago new jack johnson tabs accessory computer computer ... consultant merion golf club pa card france germany international phone prepaid... to get an american express black card animal right terrorist satellite...italian language in italy golf shoes greenjoy charles la lake newspaper... ...tip and trick bank citizen number phone business card logo ideas turned into bear black cat jack discount real estate ... how to back up x box games black model photo woman based business home job ... ohio life is elsewhere circle friend poem jack o lantern art projects media player 9 download alias golf shoes animal even here in mute some them ... ... court goodyear american eagle review black cinch etnies shoes white white classroom science...cat figurine american film archives treasures jack the ripper paintings armored core music...man owa exchange 2003 change password black masculinity conference american vehicle insurance ....com make money mailing post card pandaantivirusonline commercial insurance quote uk ... ... plunge polar dark angel clothing black college picture track woman recently ... long soleil sport sunblock headphone jack to rca delaware state news ... service pack 3 musicnow download card computer instruments eivr overdraft protection bank of america brazil calling card phone womens gymnastics pictures cheap ...40's look peeptoe black ankle strap shoes cat urine on ... ...fall out boy master card black card best get pregnant time...framingham 2006 cheatbook database download black boxer dog white application of...breakfast benton persephone yellow box shoes for kids michael timothys urban...program at t prepaid phone card asia intermountain health group amli...vw web p2p torrent download jack mannequins motivation in physical education... ...annies fine furniture anime black download episode jack martin burke associates...cable cat5e manufacturer avermedia pcmcia card tv tuner for laptopnotebooks bungee ...purchase us time magazine old black and white photos of men...the future jennifer carrasco black white dress shoes dogs scoot pathos...starting small business in ontario black and white soccer ball government... ...how to get an american express black card washington university internal medicine residency... you quiz mcgeorge lawschool wooden longbows jack o lantern contest winner buyer beware ...forbes professions merchant phone no credit card required english importance american folk festival...cables door glass handle buy bally shoes online james fiorentino used dental equipment... ... chart def jam comedy torrent black cat train heartnet boblong intimidators ... com custom deanos air black force one shoes custom hotrods car ...classified download ea uk website card dell driver sound south spain...alfred mcalpine business services barbie black comforter hauppauge drivers mce main...music video code vg cats jack uk mistress lists the german... ...seeping into those polished Prada shoes. He swore he could hear...She wants her children in black and crying, even Brian wishing...hand. She can almost hear Jack hitting Brian in the next...bends down to untie his shoes, Justin runs his lips from...novel, dressed in a long black jacket, lips blood red from...now. There is a simple card on the desktop with a...desolate. He only sees in black and white. Work holds no... Alabama Jack Black Black Card Jack Strategy Black Jack Black Card Jack Dogs Basic Black Card Jack Strategy Gambling Black Card Jack Odds Jack Counties Black Card Jack Tip Jack Daniels Black Card Jack Play Jack Johnson Black Card Jack Split Jack Nicholson Black Card Jack Printable Strategy Jack Russell Black Card Jack Look Reader Table Jack Russell Terrier Result Page: 1 2 3 4 5 6 7 8 9 for Black Card Jack Shoes
http://www.ljseek.com/Black-Card-Jack-Shoes_s4Zp1.html
crawl-002
refinedweb
653
58.89
Download presentation Presentation is loading. Please wait. Published byTiffany French Modified over 4 years ago 1 Introduction to Object Oriented Programming 2 Object Oriented Programming Technique used to develop programs revolving around the real world entities In OOPs, every real life object has properties and behavior. 3 Features of OOP Language Abstraction Inheritance Encapsulation Polymorphism 4 Object The basic entity of object oriented programming language. Class itself does nothing but the real functionality is achieved through their objects. Object is an instance of the class. It takes the properties (variables) and uses the behavior (methods) defined in the class. The concept that all objects, while being unique, are also part of a set of objects that have characteristics and behaviors in common 5 State of an object The set of values of the attributes of a particular object is called its state 6 Class Defines the properties and behavior (variables and methods) that is shared by all its objects. A class is a piece of computer program that serves as a template for the creation of an object 7 Name Age Color Weight Name-Lassie Age-4y Color-Brown/Black Weight-60Kg Name-Tommy Age-6y Color-Black Weight-65Kg Name-sprinter Age-4y Color-Brown/Black Weight-68Kg Name-Lany Age-6y Color-Brown/Black Weight-62Kg Dog Class Objects 8 Instance The actual object created at run-time The Lassie object is an instance of the Dog class 9 Abstraction The process of abstraction in Java is used to hide certain details and only show the essential features of the object. 10 Encapsulation. 11 Inheritance Allows a class (subclass) to acquire the properties and behavior of another class (superclass). In java, a class can inherit only one class (superclass) at a time but a class can have any number of subclasses. It helps to reuse, 12 Polymorphism Allows one interface to be used for a set of actions i.e. one name may refer to different functionality. Polymorphism allows a object to accept different requests of a client and responds according to the current state of the runtime system 13 Two types of polymorphism Compile-time polymorphism Runtime Polymorphism 14 Compile-time polymorphism Method to be invoked is determined at the compile time. Compile time polymorphism is supported through the method overloading concept Method overloading means having multiple methods with same name but with different signature (number, type and order of parameters). 15 Runtime Polymorphism Method to be invoked is determined at the run time. The example of run time polymorphism is method overriding. When a subclass contains a method with the same name and signature as in the super class then it is called as method overriding. 17 Declaring Classes class MyClass { //field, constructor, and method declarations } The class body is the area between the braces. It contains constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects. 18 Constructors A class contains constructors that are invoked to create objects from the class blueprint When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called Constructors are used to initialize the instance variables (fields) of an object. 19 Constructors Constructor name is class name. A constructors must have the same name as the class its in. Default constructor is created automatically by the compiler only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created. The default constructor initializes all instance variables to default value (zero for numeric types, null for object references, and false for booleans). 20 Differences between methods and constructors There is no return type given in a constructor signature (header). The value is this object itself There is no return statement in the body of the constructor The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameterless super class constructor. 21 this(...) Calls another constructor in same class. 22 super(...) Use super to call a constructor in a parent class. Calling the constructor for the super class must be the first statement in the body of a constructor. 23 Passing Information to a Method or a Constructor Parameters refers to the list of variables in a method declaration. Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order. 24 Declaring Member Variables There are several kinds of variables * Member variables in a class—these are called fields. * Variables in a method or block of code— these are called local variables. * Variables in method declarations—these are called parameters. 25 Field declarations are composed of three components 1. Zero or more modifiers, such as public or private. 2. The field's type. 3. The field's name. 26 Access Modifiers control what other classes have access to a member field * public modifier—the field is accessible from all classes. * private modifier—the field is accessible only within its own class. 27 Types Variables must have a type. Use primitive types such as int, float, boolean, etc. Or you can use reference types, such as strings, arrays, or objects. 28. 29 Transient Variables member variables are part of the persistent state of the object Member variables that are part of the persistent state of an object must be saved when the object is archived transient keyword to indicate to the Java virtual machine that the indicated variable is not part of the persistent state of the object Transient int totalAvg; 30 Volatile Variables If a member variable is modified asynchronously by concurrently running threads the volatile variable is loaded from memory before each use, and stored to memory after each use thereby ensuring that the value of the variable is consistent and coherent within each thread 31 Defining Methods The required elements of a method declaration are the Modifiers—such as public, private method's return type Name a pair of parentheses () and parameter list in parenthesis and a body between braces {} 32 Overloading Methods distinguish between methods with different method signatures means that methods within a class can have the same name if they have different parameter lists 33 Method Overriding achieved when a subclass overrides non-static methods defined in the superclass. The new method definition must have the same method signature (i.e., method name and parameters) and return type. Only parameter types and return type are chosen as criteria for matching method signature 34 Creating Objects A class provides the blueprint for objects Create an object from a class Creating Objects includes three parts 1. Declaration: 2. Instantiation: The new keyword is a Java operator that creates the object. 3. Initialization: The new operator is followed by a call to a constructor, which initializes the new object. 35 Declaring a Variable to Refer to an Object To declare a variable.This declaration also reserves the proper amount of memory for the variable type name; declaring a variable to hold an object is just like declaring a variable to hold a value of primitive type its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, 36 Instantiating an Object used new operator to create a new instance of an object.. 37 Initializing an Object classes provide constructor methods to initialize a new object of that type. A class may provide multiple constructors to perform different kinds of initialization on new objects. When looking at the implementation for a class, you can recognize the constructors because they have the same name as the class and have no return type. 38 Referencing an Object's Variables To access an object's variables, simply append the variable name to an object reference with an intervening '.' (period). dogObj1.name=“Lassie”; dogObj1.age=1; 39 Calling an Object's Methods Calling an object's method is similar to getting an object's variable. To call an object's method, simply append the method name to an object reference with an intervening '.' (period), provide any arguments to the method within enclosing parentheses. If the method does not require any arguments, just use empty parentheses. dogObj1.setName(“Lassie”); 40 The Garbage Collector. 41 Finalization Before an object gets garbage collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. This process is known as finalization. protected void finalize() throws Throwable 42 Public, Abstract, and Final Classes The public modifier declares that the class can be used by objects outside the current package. By default a class can only be used by other classes in the same package in which it is declared. The abstract modifier declares that your class is an abstract class. An abstract class may contain abstract methods (methods with no implementation). Abstract classes are intended to be subclassed and cannot be instantiated. the final modifier you declare that your class is final; that is, that your class cannot be subclassed. 43 Abstract Classes a class that you define an abstract concept and should not be instantiated. for example, Mammal class in the real world. Have you ever seen an instance of Mammal ? What you see instead are instances of Dogs,Cats,Lions,Bats abstract class Number { } 44 Abstract Methods methods with no implementation. abstract void getName(); 45 Final Classes declare a class as final; that is, that class cannot be subclassed. final class Dog { } 46 Final Methods protect class's methods from being overridden, can use the final keyword in a method declaration to indicate to the compiler that the method cannot be overridden by subclasses 47 Declaring Constants To create a constant member variable in Java use the keyword final in your variable declaration. final double AVOGADRO = 6.023e23; 49 Classes can be derived from other classes, thereby inheriting fields and methods from those classes. A class that is derived from another class is called a sub class (also a derived class, extended class, or child class). The class from which the subclass is derived is called a super class (also a base class or a parent class). public class Dog extends Mammal { } 50 Inheritance Can reuse the fields and methods of the existing class without having to write them A subclass inherits the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. 51 *. 52 Private Members in a Superclass A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. 53 A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. 54 Creating and Using Interfaces An interface is a collection of method definitions (without implementations) and constant values. Similar presentations © 2019 SlidePlayer.com Inc.
http://slideplayer.com/slide/7001351/
CC-MAIN-2019-43
refinedweb
1,936
50.46
This document covers the following topics: Within the past few years IPv6 has gained much greater acceptance in the industry, especially in certain regions of the world, i.e., Europe and the Asian Pacific. Extensibility, mobility, quality of service, larger address space, auto-configuration, security, multi- homing, anycast and multicast, and renumbering—these are some of the features of IPv6 that make it desirable. With the release of J2SE 1.4 in February 2002, Java began supporting IPv6 on Solaris and Linux. Support for IPv6 on Windows was added with J2SE 1.5. While other languages, such as C and C++ can support IPv6, there are some major advantages to Java: We will prove these statements with code examples below and provide additional details on IPv6 support. The following operating systems are now supported by the J2SE reference implementation: Using IPv6 in Java is easy; it is transparent and automatic. Unlike in many other languages, no porting is necessary. In fact, there is no need to even recompile the source files. Consider an example from The Java Tutorial:); } // ... code omitted here communicateWithEchoServer(out, in); out.close(); in.close(); stdIn.close(); echoSocket.close(); You can run the same bytecode for this example in IPv6 mode if both your local host machine and the destination machine (taranis) are IPv6-enabled. In contrast, if you wanted the corresponding C program to run in IPv6 mode, you would first need to port it. Here's what would need to happen: struct sockaddr_in sin; struct hostent *hp; int sock; /* Open socket. */ sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { perror("socket"); return (-1); } /* Get host address */ hp = gethostbyname(hostname); if (hp == NULL || hp->h_addrtype != AF_INET || hp->h_length != 4) { (void) fprintf(stderr, "Unknown host '%s'\n", hostname); (void) close(sock); return (-1); } sin.sin_family = AF_INET; sin.sin_port = htons(port); (void) memcpy((void *) &sin.sin_addr, (void *)hp->h_addr, hp->h_length); /* Connect to the host */ if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1) { perror("connect"); (void) close(sock); return (-1); } struct addrinfo *res, *aip; struct addrinfo hints; int sock = -1;); } /* Try all returned addresses; } freeaddrinfo(res); Note that for new applications, if you write address-family-agnostic data structures, there is no need for porting. However, when it comes to server-side programming in C/C++, there is an additional wrinkle. Namely, depending on whether your application is written for a dual-stack platform, such as Solaris or Linux, or a single-stack platform, such as Windows, you would need to structure the code differently. For server-side programming, Java shows a big advantage. You still write the same code as before: ServerSocket server = new ServerSocket(port); Socket s; while (true) { s = server.accept(); doClientStuff(s); } Now, however, if you run the code on an IPv6-enabled machine, you immediately have an IPv6-enabled service. Here's the corresponding server C code for a dual-stack platform: int ServSock, csock; struct sockaddr addr, from; ... ServSock = socket(AF_INET6, SOCK_STREAM, PF_INET6); bind(ServSock, &addr, sizeof(addr)); do { csock = accept(ServSocket, &from, sizeof(from)); doClientStuff(csock); } while (!finished); Notice that on a dual-stack machine, since one socket, the IPv6 socket, will be able to access both IPv4 and IPv6 protocol stacks, you only need to create one socket. Thus this server can potentially support both IPv4 and IPv6 clients. Here's the C code for the same server for a single-stack platform: SOCKET ServSock[FD_SETSIZE]; ADDRINFO AI0, AI1; ServSock[0] = socket(AF_INET6, SOCK_STREAM, PF_INET6); ServSock[1] = socket(AF_INET, SOCK_STREAM, PF_INET); ... bind(ServSock[0], AI0->ai_addr, AI0->ai_addrlen); bind(ServSock[1], AI1->ai_addr, AI1->ai_addrlen); ... select(2, &SockSet, 0, 0, 0); if (FD_ISSET(ServSocket[0], &SockSet)) { // IPv6 connection csock = accept(ServSocket[0], (LPSOCKADDR)&From, FromLen); ... } if (FD_ISSET(ServSocket[1], &SockSet)) // IPv4 connection csock = accept(ServSocket[1], (LPSOCKADDR)&From, FromLen); ... } Here you need to create two server sockets, one for IPv6 stack and one for IPv4 stack. You also need to multiplex on the two sockets to listen to connections from either IPv4 or IPv6 clients. With Java you can run any Java applications, client or server, on an IPv6-enabled platform using J2SE 1.4 or later, and that application will automagically become IPv6-enabled. Contrasting this with legacy, native-language applications, if you wanted any C/C++ applications to be IPv6-enabled, you would need to port and recompile them. The Java networking stack will first check whether IPv6 is supported on the underlying OS. If IPv6 is supported, it will try to use the IPv6 stack. More specifically, on dual-stack systems it will create an IPv6 socket. On separate-stack systems things are much more complicated. Java will create two sockets, one for IPv4 and one for IPv6 communication. For client-side TCP applications, once the socket is connected, the internet-protocol family type will be fixed, and the extra socket can be closed. For server-side TCP applications, since there is no way to tell from which IP family type the next client request will come, two sockets need to be maintained. For UDP applications, both sockets will be needed for the lifetime of the communication. Java gets the IP address from a name service. You don't need to know the following in order to use IPv6 in Java. But if you are curious and what to know what happens under various circumstances, the remainder of this document should provide answers. This is also called anylocal or wildcard address. If a socket is bound to an IPv6 anylocal address on a dual-stack machine, it can accept both IPv6 and IPv4 traffic; if it is bound to an IPv4 (IPv4-mapped) anylocal address, it can only accept IPv4 traffic. We always try to bind to IPv6 anylocal address on a dual-stack machine unless a related system property is set to use IPv4 Stack. When bound to ::, method ServerSocket.accept will accept connections from both IPv6 or IPv4 hosts. The Java platform API currently has no way to specify to accept connections only from IPv6 hosts. Applications can enumerate the interfaces using NetworkInterface and bind a ServerSocketChannel to each IPv6 address, and then use a selector from the New I/O API to accept connections from these sockets. However, there is a new socket option that changes the above behaviour. Draft-ietf-ipngwg-rfc2553bis-03.txt has introduced a new IP level socket option, IPV6_V6ONLY. This socket option restricts AF_INET6 sockets to IPv6 communications only. Normally,. By default this option is turned off. Packets with the loopback address must never be sent on a link or forwarded by an IPv6 router. There are two separate loopback addresses for IPv4 and IPv6 and they are treated as such. IPv4 and IPv6 addresses are separate address spaces except when it comes to "::". This is used for hosts and routers to dynamically tunnel IPv6 packets over IPv4 routing infrastructure. It is meaningful for OS kernel and routers. Java provides a utility method to test it. This is an IPv6 address that is used to represent an IPv4 address. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. Thus, on a dual-stack node with IPv4-mapped address support, an IPv6 application can talk to both IPv4 and IPv6 peer. The OS will do the underlying plumbing required to send or receive an IPv4 datagram and to hand it to an IPv6 destination socket, and it will synthesize an IPv4-mapped IPv6 address when needed. For Java, it is used for internal representation; it has no functional role. Java will never return an IPv4-mapped address. It understands IPv4-mapped address syntax, both in byte array and text representation. However, it will be converted into an IPv4 address. On dual stack machines, system properties are provided for setting the preferred protocol stackIPv4 or IPv6as well as the preferred address family typesinet4 or inet6. IPv6 stack is preferred by default, since on a dual-stack machine IPv6 socket can talk to both IPv4 and IPv6 peers. This setting can be changed through the java.net.preferIPv4Stack=<true|false> system property. By default, we would prefer IPv4 addresses over IPv6 addresses, i.e., when querying the name service (e.g., DNS service), we would return Ipv4 addresses ahead of IPv6 addresses. There are two reasons for this choice: This setting can be changed through the system property java.net.preferIPv6Addresses=<true|false> For many years, if not forever, there will be a mix of IPv6 and IPv4 nodes on the Internet. Thus compatibility with the large installed base of IPv4 nodes is crucial for the success of the transition from IPv4 to IPv6. Dual stack, defined in RFC 1933, is one of the main mechanisms for guaranteeing a smooth transition. The other mechanism is IPv6 packet tunneling, which is relevant to the JDK only through the IPv4-compatible address. The former is the most relevant piece to the JDK. A dual stack includes implementations of both versions of the Internet Protocol, IPv4 and IPv6.. However, unless a socket checks for the peers address type, it won't know whether it is talking to an IPv4 or an IPv6 peer. All the internal plumbing and conversion of address types is done by the dual-protocol stack. Note: IPv4-mapped address has significance only at the implementation of a dual-protocol stack. It is used to fake (i.e., appear in the same format as) an Ipv6 address to be handed over to an IPv6 socket. At the conceptual level it has no role; its role is limited at the Java API level. Parsing of an IPv4-mapped address is supported, but an IPv4-mapped address is never returned.DK. sun.net.spi.nameservice.provider.<n>=<default|dns,sun|...> Specifies the name service provider that you can use. By default,. sun.net.spi.nameservice.domain=<domainname> This property specifies the default DNS domain name, e.g., eng.sun.com.
http://java.sun.com/j2se/1.5.0/docs/guide/net/ipv6_guide/index.html
crawl-002
refinedweb
1,663
55.54
Use Case - Displaying Text In QML Displaying and Formatting Text To display text in QML, create a Text item and set the text property to the text you wish to display. The Text item will now display that text. Several properties can be set on the Text item to style the entire block of text. These include color, font family, font size, bold and italic. For a full list of properties, consult the Text type documentation. Rich text like markup can be used to selectively style specific sections of text with a Text item. Set Text::textFormat to Text.StyledText to use this functionality. More details are available in the documentation of the Text type. Laying Out Text By default, Text will display the text as a single line unless it contains embedded newlines. To wrap the line, set the wrapMode property and give the text an explicit width for it to wrap to. If the width or height is not explicitly set, reading these properties will return the parameters of the bounding rect of the text (if you have explicitly set width or height, you can still use paintedWidth and paintedHeight). With these parameters in mind, the Text can be positioned like any other Item. Example Code import QtQuick 2.3 Item { id: root width: 480 height: 320 Rectangle { color: "#272822" width: 480 height: 320 } Column { spacing: 20 Text { text: 'I am the very model of a modern major general!' // color can be set on the entire element with this property color: "yellow" } Text { // For text to wrap, a width has to be explicitly provided width: root.width // This setting makes the text wrap at word boundaries when it goes past the width of the Text object wrapMode: Text.WordWrap // You can use \ to escape quotation marks, or to add new lines (\n). Use \\ to get a \ in the string text: 'I am the very model of a modern major general. I\'ve information vegetable, animal and mineral. I know the kings of england and I quote the fights historical; from Marathon to Waterloo in order categorical.' // color can be set on the entire element with this property color: "white" } Text { text: 'I am the very model of a modern major general!' // color can be set on the entire element with this property color: "yellow" // font properties can be set effciently on the whole string at once font { family: 'Courier'; pixelSize: 20; italic: true; capitalization: Font.SmallCaps } } Text { // HTML like markup can also be used text: '<font color="white">I am the <b>very</b> model of a modern <i>major general</i>!</font>' // This could also be written font { pointSize: 14 }. Both syntaxes are valid. font.pointSize: 14 // StyledText format supports fewer tags, but is more efficient than RichText textFormat: Text.StyledText } } } Internationalization and Scalability When dealing with texts, applications must take into account various topics such as the device's orientation and the language settings. The following pages go into detail about these various.
https://doc.qt.io/archives/qt-5.7/qtquick-usecase-text.html
CC-MAIN-2019-43
refinedweb
497
63.09
Im trying to write a program that reads from a text file and then outputs the total words, most words per line, total bumber of lines and average words per line. The problem is that ive got a total mental block on how to get the most words per line thing working. All i can do so far is get it to be the same as the word count, and its starting to do my head inso any help will be appreciated. I get the feeling that its one of those things where ill kick myself once i know the anwer. Thanks for your help, by the way i know its a bit messy but ill tidy it up when finished lolThanks for your help, by the way i know its a bit messy but ill tidy it up when finished lolCode:#include <iostream> #include <fstream> #include <sstream> #include <string> using namespace std; void main(int argc, char **argv) { // make sure that the user has specified a filename if(argc < 2) { cout << endl << "You must enter a filename" << endl << endl; return; } string filename = argv[1]; ifstream fin(filename.c_str()); // define our file input stream // make sure that the file exists if(!fin) { cout << endl << "Cannot find file" << endl << endl; return; } /******************************************************************** Process the text data file ********************************************************************/ cout << endl << "Reading input file: " << filename << endl << endl; int words = 0, max = 0; // to count words and longest line string temp; for (int line = 0; !fin.eof(); line ++) { // for each line in file ... getline(fin, temp); // get the line into temp string istringstream sstr(temp); // create string stream tokeniser while (sstr >> temp) { // for each word from line ... words++; // increment word count for line max++; // update total words so far } // update longest line if latest was longer } /******************************************************************** Output the stats ********************************************************************/ cout << endl << "Total lines:" << line ; cout << endl << "Total words:" << words ; cout << endl << "Max line: " << max << " words" ; cout << endl << "Average: " << (words/(double)line) << " words per line" ; cout << endl << endl ; }
http://cboard.cprogramming.com/cplusplus-programming/59132-max-word-count.html
CC-MAIN-2014-35
refinedweb
322
73.85
Hey fellow programmers. I am just starting to work on C++ and languages in computer programming. So far its not bad yet, but having an issue with this program I am trying to write. The program I am writing is to compute the sum of the minutes exercised per week, as well as the average. The user is asked to input the minutes of exercise per day, and from there am required to use a counter-controlled while loop to figure out the sum and average. I am having issues with my code. I have it so that it displays the sum and average minutes, but it also needs to kick out the number of days exercised and if a 0 is entered, it still gives me seven for days exercised. I am looking for help and ideas how to get this to work right. Thanks for help. My code is below. //Program to calculate the average number of minutes //excersized per week by an individual. #include <iostream> using namespace std; int main() { int counter; int number; int sum; int limit; limit = 7; sum = 0; counter = 0; while (counter < limit) { cout << "Enter number of minutes excercised per day. Press enter after each entry." << endl; cout << "The first day of the week is Monday." << endl; cin >> number; sum = sum + number; counter = counter + 1; } cout << "The total minutes excersized is " << sum << endl; if (counter != 0) cout << "The average minutes excersized per day during this week is " << sum / counter << endl; else cout << "Zero minutes entered for the week." << endl; if (counter = limit) cout << "The number of days excercised is " << counter << endl; return 0; }
https://www.daniweb.com/programming/software-development/threads/92914/help-with-counter-controlled-loop-to-find-average
CC-MAIN-2018-43
refinedweb
270
72.36
DesktopX version 2.2 What's new from version 2.1: ------- Major new features: + Overlays - use F9/F10 to activate or show/hide widgets and objects that are normal Z-order. + Overlay hot keys can be defined by users + Widgets will automatically install themselves to your widget folder no matter where they are run from. + Widgets can be set to be run on start up from their right-click menu. + Important to remember: Widgets DO NOT require DesktopX to be running to be used. + DirectGUI V2 now the base graphics engine. Means much faster graphics drawing, animation, shadows, real time dragging, etc. Just plain faster. + Rotation and sizing now integrated into scripts and very fast. + ActiveX controls have lower memory overhead. Minor new features or fixes: - New Documentation - Widgets can be imported into your DesktopX environment as objects (import menu) - Widgets will automatically install themselves into the DesktopX Widgets folder for future use. - Widgets will remember their last position - Widgets and objects can install fonts that are included as part of them (see summary page on object to attach files). - Load widget menu item from DesktopX system tray item. - ActiveX controls behave better. - Tons of new abilities to the DesktopX class (right click properties, object type) such as create a new object. - New tab for configuring overlays - IconX graduates to its own stand-alone program but IconX support still integrated into DesktopX (if you have IconX installed you can configure it from DesktopX still). - Lots of "Crash bugs" found/fixed - Multi-monitor support improved - Shadows set to be controlled by offsets - Multi-line DX labels - Better edge alignment support - Multi-line tooltips - Bitmap resizing much faster. - Most of the object model is now accessible from scripting. - DX auto-reinitializes VBScript.dll if it gets messed for some reasons. - Added Object.Contrast [-100,100] - Added States("name") namespace. It supports: .Hue [1,255] 0=disabled .Opacity [0,100] .Brightness [-255,255] .Contrast [-100,100] .Rotation .TextColor .Text .TextBorder .TextBorderColor - Added Widget.Restore Widget.Minimize Widget.About Widget.Close Widget.Caption - sets the widget systray tooltip or taskbar item text. - Added States and Comment fields to the Navigator. - Object browser can directly modify the object position, width and comments. - ObjNav row selections are synced with actual DX objects selections. - Improved and fixed widget systray and taskbar access. - Fixed/improved ActiveX dragging over layered windows. - Objects stick on screen border. - To reference ALL states, use empty string (i.e. .State("").) - Fixed 1000 max objects limit. - Systray Widgets icon click toggles it visible/invisible. - Exposed the Widget namespace in the GUI. - Added System_OnScreenChange. It can be used to manually reposition/resize objects and contained objects. In this case it is suggested to disable automatic reposition (just leave Left/Top screen adjustment settings). - Changed the way workarea is implemented. It should fix positioning issues and other problems. - Added By Name and By Date sorting methods in Object and Theme navigator. - Fixed export preview to take invisible objects in consideration. - DesktopX builds now bitmaps and effects on the fly only when they are needed and trashes them when they are not used anymore. This greatly reduces loading time and average memory usage. - Fixed bug when unloading non-Pro widgets. - Fixed all Browse dialogs on Win9x. - Implemented Object.Parent to set parent objects at runtime. - Fixed crash in .ini parser for corrupted objects. - DXScripts should be Norton friendly. - Improved automatic installation/uninstallation of sdctrls.dll for DX Pro objects. - Fixed bad crash with multiple object properties panels opened. - Added Object.Resize(w, h) method. It's the dual of .Move. It sets width+height in one shoot for better performance. - Fixed Hue changing resetting the animation. - Added System.IsKeyDown(vk). - Added Object_OnKeyUp(vk, flags). - Added Cursor templates to DX objects (Relation panel). - Removed Persistent objects. You can more effectly use widgets for that purpose. - Fixed Object dragging continuing after losing focus. - Tons of core optimizations and tweaks. - AX ctrls properties can be correctly set at design time. - Fixed AX ctrls misalign after parent dragging. - Added Object_OnStateChanged(state). This is different from _OnStateChange in that it notifies when the status change has completed (i.e. when the animation has finished). This can be useful for synchronization of objects and effects. - Added script methods: System.FolderDialog(title, rootdir, flags) for flags, see System.FileOpenDialog and FileSaveDialog(title, defaultFile, initialDir, extensions, flags) extensions must be a serie of | separated description-extension pairs like: "Text files|*.txt|All files|*.*" for flags, see ex. x = System.FileSaveDialog("My title", "new.txt", "c:\temp", "Text files|*.txt|All files|*.*", 0) Object_OnDropFiles(files) files is a string with dropped file names separated by "|" ex. Function Object_OnDropFiles(files) x = Split(files, "|") For i=0 To UBound(x) msgbox x(i) Object_OnDropFiles = True End Function - Fixed global admin password not setting (not 9x browse buttons though) - Fixed System.SetWallpaper - Fixed AX misalignment on setting appbars. - Fixed desktop zorder in standalone widgets. - Correct workarea calculation and appbar sizing in standalone widgets. - Fixed Remove widget option leaving undeleted objects.
http://www.stardock.com/products/desktopx/history.html
crawl-002
refinedweb
831
53.17
Possible Issue. Hi guys, I'm writing here just because I want to point out a small typo in the code of the current backtrader version on github (backtrader==1.9.59.122). Unfortunately the repo has not the Issue section available and I'm sorry if I'm posting it in the wrong place. The typo is at line 58 of datacache.py I believe that: impor osshould be import os Also, at line 80 of datacache.py I believe that: path os.path.join(path, self.p.appname)should be path = os.path.join(path, self.p.appname) Thanks again to Daniel for his amazing backtesting tool. - Paska Houso last edited by I can see what you see, but what's the actual issue? Oh, nothing in particular - I retrieved backtrader via git and I got errors about the aforementioned lines during the conversion to .pyc files during the installation process. I supposed that maybe someone else encountering the same problem might benefit from the corrections.
https://community.backtrader.com/topic/826/possible-issue
CC-MAIN-2021-21
refinedweb
168
66.33
Introducing In my previous blog i´ve shown you how easily we can build up an simple Workflow with new SAP Cloud Platform Workflow service. In this blog i will start this WF periodically to get every day an overview of my current alerts. The setup is also aquite simple process how described also in this blog. Let´s start…. Enter your SAP CP Integration Web UI and switch to “Monitor” view: In this view we must define/deploy our “User Credential” for the user which is allowed to start the WF: Now enter the “Security Material” tile and add the credential: Define the following Information: - Name - Description - User An click Deploy Yo should now see the new credential on top of the of your security materials: No we can switch to the “Design” view of SAP CP Integration to define our new artifact (Integration Flow). Design the Integration Flow Select an existing package or create an new one: Create a new Integration Flow by providing a name, for me i call the Flow “timer_based_wf_instance_start“: If we click Ok we switch over to the desing perspective, were we can see an empty iflow: My First task is now to delete the “Start” event and the “Sender”. The final Integration flow should look like this: Integration Flow objects in detail The following objects are added/changed: - Timer: The Start Event is now a “Time based Event”, because of the fact that i want to shedule my Integration Flow once a day at 9:00, from Monday to Friday. - Content Modifier #1: This “Message Header” is requierd to fetch the XSRF token from SAP Cloud Platform Workflow API. The HTTP(S) connection between our Request-Reply connection and the Receiver, contains the following details: Address: The Endpoint form the API documentation “https://<WFRUNTIME_HOST>hana.ondemand.com/workflow-service/rest/v1/xsrf-token” Method: GET Authetication: Basic Credential Name: Our credential Name which we created earlier “WFAAS_USER“ - Content Modifier #2: This contains in the “Message Body” section our “definitionid” for the SAP CP WF, this is required for the API call to start our WF instance. - Groovy Script: This script is used to store the cookie in our message header. You can find the script also in this blog, but there are two little errors, the script which work’s for me is this one: import com.sap.gateway.ip.core.customdev.util.Message; import java.util.HashMap import java.util.ArrayList import java.util.Map import org.slf4j.Logger import org.slf4j.LoggerFactory import groovy.xml.* import java.io.*; def Message processData(Message message){ def headers = message.getHeaders(); def cookie = headers.get("set-cookie"); StringBuffer bufferedCookie = new StringBuffer(); for(Object item : cookie){ bufferedCookie.append(item + ";"); } message.setHeader("cookie", bufferedCookie.toString()); Logger log = LoggerFactory.getLogger(this.getClass()); log.error("cookie"+ bufferedCookie); return message; } - Finally we need the Connection between the Message End and the Receiver, which contains the API call to start the WF: The HTTP(S) connection has the following Address: The Endpoint form the API documentaion “https://<WFRUNTIME_HOST>hana.ondemand.com/workflow-service/rest/v1/workflow-instances” Method: POST Authetication: Basic Credential Name: Our credential Name which we created earlier “WFAAS_USER“ Test the Integartion Flow To test our newly created Integration Flow we just change the “Timer Start Event” to the option “Run Once“. Finally click on deploy an check the “Monitor” view of SAP CP Integration An yes no error, also we should now have a new SAP CP WF Instance running?…… Enter the FLP and open the “Workflow Instances” tile: …..and whoot, there it is… ;o) Conclusion I hope you can see how easily you can start an SAP Cloud Platform Workflow by SAP Cloud Platform Integration. For me, this is a (the) perfect combination. And shows once more (hopefully) how simple you can combine different SAP Cloud Platform services together. Finally check my next blog how we go ahead with the combination. cheers, fabian That’s one more great post Fabian!!!
https://blogs.sap.com/2017/05/05/using-sap-cloud-platform-integration-to-start-a-sap-cloud-platform-workflow/
CC-MAIN-2017-30
refinedweb
663
51.28
I want to add only vertical scrollbar for my panel. I can do it succesfully but in horizontal view there is no dots appearing for long texts. I want to see both vertical scrollbar and three dot for long texts that doesn't fit the screen. How can I do it? By the way If I add my panel directly to the frame dots appearing. with scrollpane when adding panel directly to the frame public class ScrollPaneDemo { public static void main(String[] args) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); for (int i = 0; i < 25; i++) { panel.add(createLabel()); } JScrollPane scrollPane = new JScrollPane(panel); scrollPane .setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); JFrame frame = new JFrame(); frame.getContentPane().add(scrollPane); frame.setSize(300, 300); frame.setVisible(true); } public static JLabel createLabel() { return new JLabel( "Long Text, Long Text, Long Text, Long Text, Long Text, Long Text, Long Text, Long Text, Long Text"); } } This is surely a bad idea, but if that's what you want then here it is. Modify your panel to override its getPreferredSize to be its default height, but its parent's width: JPanel panel = new JPanel() { @Override public Dimension getPreferredSize() { int h = super.getPreferredSize().height; int w = getParent().getSize().width; return new Dimension(w, h); } }; The parent class is the JViewport which is the "window through which you look" at the component in the scroll pane. Now the line scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); does nothing because it is guaranteed that the width of the panel is the width of the viewport, which means you have nowhere to scroll to and by default the scrollbar won't appear. The only way to see the remaining text is to resize the scroll pane through resizing of the frame. I won't be surprised if anything breaks with this.
https://codedump.io/share/5uKKRPGjaUDT/1/jscrollpane-show-only-vertical-bar-and-three-dot-for-horizontal
CC-MAIN-2017-30
refinedweb
301
56.96
By now you should be able to: If you have not done all of these things go back to lab 1, complete it and restart this lab when you have finished lab 1. In future weeks you will be expected to have completed and written up the previous lab before starting on the next one. To make best use of the tutorial time it is your responsibility to stay up to date and to catch up with previous week's labs if you are unable to attend a tutorial. At the end of this lab you should be able to write simple Python programs which: open your circle.py program, modify it, paying particular attention to the second line, so that it reads: import math radius=int(raw_input("Please enter a radius")) area=math.pi*radius**2 print "For a circle of radius %s the area is %s" % (radius,area) and save it as circle2.py . Run this program, and when prompted for a radius input: 2 If your program runs correctly you should see the output: >>> For a circle of radius 2 the area is 12.5663706144 (Assuming it is run using import circle or in an environment such as pywin that outputs to the python command line system. If it is run by other means you won't get the >>> prompt, but the rest of the output should be visible.) Run your program again for radiuses of 1 and 1.5 . Write down the results which you get in your logbook for a radius of 1 and write down the error message which you get for a radius of 1.5 . Change line 2 of your program so that it reads: radius=float(raw_input("Please enter a radius")) Test your program again for input values of 1, 1.5 and 2. Write down the results in your logbook and answer the following questions in your own words in your logbook: Does the int() built in function accept floating point (fractional) values ? Does the float() built in function accept integer (whole number) values ? Which built in function seems more useful for this application and why ? Test your program again for an input value of: Fred . Write down the error message you get in your logbook exactly as it appears. Examine this message carefully and explain in your logbook how Python tells you about the location in your program where the error occurred and the kind of error which occurred. Save your program as circle3.py and insert 2 additional lines (starting with try and except ) to help catch the ValueError without allowing it to crash your program. You will need to indent some existing lines by 2 or 4 spaces (you must do this consistently) so that your program looks like this: import math try: radius=float(raw_input("Please enter a radius")) area=math.pi*radius**2 print "For a circle of radius %s the area is %s" % (radius,area) except(ValueError): print "you entered invalid input" Test your program again providing inputs: 1, 1.5 and Fred, and write the results into your logbook. Open a new program file and (using copy and paste from circle2.py if you wish) input the following code and save it as if1.py mark=float(raw_input("Please enter a mark")) if mark >= 40: print "You passed" else: print "You failed" Test this program using inputs of 39, 40 and 99 and write the results in your logbook. Adapt this program as show below and save it as if2.py . mark=float(raw_input("Please enter a mark")) if mark < 40: print "fail" elif mark < 50: print "pass" elif mark < 70: print "credit" else: print "distinction" Run the program 4 times with input values chosen to get the following output: fail pass credit distinction Given that credits are awarded for marks greater than or equal to 50 and less than 70, why doesn't the test for a credit: elif mark < 70: print "credit" need to check for marks greater than or equal to 50 in addition to marks less than 70 in order to avoid awarding credits for marks not deserving credits ? Look at the whole program and write your understanding of this question and your answer in your logbook. In your logbook write down your understanding of if [test]: elif [test]: and else: if you have not yet completely done so. Save the following program as string1.py : name=raw_input("Please enter your name") print "you entered: %s" % name Test it using input values: Fred , 1 and 1.5 . You didn't have to say something like: string(raw_input("Please enter your name")) in the manner you did with circle2.py when obtaining int and float data from the keyboard, because raw_input() returns a string anyway. You had to convert a string to a float or an int when you wanted numbers, but if you both want a string and get a string no conversion is needed. Note that the strings "1" and "1.5" which worked with the above program may have looked to you just like numbers, but if you are in any doubt about whether these are numbers or strings then try modifying circle2.py as follows: import math radius=raw_input("Please enter a radius") area=math.pi*radius**2 print "For a circle of radius %s the area is %s" % (radius,area) and running this modified version with inputs of 1.5 and 1. Excercise: carry out the above modification to circle2.py and write down in your logbook the kind of error you get and the program line in which this error is detected. Write down the line number where this design error actually occurs. (Hint: errors are very often detected in programs somewhere below the line where they really occur.) Save the following program as string2.py and run it: fname=raw_input("Please enter your first name") lname=raw_input("Please enter your last name") print "Hello %s %s" % (fname,lname) How would you store the combination which appears on the output for later ? Modify and save it as follows: fname=raw_input("Please enter your first name") lname=raw_input("Please enter your last name") greeting= "Hello %s %s" % (fname,lname) print greeting Write the results of your test of the above programs in your logbook. Here is another approach to joining strings. Save the following program as string3.py fname=raw_input("Please enter your first name") lname=raw_input("Please enter your last name") name=fname+lname print name What did the + operator do to the 2 strings ? How would you join the 2 names together with a space between them ? (Hint: you could also add the string: " " which is a single space surrounded by quotes, and use 2 + operators to add your 3 strings) Test your solution, and write the answers in your logbook. Excercise: a. write a program called address.py which inputs your full name and address from the keyboard (the address might include 3 lines, line1, line2 and line3 and a postcode ) and which prints out the name and address on the output like this: Bilbo Baggins, 3 Bag End Lane, Hobbiton, The Shire, HB1 QW4 Hint: if you want to output more than 1 line using a single print statement, you can use the escape \n (backslash followed by n) either within a string or added to a string to achieve this. Print this program and stick it into your logbook when you have finished. Save the following program as cmpstring.py and test it : name=raw_input("Enter your name") if name == "Aladdin": print "your wish is my command!" else: print "go away" Then by rearranging the above program (always use edit/cut and paste for this kind of job, don't rewrite unless you can type quicker than use the mouse) get it to give exactly the same test results, but this time around using the != comparison operator (not equal to) intead of the == (equal to) comparison operator. Develop a program testand.py which asks for a name and a password, and prints an acceptance message if the name is "Aladdin" and the password is "sesame" . This program should print a rejection message in all other cases. This should be achieved by combining the 2 tests into 1 using the and keyword. Stick a printed copy of your program source code into your logbook. Develop a program (testor.py) that asks the user if he/she is happy. If the user enters either "y" or "Y" print a suitable greeting (e.g. "great") , otherwise a suitably compassionate reply (e.g. "sorry to hear that") . You should combine the tests for "y" and "Y" using the or keyword. Stick a printed copy of your program source code into your logbook. Save the following program into a file called not.py . The while 1: statement is an infinite loop which would go on forever if there were no break statement to end the loop. Run this program, providing input values of 0,11 and 1. while 1: number=int(raw_input("enter a number between 1 and 10: ")) if not 1 <= number <= 10: print "out of range, try again" else: break print "you entered %d" % number Write down in your logbook the effect of the keyword: not on the way the if statement handles the test: 1 <= number <= 10 . Write and save a Python program which opens a file called: fileworld in the current working directory, and writes the text: 'Hello File World !' to this file. Open this file in notepad or vi or display it by some other means, so you know the file was created successfully. Write the source code for your program into your logbook. Create a new version of the program you wrote which prompted for your name and address, so that instead of displaying user inputs for name and the various address parts on the console it writes this address label to a file called: address.txt . Make sure you test the program by checking output using Notepad etc. Create a text file containing 3 numbers, one on each line, e.g: 3 5 6 Write and save a program which reads each line and converts it into a floating point object (you can use references a, b and c for to refer to these numbers). Hint: you converted keyboard input which raw_input() gave you as strings into floats by using the float() builtin function. You can do something similar to the string output by the readline() method. Print out the sum (all 3 numbers added up) and the product (all 3 numbers multiplied together) and the average (your sum divided by 3.0). When you have got it working put the source code into your logbook. Write and save a copy of a program which reads a file address.txt containing an address label similar to the kind of address file you have used before, but not containing a phone number. Your program must store the address. Add a prompt which asks the user for a telephone number. Close address.txt and reopen it in write mode, writing the address back to the same file together with a phone number. Write a program which reads 4 numbers from a file called guess_file.txt . The first, N, is a number greater than 1, e.g. 5.0 . Your program is expected to find a closer approximation to the square root of this number than your guess. The second number, lower_limit, will start at 1.0 and is the lower limit of what the square root of N might be. The third, upper_limit, is the upper limit of what the square root might be and starts as the same number as N. The forth, guess, is the first guess as to the square root of N. The first guess should start at (N+1)/2.0 e.g: (5.0+1.0)/2.0 is 3.0 : Here is what your guess_file.txt should contain before the first program run: 5.0 1.0 5.0 3.0 An algorithm which improves upon a guess for the square root of a number N works as follows: open guess_file in read mode input N, upper_limit, lower_limit and guess from guess_file close guess file print these values to screen guess_squared = guess multiplied by itself. if guess_squared is greater than N : upper_limit = guess else if guess_squared is less than N : lower_limit = guess else : # guess is equal to the square root of N print the square root of N is guess next_guess = (upper + lower)/2.0 open guess_file in write mode output N, upper_limit, lower_limit and next_guess to guess_file close guess file print these values to screen Convert the above pseudo-code algorithm into a Python program which is saved in a file called guessqrt.py . Debug it. Run it so that the upper and lower limit values stored in the guess file get closer to each other and the guess improves each time you run this program. When you have got your program working print the source code and paste this into your logbook. Run this program a few times, each time noting down in your logbook the upper, lower and guess values. How many times do you need to run this program before the guess doesn't change by more than 0.001 (1 thousandth) ? Check your calculated square root using a calculator. Adjust the if and else if (elif) tests in your source code so that when the difference between guess_squared and the number N is less than 0.001 the else: block is used and the guess is printed. Print the adjusted source code and paste this into your logbook, or record the adjustments made to these tests into your logbook.
http://bcu.copsewood.net/python/ex2.html
CC-MAIN-2017-22
refinedweb
2,291
69.41
view raw I have a python script (which must be called as root), which calls a bash script (which must be called as non-root), which sometimes needs to call sudo. This does not work - the "leaf" sudo calls give the message "$user is not in the sudoers file. This incident will be reported." How can I make this work? The code (insert your non-root username in place of "your_username_here"): tezt.py: #!/usr/bin/python3 import os import pwd import subprocess def run_subshell_as_user(cmd_args, user_name=None, **kwargs): cwd = os.getcwd() user_obj = pwd.getpwnam(user_name) # Set up the child process environment new_env = os.environ.copy() new_env["PWD"] = cwd if user_name is not None: new_env["HOME"] = user_obj.pw_dir new_env["LOGNAME"] = user_name new_env["USER"] = user_name # This function is run after the fork and before the exec in the child def suid_func(): os.setgid(user_obj.pw_gid) os.setuid(user_obj.pw_uid) return subprocess.Popen( cmd_args, preexec_fn=suid_func, cwd=cwd, env=new_env, **kwargs).wait() == 0 run_subshell_as_user(["./tezt"], "your_username_here") # <-- HERE #!/bin/bash sudo ls -la /root sudo ./tezt.py I'd suggest using sudo to drop privileges rather than doing so yourself -- that's a bit more thorough where possible, modifying effective as opposed to only real uid and gid. (To modify the full set yourself, you might try changing setuid() to setreuid(), and likewise setgid() to setregid()). ...this would mean passing something to Popen akin to the following: ["sudo", "-u", "your_username_here", "--"] + cmd_args
https://codedump.io/share/jU029Z1lJ4Mn/1/sudosuid-non-root-nesting-fails
CC-MAIN-2017-22
refinedweb
237
60.01
This appendix contains the following sections: Oracle Reserved Namespaces This appendix lists words that have a special meaning to Oracle. Each word plays a specific role in the context in which it appears. For example, in an INSERT statement, the reserved word INTO introduces the tables to which rows will be added. But, in a FETCH or SELECT statement, the reserved word INTO introduces the output host variables to which column values will be assigned. The following words. The following PL/SQL keywords may require special treatment when used in embedded SQL statements. Table B-1 contains a list of namespaces that are reserved by Oracle. The initial characters of function names in Oracle libraries are restricted to the character strings in this list. Because of potential name conflicts, use function names that do not begin with these characters. For example, the SQL*Net Transparent Network Service functions all begin with the characters "NS," so you need to avoid naming functions that begin with "NS."
http://docs.oracle.com/cd/E18283_01/appdev.112/e10830/appb.htm
CC-MAIN-2014-35
refinedweb
165
55.03
Add "canary-in-the-mine" instrumentation to detect when the browser process spends too long outside its main-thread event loop(s) RESOLVED FIXED Status () ▸ General People (Reporter: cjones, Assigned: blassey) Tracking Firefox Tracking Flags (Not tracked) Details Attachments (1 attachment, 2 obsolete attachments) For fennec, we want animated zoom to run at 60fps. Bug 598873 would make things easier, but even that isn't a complete solution on fennec. To achieve that framerate, we can't spend more than 10-15ms per event-loop task. We can't reliably achieve this with SW compositing on the main thread, but when we have GL acceleration, we need to focus on that target. Easy instrumentation is to create an RAII class that sets up a SIGALRM handler for 10ms in the future when starting to process a task, and clears the handler when the task finishes. If the alarm expires while the task is running, we can NS_RUNTIMEABORT() to get backtraces, or do other fancy things. This simple plan is confounded by us having three different event loops running on the main thread, with multiple implementations, and by nested loops. But it should be easy to get something simple working. This is related to but complementary to function timer instrumentation, which doesn't give us backtraces. This is a great idea.. So this is for the chrome process only, not content processes, right? (In reply to comment #3) >. Yes; I've heard something about shaver having written a Tbeachball test that's supposed to measure this. I had in mind running builds instrumented with something like this as we would run them under valgrind (although, yes, that should be automated too ;)). (In reply to comment #4) > So this is for the chrome process only, not content processes, right? Right, I use "browser process" and "chrome process" interchangeably. Assignee: nobody → blassey.bugs Created attachment 484083 [details] [diff] [review] patch Attachment #484083 - Flags: review?(jones.chris.g) Comment on attachment 484083 [details] [diff] [review] patch Big problems with this patch - always enabled, opt and debug (!) - backtrace_symbols_fd is non-standard, need to feature test - ualarm is a newer standard, also needs a feature test >diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp >--- a/xpcom/threads/nsThread.cpp >+++ b/xpcom/threads/nsThread.cpp >@@ -500,9 +506,41 @@ nsThread::HasPendingEvents(PRBool *resul > return NS_OK; > } > >+#if defined(XP_UNIX) && !defined(ANDROID) >+ Using this on an android device was the first thing I had in mind. We can define a canary for android, but not use backtrace_symbols_fd (bionic has ualarm(), right?). Just being able to break on offenders in gdb is enough for shotgun-profiling-type use. Also, please use #if defined(BLAH) && ... # define MOZ_CANARY so this condition can live in one place. >+static void canary_alarm_handler (int signum) >+{ >+ void *array[30]; >+ >+ const char msg[29] = "event took too long to run:\n"; >+ write(2, msg, sizeof(msg)); Please add a comment here about using write() for async-signal safety, I did a double-take on first glance ;). s/2/STDERR_FILENO/. >+ backtrace_symbols_fd(array, backtrace(array, 30), 2); This is really cool, good idea :). We could use this info in a postprocessing phase. >+ raise(SIGCONT); Why is this here? Just returning from the signal handler should continue execution. >+} >+ >+class canary { Style is "class Canary". >+public: >+ canary() { >+ if (NS_IsMainThread() && XRE_GetProcessType() == GeckoProcessType_Default) { Hmmmm ... when should we allow this. We definitely only want this |if (PR_GetEnv("MOZ_KILL_CANARIES"))| or something. It's only really fair to use this instrumentation in opt builds, too, since debug ones can do all sorts of random stuff. It's not-so-great to add an env var check to ProcessNextEvent(), but I would hope it's not going to add noticeable overhead. We can try just the |if (getenv())| guard, for opt and debug, and restrict to a build flag if talos notices. >+ ~canary() { >+ if (NS_IsMainThread() && XRE_GetProcessType() == GeckoProcessType_Default) { >+ ualarm(0, 0); >+ } XXX or FIXME here plz about this not working for nested loops (OK by me, for v0). >+ } >+}; >+#endif >+ > NS_IMETHODIMP > nsThread::ProcessNextEvent(PRBool mayWait, PRBool *result) > { >+#if defined(XP_UNIX) && !defined(ANDROID) #ifdef MOZ_CANARY per above. We'll want to move this code somewhere else if/when we want to instrument the other event loops, but I agree with deferring until that time. r- for the big problems above. Attachment #484083 - Flags: review?(jones.chris.g) → review- I played around with this patch a bit on desktop-gtk. Cool stuff! Three big offenders that popped up consistently are loading XUL-y/XBL-y/CSS-y stuff, initializing NSS, and XSync()ing after ShmPutImage. But, in the steady state we spend our time in the glib event loop, which triggers a false positive every time it sits in poll() for more than 15ms. We're going to need to instrument the glib loop, at least, to get useful results. And that itself requires handling nested canaries (hah) because of the atrocious design of our event loops. Created attachment 485654 [details] [diff] [review] patch Attachment #484083 - Attachment is obsolete: true Comment on attachment 485654 [details] [diff] [review] patch We don't want this instrumentation to run by default. Per comment 7, let's only enable it if the env var is set. Other nitty stuff looks OK. Attachment #485654 - Flags: review?(jones.chris.g) → review- Comment on attachment 485654 [details] [diff] [review] patch (In reply to comment #10) > Comment on attachment 485654 [details] [diff] [review] > patch > > We don't want this instrumentation to run by default. Per comment 7, let's > only enable it if the env var is set. > > Other nitty stuff looks OK. unless there's an error in the logic I'm not seeing, sOutputFD will be set to 0 if the env var is not set, and this code will not be run. Or are you saying we should only build this code if a macro is set at build time? Attachment #485654 - Flags: review- → review?(jones.chris.g) Comment on attachment 485654 [details] [diff] [review] patch ahh, there is an error in the logic in that the alarm will be set once Created attachment 485962 [details] [diff] [review] patch Attachment #485654 - Attachment is obsolete: true Attachment #485962 - Flags: review?(jones.chris.g) Comment on attachment 485962 [details] [diff] [review] patch >+ Canary() { >+ if (sOutputFD != 0 && NS_IsMainThread() && >+ XRE_GetProcessType() == GeckoProcessType_Default) { >+ if (sOutputFD == -1) { >+ const int flags = O_WRONLY | O_APPEND | O_CREAT | O_NONBLOCK; >+ const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; >+ char* env_var_flag = getenv("MOZ_KILL_CANARIES"); >+ sOutputFD = env_var_flag ? (env_var_flag[0] ? >+ open(env_var_flag, flags, mode) : >+ STDERR_FILENO) : 0; >+ if (sOutputFD == 0) >+ return; >+ } >+ signal(SIGALRM, canary_alarm_handler); >+ ualarm(15000, 0); >+ >+ } Extra newline here. Attachment #485962 - Flags: review?(jones.chris.g) → review+ Comment on attachment 485962 [details] [diff] [review] patch a=beltzner, can land during the b7 freeze due to value of getting this information. A blog post should accompany this, so that we can get people using it! Attachment #485962 - Flags: approval2.0? → approval2.0+ Can we maybe dump the js stack too? (In reply to comment #16) > Can we maybe dump the js stack too? please file a follow up I'll wait until we need it then. Brad, if we're going to point people at this v0 implementation, can we please move +#ifdef MOZ_CANARY + Canary canary; +#endif to just after ++mRunningEvent; in nsThread::ProcessNextEvent? That still ignores the native event loop, but prevents it from contributing false positives (except with nesting). (In reply to comment #16) > Can we maybe dump the js stack too? Technically we shouldn't do that, because DumpJSStack() isn't async-signal safe. But we're already using backtrace_symbols_fd() which isn't safe either, and this isn't mission-critical code, so we could probably add that. It'll occasionally lead to deadlocks and so forth though. pushed Status: NEW → RESOLVED Last Resolved: 8 years ago Resolution: --- → FIXED
https://bugzilla.mozilla.org/show_bug.cgi?id=601268
CC-MAIN-2018-17
refinedweb
1,290
64.51
GlassFish 4.0 specific deployment descriptors (such as glassfish-resources.xml) I'm updating my deployment descriptors for Java EE 7 and GlassFish 4.0. I managed to find the Java EE 7 namespaces here: When I got to my glassfish-resources.xml, I couldn't find an updated version. I looked in the GlassFish 4 documentation and noticed that it gives samples of all the GlassFish specific deployment descriptors EXCEPT for glassfish-resources.xml, and all of the examples have 3.1 in their DTD. Did they not change, or was this not updated in the documentation? page B-15 Thanks, Ryan
https://www.java.net/forum/topic/glassfish/glassfish/glassfish-40-specific-deployment-descriptors-such-glassfish-resourcesxml
CC-MAIN-2014-10
refinedweb
103
61.22
kricker Wrote:I am trying to get my Xbox to send a WOL to my server when XBMC starts. I understand how to use autoexec.py. The problem lies in trying to find the correct WOL script. I have the tweaked WOL, but it opens a GUI to select the PC to wake. This is great if I have other computers to wake, but I want it to always wake the server and not show a GUI when running at startup. All my searches for the older WOL showed either dead links or the code I lifted from the posts did nothing. Can anyone please help me out? # Wake-On-LAN # # Written by Marc Balmer, marc@msys.ch, # This code is free software under the GPL import struct, socket def WakeOnLan(ethernet_address): # Construct a six-byte hardware address addr_byte = ethernet_address.split(':') hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16), int(addr_byte[1], 16), int(addr_byte[2], 16), int(addr_byte[3], 16), int(addr_byte[4], 16), int(addr_byte[5], 16)) # Build the Wake-On-LAN "Magic Packet"... msg = '\xff' * 6 + hw_addr * 16 # ...and send it to the broadcast address using UDP s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto(msg, ('<broadcast>', 9)) s.close() # Example use WakeOnLan('aa:bb:cc:dd:ee:ff') # My PC kricker Wrote:That is the exact code I tried to lift and use. When I run it nothing happens. If I run the tweaked WOL script it works properly. kricker Wrote:I looked for Nuka's Plug-in maker and could not find it. Is it only in the SVN? So I need to find it there? I'd love for it to only send the WOL when the share is requested. That is even better than always waking the server at boot up. <onclick>XBMC.RunScript(Q:\scripts\Wake\wakePVR.py)</onclick>
http://forum.kodi.tv/showthread.php?tid=24843&pid=125892
CC-MAIN-2015-11
refinedweb
315
68.47
snd_ctl_mixer_switch_list() Get the number and names of control switches for the mixer Synopsis: #include <sys/asoundlib.h > int snd_ctl_mixer_switch_list( snd_ctl_t *handle, int dev, snd_switch_list_t *list ); Arguments: - handle - The handle for the control device. This must have been created by snd_ctl_open() . - dev - The mixer device the switches apply to. - list - A pointer to a snd_switch_list_t structure that snd_ctl_mixer_switch_list() fills with information about the switch. Library: libasound.so Use the -l asound option to qcc to link against this library. Description:: - pswitches - This pointer must be NULL or point to a valid storage location for the switches (i.e. an array of snd_switch_list_item_t structures). - switches_size - The size of the pswitches storage location in sizeof( snd_switch_list_item_t ) units (i.e. the number of entries in the array). On a successful return, the snd_ctl_mixer_switch_list() function will fill in these members: - switches - The total switches in this mixer device. - switches_over - The number of switches that couldn't be copied to the storage location. Returns: Zero on success, or a negative value if an error occurs. Errors: - -EINVAL - Invalid handle argument. Classification: QNX Neutrino Caveats: The switch struct must be initialized to a known state before making the call; use memset() to set the struct to zero, and then set the name member to specify which switch to read.
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.audio/topic/libs/snd_ctl_mixer_switch_list.html
CC-MAIN-2021-17
refinedweb
212
66.03
EDIT: Apparently misread your question, you are referring to the Blogs in Community, not in CMS. Different beast - disregard my answer below. This is a bit of a non-answer, but TL;DR: Don't use Blogs - roll your own. There's no documentation because the Blogs templates were only included as a demo/example. They were never meant for production usage, just inspiration. You really shouldn't base any of your code on the EPiServer.Blog namespace, because in EPiServer 7.5 onwards, the namespace (along with EPiServer.Blog.dll and the Blog demo templates) are no longer included in the demos for CMS. Which means upgrading will cause you pain. Jacob Khan at EPiServer is apparently working on some new Blog templates (although for 7.5+) which may be useful. Video notes while waiting for the official blog post: Thanks for your response. This has been a little helpful. I apologize, I couldn't figure out how to edit my post after I had sent it; I have EPiServer 7.5 installed. For Blogs in Community, I am trying to access them and display them in the CMS, similar to that video you posted. Were you saying that video is using EPiServer 7.5? He doesn't seem to be using Community though (at least mine has a Community link in the UI). Hi Brandon. The blog I have posted on youtube is like you said for CMS only and a very simple blog module where editors can create blogs. Not external people. If you are looking to create a lot of blogs and in the future allow external people to create them then I recommend Relate and the community piece. The best way is to install the relate package which you can download here on world and move over the blog code that you need. EPiServer CMS comes with a sample template called Alloy while EPiServer Community comes with its own sample project. In the Community sample project you have various different features like blogs. Relate is the combination of Community, CMS and Mail. The Blog piece can be built using CMS or Community. There are advantages to using either and depending on your needs I would suggest using the CMS as Blogs if you have a limited amount of bloggers and blogs. e.g. less than 100 per month. Community is really good for larger amounts of blogs and bloggers can be external and it also comes with commenting and ratings. How to access blogs in Community is through the Relate package. Install Relate and get the code and the functionality you need there. Community also has different installation instructions than CMS. I know this is under EPiServer 7 CMS forum, but this is the closest Blog implementation thread I could find in the forum. I am using EPiServer 9.5.1 MVC and would like to include common Blog functionality (blog channels, categories, tags, archive, subscribe via email, comments, search with most popular, tetc.) into one of my customer's solution to replace their current usage of WordPress. The idea is to have site admins post blogs, so there will be a limited amount of bloggers. Where can I find the templates from the video to help me start? Is there an Add-in or 3rd party we should look into rather than building from scratch? Hi Todd You can download the package, both mvc and webforms in the same package here However, the updated version is apart of our demo kit Hope this makes sense /J Thank you for the information. I created an Alloy EPiServer CMS project via Visual Studio 2015 using the Aloy (MVC), but that did not have the Blog example templates. Am I missing something? I will try the AlloyDemoKit link you supplied, I assume this has different than the Alloy (MVC) templates in Visual Studio? As Eric mentioned the github package is not identical to the one you create in VS. It uses the project from VS as a base but has a number of extra Add-ons, configs, extensions, and more. Here's a more thorough description:. You will also find a ReadMe in the github package with further details. I got the AlloyDemoKit running locally. Great to have examples. Thank you very much for helping me. Question: This is in regards to the ability to add script (.JS) and style (CSS) files to a page. In the SitePageData.cs model there are new properties for Scripts and CSS files. In the CMS editor you can create a new link (or drag content) into the Script Files area under the script tab of the page. I assume this was only intended for use with 'External link' files with the full path, e.g. '' If I try to utilize a file that I've uploaded as content (e.g. in the Media area with something called 'myscript.js', then the item.Href does not resolve properly in the HtmlHelpers class when it callign the function AppendFiles. This is due to the files being from the LinkItemCollection and then referenced in the foreach with: outputString.AppendLine(string.Format(formatString, item.Href)); When I step through the code in the ApendFiles, my item.Href is something like, "~/link/f94f6a16640d43d5ae917838967544b8.aspx". Which is not the .js file I uploaded for content. In a view I can use @Url.ContentUrl(item.Href) to get the URL, but I have not been able to figure out a way to get this url from within the AppendFiles. Does that make sense? I'm just trying to extend this area to be able to handle uploaded CMS content. Hi Experts, I need to create a Blog and it should contain the Comment,Share link for particular blogs only.If we have 2 blogs both the shared with social media will be different. Need to Add are as: 1) Category Filter. 2) Tag Filter. 3) Blog share with all Social Media. 4) Leave a comment section . I have implemented Jacab's Sample code on my Episerver CMS successfully. But it is not completed need to do more options as i mentioned to you in above. Hi, I'm a little bit at a loss for how to add Blogs to the CMS. My development box has EPiServer 7 Alloy MVC installed and I used the Deployment center to install Community on existing site. It seems I am capable of adding blog entries after logging into the CMS, however, how do I add these to a Page or Block Type? The goal is to have an admin user log in, add a blog entry and appear on a public page. In the future we plan to allow outside users to interact with the blog, but right now it's just limited to admins. Any idea of where to start? It's difficult to find any documentation on this.
https://world.episerver.com/forum/legacy-forums/Episerver-7-CMS/Thread-Container/2014/9/Adding-Blog-to-Episerver/
CC-MAIN-2020-45
refinedweb
1,150
75.1
Using the MCP23017 port expander with WiringPi2 to give you 16 new GPIO ports – part 3 In this article, I’ll show you how to hook up and control a port expander chip with wiringpi2 for python. It’s really easy, and once set up (with about 3 lines of code) you can control your new ports just the same way as if they were on the Pi itself. This is, so far, my favourite new feature of WiringPi2 for Python – although there are some I have yet to play with. This is part 3 of my wiringpi2 for python series. If you haven’t read parts 1 & 2 yet, I recommend you read those first. What is a port expander? You probably guessed from the name, but a port expander is a chip that gives you more GPIO ports. WiringPi2 has drivers for several port expander chips… - MCP23017 – 16 ports i2c based - MCP23S17 – 16 ports spi based - MCP23008 – 8 ports i2c based - MCP23S08 – 8 ports spi based - 74×595 – 8 bit shift register We’re going to focus on just one – MCP23017 They’re all similar in usage, so I’ll simplify things by only dealing with one. There’s not much price difference between the 8 port and 16 port expanders either, so unless you need a smaller chip, you might as well have 16 ports. Although spi (10 MHz) is faster than i2c (1.7MHz), at the kind of speeds we’re interested in for general GPIO work, it doesn’t make much difference. The advantage of i2c is that you only need to hook up 2 wires to communicate with the Pi, whereas SPI uses 4. Pinouts The expanded GPIO ports are Pins 21-28 GPA0-GPA7. Pins 1-8 GPB0-GPB7. Once you’ve set up the chip (I’ll show you how in a minute) you can use these 16 GPIO ports as either inputs or outputs. Chip – Pi connection VDD – 3V3 (P1 header pin 1 or 17) VSS – GND (P1 header pin 6) SCL – SCL on Pi (P1 header pin 5) SDA – SDA on Pi (P1 header pin 3) NC – Do Not Connect RESET – 3V3 (P1 header pin 1 or 17) INTA – Do Not Connect (I think these can be used in WP2, but haven’t played wth them) INTB – Do Not Connect (I think these can be used in WP2, but haven’t played wth them) Circuit diagram Adding an MCP23017 gives us 16 additional GPIO ports to play with. You could “go to town” with this. But since my purpose here is to show you how to use wiringpi2 with the MCP23017 chip, I’m sticking to our simple “One input, one output” circuit, suitably modified for this chip. We’re using the chip’s internal pull-up. It has no pull-downs. One input, one output code for MCP23017 Before you use this code, you’ll want to check that your Pi has i2c enabled, or it won’t work. You can find out how to do that here. Once you’ve done that, you can test which i2c port your chip is set up as… sudo i2cdetect -y 1 (if you have a rev 2 Pi) sudo i2cdetect -y 0 (if you have a rev 1 Pi) If you’ve done your wiring the same as in the diagram above (A0, A1, A2 all to GND) your result should be “20”. If it’s anything else, something is wrong. Here’s the code to drive the MCP23017 with WiringPi2 for python…) wiringpi.pinMode(80, 0) # sets GPB7 to input wiringpi.pullUpDnControl(80, 2) # set internal pull-up # Note: MCP23017 has no internal pull-down, so I used pull-up and inverted # the button reading logic with a "not" try: while True: if not wiringpi.digitalRead(80): # inverted the logic as using pull-up wiringpi.digitalWrite(65, 1) # sets port GPA1 to 1 (3V3, on) else: wiringpi.digitalWrite(65, 0) # sets port GPA1 to 0 (0V, off) sleep(0.05) finally: wiringpi.digitalWrite(65, 0) # sets port GPA1 to 0 (0V, off) wiringpi.pinMode(65, 0) # sets GPIO GPA1 back to input Mode # GPB7 is already an input, so no need to change anything Early on (lines 4-5) we define… pin_base = 65 i2c_addr = 0x20 After setting up wiringpi (line 7) in its native pin mode… wiringpi.wiringPiSetup() …we initialise the MCP23017 chip (line 8) using the two variables we set earlier… wiringpi.mcp23017Setup(pin_base,i2c_addr) …if you wire all three address pins to GND, the i2c address is 0x20. (I explain how you can change this and use multiple MCP23017 chips, a bit further down.) If we start with a pin_base of 65 (the lowest available number in wiringpi2) GPA0 is allocated to 65, GPA1 = 66…GPA7=72, GPB0=73, GPB1=74…GPB7=80 You can choose whatever pin_base number you like (above 64) After that, we’re just setting up GPA0 as an output (line 10)… wiringpi.pinMode(65, 1) # sets GPA0 to output wiringpi.digitalWrite(65, 0) # sets GPA0 to 0 (0V, off) …and GPB7 as an input (line 13) with pull-up enabled (line 14)… wiringpi.pinMode(80, 0) # sets GPB7 to input wiringpi.pullUpDnControl(80, 2) # set internal pull-up The rest of the program is as it was before, except the logic is inverted with a not (line 21), because the button is now “the other way round”. (Pressing the button connects it to GND, not 3V3, as we did before.) You can use up to 8 of these MCP23017 chips If 8 onboard GPIO ports + 16 extra ports is not enough, you can connect up to eight MCP23017 chips to your Pi using different i2c addresses. There are three address pins on the MCP23017: A0, A1 and A2. They are used to determine the chip’s ID (000 to 111). Each needs to be wired to either 3V3 (1) or 0V (0). To begin with, I suggest wiring all three pins to GND, for ID 000, which gives us 0x20 as i2c address. If you want to use more than one of these chips, you can easily do that. Just wire each one’s address pins with a different address, and give it a pin_base value that doesn’t overlap with numbers already in use. e.g. ID 000, i2c address 0x20, pin_base 65 WiringPi knows this chip has 16 ports, so will allocate WiringPi pins 65-80 to this chip when this command is issued. Our first MCP23017 chip was wired as 000 = 0x20 and we chose 65 as pin_base, so… wiringpi.mcp23017Setup(pin_base,i2c_addr) …gave the Pi… wiringpi.mcp23017Setup(65,0x20) To add another MCP23017, connect Pin A0 of the second chip to 3V3 instead of GND. Now, its ID is 001, i2c address is 0x21. pin_base 81 will allocate wiringpi pins 81-96 to the second chip. Now we issue another setup command with the second pin base and i2c address in. wiringpi.mcp23017Setup(81,0x21) Our second chip is now ready to use on wiringpi pins 81 (GPA0) – 96 (GPB7). Now you can control these pins just like any other WiringPi2 pin – exactly as if they were on the Pi itself. In this way you can add up to 8 of these chips to give you a potential extra 128 ports. That should be enough for most people. If it’s not, you can have 8 of the SPI variant (MCP23S17) on each of the two SPI lines (CE0 and CE1) for another 256 ports. If you can’t do what you need to do with 384 ports, you might need a different device. I haven’t gone quite that silly yet, but I have had 3 MCP23017s and an MCP23S17 running at the same time. Watch out for your 3V3 lines Expanders are fun, but one word of warning. The 3V3 lines on the Pi (including the GPIO ports) can only give out ~51mA safely. That’s the total maximum for all ports/pins. If you want to connect up lots of leds and lots of expanders, you’ll need to power them from another source (e.g. the 5V lines or a battery) and use transistors or Darlington arrays to do the switching for you. You can use 16 standard 5mm leds with 330R resistors as the resistors limit the current to about 3 mA. But you’d be well advised not to use lower value resistors if you want that many LEDs. That’s all for today. There’s a lot of fun to be had with port expanders. Enjoy :) What we’ve covered so far in the WiringPi-Python series… Part 1 Part 2 - Raspberry Pi board revision checking with WiringPi2 for Python - Using the Raspberry Pi’s internal pull-ups and pull-downs with WiringPi2 for Python - Using hardware PWM with WiringPi2 for Python Part 3 There’s some parts of WiringPi2 that I haven’t yet explored. When I have, I’ll write part 4. If you want to use the same MCP23017 port expander chip directly with i2c instead of WiringPi, Matt Hawkins has done a 3-part series on how to do that here. The Quick2Wire library also includes driver code for the MCP23017 chip But the API isn’t quite as seamless as the one offered by WiringPi and the documentation seems quite lacking. P.S. Have you switched back to using the old Fritzing models? P.P.S. I’d be tempted the replace ‘0x65’ in your code examples with ‘pin_base + 0’ and ‘0c80’ with ‘pin_base + 15’ (so that you could change the pin_base without having to update the rest of your code), but that’s just me ;-) And it looks like AdaFruit have their own MCP23017 driver too and I’m sure there’s probably many other examples of people re-inventing the wheel ;-) I wrote this blog a few days before the new Fritzing models were even published Andrew. :) And then, when I went to update the Fritzing picture, I realised that the port labels on the new models were much too small, so would need to be made much bigger in order to be useful. I’ve done that now, so will be using my new improved, further improved Fritzing models for future diagrams. I like the pin_base suggestion and will probably implement that in future stuff I do. :) Taking the pin_base suggestion one step further, you could do: led_output = pin_base + 0 button_input = pin_base + 15 IMHO if not wiringpi.digitalRead(button_input):is much easier to read ;-) (at the ‘expense’ of adding more layers of abstraction). wiringpi.digitalWrite(led_output, 1) Lol everyone’s mind works differently. On the subject of Fritzing diagrams, I wondered why some of your wires were angled, rather than perfectly horizontal or vertical… So I did some investigation, and discovered why, and also came up with a work-around :-) Isn’t it because the power rail holes are slightly offset from the rest of the breadboard holes? (just like on a real breadboard). Not in the latest version of Fritzing (and on my breadboard) they’re not ;-) But it still has the rotation-bug, meaning that post-rotation the Pi’s P1-header pins still end up out of alignment with the breadboard pins. Unless you jiggle them both back onto grid. :) I’ve got six breadboards from various sources and I think they’re all like that. The P1 Pi pins line up with the main board holes not the power rail holes. Fritzing has various breadboard models though. I’ve never given it a second thought. It takes long enough to do this stuff without worrying about that level of detail. ;) As long as it’s clear what wire goes where, I don’t really mind. You should see what my REAL wiring looks like. I don’t think you’d like it ;) (Well you have seen my Gertboard Wii controller wiring) Apologies if I’m being overly pedantic again… please don’t take it as personal criticism :) No worries. I’ll ‘get ya’ on 21st September. ;) There’s nothing wrong with having a good eye for detail – in fact I think it’s a pre-requisite for programming and debugging. Actually it’s nice to know that someone’s watching my back. I don’t always get things right. Although I can’t promise to watch your back all the time Alex ;-) Just wanted to say, this series of articles has been excellent, great work. WiringPi has been something I’ve intended to look at for a while now, but haven’t as other things keep coming. My preference for numbering GPIO has shifted to using Pin numbers, as when describing it to beginners it seems to be the most logical to them (they are not normally concerned about the SOC’s GPIO pin numbers (as they aren’t looking at the BCM datasheet) or having GPIO0-7 being scattered around the pins (as numbered by the foundation). It just takes a little to explain only some pins are available as I/O, but that has to be explained anyway. Keen to see what other things WiringPi2 has to offer over standard RPi.GPIO. Regarding the MCP23017 I’ve done some bit-banging tests using the i2cset and i2cget to get things working, nice to see there is some direct support too. I take it that the Hardware PWM is now built into the current distros, I had all sorts of problems when merging the Occidentalis kernel to try it out (rather than imaging a new card). Software PWM was mentioned, is it any good for servo control or just a little too slow? Anyway, keep it up, as usual quality stuff! Cheers. Thanks Tim. Hardware PWM has been working as part of WiringPi for a long time. I think I got the motor program for the Gertboard working back in December 2012. I don’t really know how that affects the kernel to be honest (there be dragons LOL). I haven’t tried it with a servo. It offers other expanders too, (I have tried the SPI versions), soft PWM (not tried yet), some sound tones (not tried yet) and some other bits like Gertboard, PiFace, PiGlow support etc. I know other people have used servoblaster (C library I believe) with some success for servos with soft pwm, but I’m sceptical if Python is really suitable for servo PWM as it needs to be very precisely timed. Hi Great tutorial! I’m trying to add a second MCP23017 to my setup. The first is fine at address 0x20, and when I give the command [sudo i2cdetect -y 0] I see address 0x20 show up. However, after connecting the second MCP23017, I do not see a second address with this command. Is this normal – do you get the same thing? Does this command only show the first address only? What have you done with the three address wires? If you’ve grounded all three of them, you’ve given it the same address as the first one. You need to connect one of them to 3V3 to give the chip a different address from the first one. It doesn’t really matter which one. In this way you have eight possible addresses, where GND = 0 and 3V3 = 1 A3A2A1 0 0 0 = 0x20 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 = 0x27 I think my problem is that i’m not using wiring Pi. I copied a bit of code from another webise before I saw your page, and it uses smbus to set things up – which I can’t fathom how to add a second MCP23017. Some snippets from the code: —————- bus = smbus.SMBus(0) address = 0x20 bus.write_byte_data(address,0x00,0x00) # Set all of bank A to outputs bus.write_byte_data(address,0x01,0x00) # Set all of bank B to outputs def set_led(data,bank): #means bank1 or bank0…simple #print “set_led bank=” + str(bank) + ” data=” + str(data) if bank == 1: bus.write_byte_data(address,0x12,data) else: bus.write_byte_data(address,0x13,data) return —————- Either way, the ‘sudo i2cdetect -y 0’ command still only shows the 0x20 address. Weird. That looks like Matt Hawkins’ work. We were both working on this at the same time. He went with straight i2c and I went with WiringPi. WiringPi makes it easier, (I think) but requires installing. This is going to sound like “nasty teach giving extra homework”, but I think you should try WiringPi once you’ve finished the first way. It’ll be a great learning experience. Have fun I fixed it…and you know what it was? My lack of breadboard knowledge. I had one of the half size ones where the power rail breaks in the middle…my chip was getting no power! Thanks anyway! We’ve all done it. By the way – you’ll almost certainly do it again at some point, but next time you’ll spot it much faster. :) Do you guys know if a) there is a smaller (shorter) alternative to the MCP23017 (I need it 1 pin shorter for my project!!) and b) if other chips will work with the SMBus/Wiring Pi code? Thanks again One pin shorter?! Huh? ;-) There’s the MCP23008 which is an 18-pin chip, as opposed to the 28-pin MCP23017… If you’re prepared to write the driver code yourself (by studying the relevant datasheet), there’s no reason why any I2C chip shouldn’t work with the SMBus library! :-) Yeah kinds trying to get 3 of these on a Humble Pi board to get the most out of it, I love tight circuits! Hmm I’m reasonably comfortable with the datasheets…how hard is it to write driver code? And what would I do with it? (the MCP23017 works without me touching code…so where would it go?) Thanks again If you love tight circuits and you’re handy with a soldering iron, you can solder up the chips in “mid air” as long as you have insulation meaning they can’t electrically contact other parts ;-) And check out ‘driver code’ is basically everything that WiringPi does for you. When you’re using ‘raw SMBus’ that’s what most people count as ‘driver code’. Obviously how easy/difficult it is depends on what level of programming experience you have, how much of the chip’s functionality you need to access, and how comfortable you are with low-level bit-twiddling code. I’ll probably have to give that a miss then! I’m relatively new to all of this. Great link, although not sure that wiring goes by the book ;) If you don’t need all 16 ports on the last chip, you could just bend up the top two pins (1 & 28) and lose two ports. You’d still get 14 though. Hey just trying to use this chip with an 8×8 LED matrix. I’m getting some funny results, I can’t seem to set any of the MCP pins as a ground, and specifically, a ground that I can almost “turn on” when required, to give a selected ground power to selected LEDs. Any ideas? (Long shot!!) You might be running into the current limitations of the chip. It can’t provide very much current. I’ve forgotten the details, but it’s in the data sheet. Where can I find a write-up of the WiringPi2 functions/methods for Python3, including descriptions of parameters being passed through “module.method(parameter list)”? I could muddle through the source code, but that seems like an awful lot of work! As far as I know, what you find on here is the only available documentation for WiringPi2 for Python. But the good news is that the C documentation is pretty good on Gordon’s site and you can work out most things from that. wiringpi.com Hello, Thank’s a lot for that tutorial. I have bought the necessary but i have a pb. When i want to execute the python script, i can read : pi@raspberrypi ~/scripts $ sudo ./gpioextender2.py import.im6: unable to open X server `’ @ error/import.c/ImportImageCommand/368. ./gpioextender2.py: 4: ./gpioextender2.py: Syntax error: Bad function name I have no x server launch on my raspbian OS. What’s wrong ? Thank’s in advance for your help. Nico33 Are you doing this in the command line or in LXTerminal? I do that in command line with ssh. What is LXterminal ? A way of getting a terminal in LXDE. Irrelevant if you’re using ssh. I don’t know what to suggest. There is a message about function names there? I discovered the hard way that if you choose an “obvious” function name, sometimes it messes things up. e.g. once I had a program called email.py which conflicted with a function called email, buried deeply in one of the modules I was using. It could be something like that? Hah, I just had a similar problem in Perl recently! For years and years I’d been using my own read_file function, but then I needed to use a 3rd-party module that defined its own read_file function, so I had to change my function name and do a big search’n’replace over all my code files ;-) That error looks a bit weird :-/ Could you paste the full source code of your gpioextender2.py script to and then copy the relevant URL here? (LXTerminal is the default graphical terminal app on LXDE – which you obviously can’t be using if you’re not running an X server! ;-) ) here is the pastbin link : Thanks for your help. Ah… you’re not supposed to call all three ‘setup’ functions, you’re supposed to choose just one numbering scheme from “BCM GPIO numbers” or “wiringpi numbers” or “P1 header pin numbers” and stick to using just that code section. Oups … It’s a mistake. Here is the good file : pi@raspberrypi ~/scripts $ cat gpioextender.py import wiringpi2 as wiringpi from time import sleep wiringpi.wiringPiSetup() # initialise wiringpi wiringpi.pinMode(12, 2) pi@raspberrypi ~/scripts $ sudo ./gpioextender.py import.im6: unable to open X server `’ @ error/import.c/ImportImageCommand/368. from: can’t read /var/mail/time ./gpioextender.py: 4: ./gpioextender.py: Syntax error: Bad function name Aha! Now the problem is obvious – you need to use sudo python gpioextender.py (or python3 if necessary) and then it should all work. Alternatively you could add #!/usr/bin/env python as the first line of your script, and then your sudo ./gpioextender.py invocation would work. Without the #! line, the bash shell try to execute “import” as a shell command rather than running your script via the python interpreter. I am having a similar issue as Nico33 and Andrew are discussing above. Where I am not effectively telling my python interpretor what or how to run wiringpi. In playing with the execute command line: #!/usr/bin/ pythonN I think I got the program to execute, but the very next thing that happend is that I got a syntax error here: import wiringpi2 as wiringpi from time import sleep Syntax line 3 and both IDLE and Terminal pointed to the Fr in From? this lead me to believe that there was something mission in the line above “import wiringpi2 as wiringpi” . So I looked for wiringpi2 and was unable to find it. Even though I have downloaded and installed it momments previous. I am going to give it another couple of looks later today. But it seems that the call to wiringpi2 or wiringPi2 is not happy. In Python code, you need to spell ‘from’ all lower case :-) The reason you can’t ‘see’ wiringpi2 is that it got installed into a python-specific system directory (can’t remember which one it uses off the top of my head). Ah…I will have to look for wiringpi2, when I get back to the Pi tonight. I will post a transcript of my error codes as they pop up. Hopefully I will get this happening without too much more pestering. Dave Thank’s a lot for the time spent to explain to me ! And it’s ok now. Hi There, Nice tutorial I am using mcp23017 chips and I was wondering if is there a code to set up all the cip’s pins as Outputs from a single line instead of using 16 lines and setting up each pin to output. wiringpi.pinMode(65, 1) wiringpi.pinMode(66, 1) wiringpi.pinMode(67, 1) . . . . Thanks Marius No single line command as far as I know, but you could do them all in about 2 lines with a loop. I need to connect a lot of of these chip to a raspberry, so I need an external 5v power supply. I’m a beginner in electronic, could you provide a diagram to connect 2 or more of these chip with external 5v power supply without burn my raspberry? If I power my I/O chip with 5v … the GPA and SDA SCL pins works at 5v? right? so I need a MOSFET to connect it to raspberry…right? thank you Best way to do it would be power the chips with 3v3 and use a Darlington array ULN2803 chip on each side to handle the current to power your devices. If you power your IO chip with 5V, I think you’ll toast the Pi. I have read somewhere (I don’t know if is it true…) that if you connect several of these devices don’t work well with 3.3v. For this reason I want use 5v (I need 10 of these). I have found this diagramm…. What do you think about it? Thank you. I guess if you try to power too much stuff from the Pi’s (limited) 3.3V power supply that might cause problems yeah. Should work fine if you also use an external 3.3V power supply though (or you could connect a 5V->3.3V regulator to your 5V power supply). Just make sure to remember to connect all the GNDs together. I’m not qualified to comment on schematics ;) If you are drawing current to power output devices, e.g. LEDs, I would say that’s the case, but there should be enough to power a whole bunch of these chips, since you’re only powering the chip itself from the 3v3. Any current hungry outputs would be powered from the separate line (3v3, 5v or whatever you want) on the Darlington. If you want to use inputs as well, you’ll need a level converter or, as Andrew said below, a resistor divider. According to the datasheet, this chip requires 1 mA to run. You could therefore power lots of them safely with the Pi’s 3V3 lines (which can handle a total of ~60mA Max), as long as you only use them for signalling, rather than powering outputs. Couple that with the Darlington idea, and a voltage divider for your inputs and you’re sorted. ….I need to receive a flow meter sensor input (5v) as well so…in case I use the ULN2803 chip, I can connect this input sensor to the pin output? ex: flow meter 5v -> (out) ULN2803 (in) -> MCP23017 3.3v Nope, AFAIK the ULN2803 only works for switching outputs. Easiest way to connect a 5V sensor to a 3.3V input is simply using a resistor divider, along the lines of Hello, I can’t seem to get a LED to light. But, I can detect my i2c chip when I use this command: sudo i2cdetect -y 1 All I want to do is light a LED, so I changed your script to this:) # Note: MCP23017 has no internal pull-down, so I used pull-up and inverted # the button reading logic with a "not" wiringpi.digitalWrite(65, 1) # sets port GPA1 to 1 (3V3, on) The code runs without any errors but the LED does not light. I have checked and double checked my wiring and cannot figure it out. I also tried using this command: sudo i2cset -y 1 0x20 0x14 0x01 When I run this, i get this error: Error: Write failed Is the resistor too high a value? Does the LED work? Is the LED the right way round? (long leg towards the port, short leg towards GND) Is the LED connected to the right pin (8th down from the dimple, on the right hand side?) Have you tried a different pin on the port expander chip? e.g. the top right one (72 in wiringpi) It’s got to be something simple. Maybe you have a dogdy chip? Thanks for the help! It turned out one of my jumper wires was faulty. I’ve had that before too. A real nuisance. Glad you got it working. :) Until you know what kind of common problems to look for, debugging hardware can be a lot more frustrating than debugging software ;-) Yes indeed. And even then old things you learnt previously can come along and bite you in the butt when you least expect it. A jumper wire that worked yesterday might not be good today if you tugged it too hard out of the breadboard. That’s why everyone needs a multimeter. :) Missed opportunity for a link to ? ;-) Lol. Any multimeter well do. Even a cheap £10 one. I got that multimeter for reviewing it. I don’t have any stake in how well it sells. I am enjoying using it though :) That is how I found the problem. Took apart the circuit and tested all the wires. :) Hello, Have you any idea of the distance max in meter between the rasp and the MCP ? I want to have the raspberry in my home and the MCP next my swiming pool. Thanks Nico33 No idea, sorry. I suspect it’s one of those things where the only way to find out it to try it ;-) Have a look at the note on about shielded cables. But even if it doesn’t work over a long cable, the Pi is small enough that it should be easy to mount it in an external waterproof enclosure? Hey, Great tute! I’ve connected the MCP23017 chips to a 16 channel relay board and by doing this I’ve discovered that when the pins are set as outputs and turned off eg: wiringpi.pinMode(65, 1) wiringpi.digitalWrite(65, 0) They have a voltage output of 0.14V which isn’t much i know but it is still enough to trip the relays. On further investigation when turned on “wiringpi.digitalWrite(65, 1)” the output voltage is 3.44V (3.3+0.14). Any ideas why this is? Also is there a problem setting them to inputs to effectively turn them off? This gives the output voltage of 0V. Cheers, Kip Don’t most relay boards trip at 0 and switch off at 1 (i.e. 3v3 or 5v)? Could that be what you’re seeing? I know that type of board and i dont think is is and if it were i should of seen them turn off at 1. I would of thought that they would only trip at 3v3 or at 5v but they seem to trip from the 0.14v which the MCP23017 chip is outputting (pretty consistent on the multimeter) when the pin is set as an output. I’ve managed to solve the problem by turning them from outputs to inputs every time i want to turn the relays off and on. A bit hacky i know but it does the trick. Chuck a miltimeter on one of the pins and see if you get the same. Place a 220ihm resistor between the pin and ground. This will make sure that the output is zero when the state of the pin is zero. Hello I tried to make my LED blinks but it doesnt. I try running the code with the LX terminal and have no error but the LED doest light up. I tried to figure out this prblem for few days and i have no idea what is wrong. I really need your help. Thank you :) To help you, we need a good, clear, photo of your wiring. It’s almost certainly a wiring issue. We also need a proper description of what you’ve done. For example you didn’t say what sort of Pi you’re using. It’s impossible to help you without the proper information. Ordinarily I’d suggest asking in the forums, but they seem to be down at the moment due to massive traffic on the RPi site because of the Pi 2 launch. Now i got the LED light up with pin base 65. But now i have different problem where when i change to another pin such as pin base 66, the LED does not light up. I just change the pin base in the coding as well as the position of the LED at the mcp23017 chip to pin 66. Still cannot figure out what is wrong :( Hello There, I use as port expansion this does not work with your code after the launch, there are already problems with finding the wiringpi2 file could you help me? Do you have any further information about what the particular function calls are from wiringPi2 for Python and the SPI interface. I’m trying to interface to an ST Microelectronics L6470 stepper chip that has an SPI communications. For example, to tell the L6470 chip to RUN, I need to send a binary string 8 bits in length. I dunno what support there is for “raw” SPI communication within WiringPi, but for pure-Python access you could look at I would like to read all the pins without using a for loop isn’t there any function there that can do it ? Since that the the I2C can send 8 bit at once or something like that I have an old Raspi.IO-Duino that I would like to use as vanilla MCP2307 from Pi. It doesN#t however show up on I2Cdetect, and I cannot see how to get at the 3 address pins A1/A2/A3 ( of the MCP23017 pins 15-17 when installed in the RaspiIO-Duino. Are you talking about using it in the prototyping area? That’s the only way it would work on a Duino. You can’t use it in place of the ATMEGA chip because the tracking on the PCB would be all wrong.
https://raspi.tv/2013/using-the-mcp23017-port-expander-with-wiringpi2-to-give-you-16-new-gpio-ports-part-3?replytocom=33271
CC-MAIN-2022-40
refinedweb
5,790
80.01
Centrino drivers have been available to Linux for 2 years as intel put in resources to create the an open driver (with firmware limitation though). However, the newest stable version of this ipw driver has just been included in this kernel version. IPW support has been working great in Linux, even before the inclusion of it in the main kernel tree. Those drivers have been implemented by the intel guys. It's not about having a "good driver model" (may you could explaing why linux doesn't have a "good one", it certainly doesn't have a stable one - on purpose - but you may want to explain why it's "bad"), is about "having specs and/or people willing to do the dirty job". Those drivers have been living out-of-the tree for ages, anyway. My laptop is running Slackware 10.2 with Linux 2.6.14, and it's rock solid :-) Hmm, LOL here. Don't you think that is a bold statement to make for something that's been released, what, the day before? For me, 'rock solid' means 'everything working fine' (I assume that's what you mean here), but IMHO also includes 'continues to do so with time passing by' and 'with a variety of circumstances, systems and applications'. Time hasn't passed by yet, and testing by a larger audience is about to happen (but hasn't yet). Not that I have much doubt about how well the latest 2.6.x release will work for me, but unless you're a developer who just ran the exact same thing for at least a week non-stop on, say, an 8-way SMP machine under heavy load, 'rock solid' is simply a premature claim. And yes, I know pre-release (-RC1, -RC2 etc) DO get plenty of testing, but that's just not the same as the testing it gets when it's released to the public at large. And from what I gather, average Linux users don't have a habit of running every other -RC kernel. ... when "Numa-aware slab allocator" is the first item in the "comprehensible" version of the changelog. Anyway, good to see PPTP included, now maybe someone will come up with a good configuration system for it. I'm pretty sick of booting into windows every time I need to access my uni VPN. explaining what a "numa-aware slab allocator" for people who has no idea of what a slab allocator or numa is isn't exactly a easy task. It'd require more than a A4 paper. The "comprehensible changelog" is supposed to have a list of the most important kernel changes. That doesn't means people is really going to understand what they mean, by "comprehensible" it means "something that people can beat themselves to understand" (which is an almost impossible task in a 2.1 MB changelog even if you're a kernel hacker from other OS) I think Reiser4 is something so amazing (or at least hyped to be so) that enough people want it, to make it worth treating exceptionally. God, just because "it's reiser4" doesn't means they shouldn't address the problems Most people that dislike Hans appear to do so less because he's arrogant, but because he is smarter than them on some topics I won't comment on this... "I think Reiser4 is something so amazing (*****or at least hyped to be so*****)" Ding ding ding ding!!! Whether or not it really is worthy, the reason "enough people want it" is because of the hype. Most of the users clamoring for it don't know enough to be able to make a good judgement, they are motivated by hype. Let the kernel devs makes their call. They are a lot more qualified to do so than the folks who keep wondering why it isn't in. Let the kernel devs makes their call. They are a lot more qualified to do so than the folks who keep wondering why it isn't in. I think just about everybody can see the potential of Reiser 4's model, especially when it comes to things like namespaces. The sole reason why some devs are fairly hostile to it is because they can see the end of their filesystems - it's about a question of ego. They haven't looked into the future and planned ahead. Hans quite obviously has. While part of it might be ego, I think the majority just think that the current file systems are good enough. And they wonder why anyone would want to do things in such a different way. Kind of a "If it ain't broke, don't fix it" attitude. Meanwhile Hans sees that everyone accepts Reiser3, which he believes to be inferior in every way, and so he gets upset when people question why he's changing things. Let's be fair: Architectures and designs always last longer than a finite amount of resources is going to. The devs think traditional file systems will scale up as they always have and wonder why Reiser is fiddling with so many things that file systems are "supposed" to leave alone. They just don't see the upside. Not that I think they're right... Yet, it's the reality. For many people, computer data is priceless. For enterprises, it's a question of survival. Under these circumstances, anyother with some common sense would rather play safe than trying the new bling-blings that could potentially screw his data up. Now, we need some people to test the new stuff, but the average Joe won't risk himself unless necessary. That was his point. How come this post was modded down? It just states the truth. If you don't believe me, then look it up on kerneltrap.org. It seems to me that both sides in this argument were acting a little bit entitled, but I imagine they would both point to previous "discussions" to support that the other guy started it first. R4 did not make it into mainline because it really is not quite ready yet. Hans ego is causing no end of delays for those people who want R4 to go mainline. I will admit I am looking forward to the day R4 *IS* ready for mainline inclusion. Until then I will simply keep plodding along with good ole XFS Peace That's not a problem. It is a compile time option. In make menuconfig, you select the memory limit (1 GB, 4 GB, 64 GB....patched kernels go higher I believe). Ubuntu ships in its repos a 386 kernel (limit of 768 MB of RAM for some odd reason) and a 686 kernel (limit of 4 GB if I'm not mistaken). Thanks for 2.6.14 Linux kernel developers! FYI: Filesystems which only take care for the metadata are really not on the top of my list to put in production use. My *personal* favorite based on safety first is ext3, next would be vxfs on Solaris (out of scope) but both XFS and Reiserfs caused dataloss when we used it on our (I must say older) fileservers. YMMV but i'am looking forward to ext4 (extents/multiblock allocator/delayed allocation). I'd recomend people to read to see wat v9fs/9P can do. Also peek at the various plan 9 papers - these things are quite so neat. (atleast in comparison with FUSE) Ummmm, calm down people. Claiming that reiser4 wasn't included in 2.6.14 because it is utter crap and the majority of kernel developers recognize this is just plain wrong. Claiming that it wasn't included in 2.6.14 because the majority of kernel developers are protecting their egos is also plain wrong. Linux is about choice, and thats why reiser4 will eventually get merged into mainline. Even if the new concepts introduced by reiser4 aren't thought to be useful by some, there is no harm in including it in the main kernel as long as it doesn't negatively affect other parts of the kernel. There are many filesystems that are currently in mainline which *I* deem useless, but who cares? I just don't use them. Filesystem A doesn't pose a risk to my data if I don't use filesystem A; likewise reiser4 won't affect you if you choose not to use it. This is a silly flame war. When the issues around the current implementation of reiser4 are resolved then you will see it in mainline, until then, you'll have to wait or patch yourself. /mike. Regarding FUSE, what exactly is its aim - is it meant for all filesystems to eventually be put under it? I heard this can be so for both security reasons and stability reasons. Is ext2, ext3, JFS, XFS, etc. available under it? What about Reiser4 coming into the kernel, will this be going under FUSE?
http://www.osnews.com/comments/12432
CC-MAIN-2015-48
refinedweb
1,497
71.65
From: Ben Wijen <b...@wijen.net> to O_CLOEXEC (which does not exist on Windows), so let's just open temporary files with the O_CLOEXEC flag and map that flag to O_NOINHERIT on Windows. As Eric Wong pointed out, we need to be careful to handle the case where the Linux headers used to compile Git support O_CLOEXEC but the Linux kernel used to run Git does not: it returns an EINVAL. This fixes the test that we just introduced to demonstrate the problem. Signed-off-by: Ben Wijen <b...@wijen.net> Signed-off-by: Johannes Schindelin <johannes.schinde...@gmx.de> --- compat/mingw.h | 4 ++++ git-compat-util.h | 4 ++++ lockfile.h | 4 ++++ t/t6026-merge-attr.sh | 2 +- tempfile.c | 7 ++++++- tempfile.h | 4 ++++ 6 files changed, 23 insertions(+), 2 deletions(-) diff --git a/compat/mingw.h b/compat/mingw.h index 95e128f..753e641 100644 --- a/compat/mingw.h +++ b/compat/mingw.h @@ -67,6 +67,10 @@ typedef int pid_t; #define F_SETFD 2 #define FD_CLOEXEC 0x1 +#if !defined O_CLOEXEC && defined O_NOINHERIT +#define O_CLOEXEC O_NOINHERIT +#endif + #ifndef EAFNOSUPPORT #define EAFNOSUPPORT WSAEAFNOSUPPORT #endif diff --git a/git-compat-util.h b/git-compat-util.h index f52e00b..db89ba7 100644 --- a/git-compat-util.h +++ b/git-compat-util.h @@ -667,6 +667,10 @@ void *gitmemmem(const void *haystack, size_t haystacklen, #define getpagesize() sysconf(_SC_PAGESIZE) #endif +#ifndef O_CLOEXEC +#define O_CLOEXEC 0 +#endif + #ifdef FREAD_READS_DIRECTORIES #ifdef fopen #undef fopen diff --git a/lockfile.h b/lockfile.h index 3d30193..d26ad27 100644 --- a/lockfile.h +++ b/lockfile.h @@ -55,6 +55,10 @@ * * calling `fdopen_lock_file()` to get a `FILE` pointer for the * open file and writing to the file using stdio. * + * Note that the file descriptor returned by hold_lock_file_for_update() + * is marked O_CLOEXEC, so the new contents must be written by the + * current process, not a spawned one. + * * When finished writing, the caller can: * * * Close the file descriptor and rename the lockfile to its final diff --git a/t/t6026-merge-attr.sh b/t/t6026-merge-attr.sh index 3d28c78..dd8f88d 100755 --- a/t/t6026-merge-attr.sh +++ b/t/t6026-merge-attr.sh @@ -181,7 +181,7 @@ test_expect_success 'up-to-date merge without common ancestor' ' ) ' -test_expect_success !MINGW 'custom merge does not lock index' ' +test_expect_success 'custom merge does not lock index' ' git reset --hard anchor && write_script sleep-one-second.sh <<-\EOF && sleep 1 & diff --git a/tempfile.c b/tempfile.c index 0af7ebf..2990c92 100644 --- a/tempfile.c +++ b/tempfile.c @@ -120,7 +120,12 @@ int create_tempfile(struct tempfile *tempfile, const char *path) prepare_tempfile_object(tempfile); strbuf_add_absolute_path(&tempfile->filename, path); - tempfile->fd = open(tempfile->filename.buf, O_RDWR | O_CREAT | O_EXCL, 0666); + tempfile->fd = open(tempfile->filename.buf, + O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0666); + if (O_CLOEXEC && tempfile->fd < 0 && errno == EINVAL) + /* Try again w/o O_CLOEXEC: the kernel might not support it */ + tempfile->fd = open(tempfile->filename.buf, + O_RDWR | O_CREAT | O_EXCL, 0666); if (tempfile->fd < 0) { strbuf_reset(&tempfile->filename); return -1; diff --git a/tempfile.h b/tempfile.h index 4219fe4..2f0038d 100644 --- a/tempfile.h +++ b/tempfile.h @@ -33,6 +33,10 @@ * * calling `fdopen_tempfile()` to get a `FILE` pointer for the * open file and writing to the file using stdio. * + * Note that the file descriptor returned by create_tempfile() + * is marked O_CLOEXEC, so the new contents must be written by + * the current process, not any spawned one. + * * When finished writing, the caller can: * * * Close the file descriptor and remove the temporary file by -- 2.10.0.rc0.115.ged054c0 -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
https://www.mail-archive.com/git@vger.kernel.org/msg101416.html
CC-MAIN-2017-51
refinedweb
594
52.26
Hey guys, I'm quite new to AutoIt and I want to code a simple script for files. I want to drag files with my mouse from the desktop/a folder and drop them in the programm on a list. The list should add the filenames as a item. Now I would like if someone could tell me with what functions I could do this. Thats all I guess for now. best regards. Drag&Drop and List Started by Dr7 , Feb 22 2012 06:26 PM 1 reply to this topic #1 Posted 22 February 2012 - 06:26 PM #2 Posted 22 February 2012 - 06:56 PM Hi, Dr7, welcome to the forums. Check out the functions GUICreate, GUICreateList, and the GUI Control Styles page in the helpfile (specifically, $WS_EX_ACCEPTFILES). This is real quick, but should nudge you in the right direction. #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> Local $msg GUICreate("My Drag 'N Drop GUI", 200, 200) $mylist = GUICtrlCreateList("My List", 10, 10, 100, 100, Default, $WS_EX_ACCEPTFILES) GUISetState(@SW_SHOW) While 1 $msg = GUIGetMsg() If $msg = $GUI_EVENT_CLOSE Then ExitLoop WEnd GUIDelete() If you put a million monkeys on a million keyboards, one of them will eventually write a Java program. The rest of them will write Perl programs. My Scripts: SCCM UDF, Include Source with Compiled Script, Disk Maintenance for Windows XP, "Deal-A-Day" Sites, Windows Firewall UDF 0 user(s) are reading this topic 0 members, 0 guests, 0 anonymous users
http://www.autoitscript.com/forum/topic/137838-dragdrop-and-list/?p=965266
CC-MAIN-2014-42
refinedweb
243
69.01
The Java Specialists' Newsletter Issue 0062001-01-25 Category: Language Java version: GitHub Subscribe Free RSS Feed Welcome to the 6th issue of The Java(tm) Specialists' Newsletter, a weekly newsletter appearing each Thursday, which explores some of the interesting parts of the Java(tm) language. My company, Maximum Solutions, has been very active with Java programming, consulting, training and mentoring. I particularly want to thank my client DataVoice (Pty) Ltd in Stellenbosch, South Africa, for giving me the opportunity to spend hours programming in Java on one of the first real Java projects in South Africa, perhaps even the biggest, with more lines of pure Java code than the JDK 1.3, and actually paying me to have fun. Last night I worked on one of my most successful programs. It was a small 56 line program that I wrote in QuickBasic in April 1988, which my dad, who has a drinking straw manufacturing company, has used, with only minor modifications, to print thousands and thousands of labels for the boxes in which he packs his drinking straws. Perhaps one day you will see the logo "Maximum Solutions, the QuickBasic specialists!" It's a terrible program, impossible to decipher, even contains a GOTO statement (!) but it does the job extremely reliably. I had to change his address last night (yes, it's hard coded!) and was thinking about what effort would be involved in writing the same program in Java. I would probably store all the customer details in an Access database, have autocompleting combo boxes, etc., but it would cost a fortune in time and energy to produce, far more than I could save by making it "nicer". It is very important that as Java enthusiasts we keep an objective view of what applications lend themselves to Java and which do not. Otherwise we might find that we end up with something that is too expensive or too slow for its intended purpose. Overselling Java might benefit us in the short term, as companies scurry to hire us, but will damage us if Java gets a bad name. A Java Architect can command a salary of US$ 170'000 in USA at the moment, let's live up to the expectation and be responsible in our claims. NEW: Please see our new "Extreme Java" course, combining concurrency, a little bit of performance and Java 8. Extreme Java - Concurrency & Performance for Java 8. Now to the trick of the week, which is something you should never need to do. Please avoid doing this under all circumstances, because there are much better places to put method code than in interfaces, but I want to show you what is possible with inner classes. The call-back mechanism shown below is actually quite useful at times, especially if you want to make asynchronous database updates, but that is a topic for another newsletter. I want to thank Niko Brummer from DataVoice for this idea, although he vehemently denies having ever really resorted to writing implementation code in an interface. Niko is a very deep person who likes to think of alternative ways of doing things, so thanks to Niko for this crazy idea :) /** This interface contains an interfaces representing a Method and an interface showing the Result of the method call using the callback pattern. It also contains a data member (automatically public static final) which is an anonymous inner class implementing our Method interface. */ public interface CodeInsideInterface { public interface Method { public void run(Result callback); } public interface Result { public void result(Object answer); public void exception(Exception problem); } Method calculateIQ = new Method() { // I always write my data members as final if possible, this catches a // lot of bugs at compile time private final java.io.BufferedReader stdin = new java.io.BufferedReader( new java.io.InputStreamReader(System.in)); public void run(Result callback) { int iq = 100; try { System.out.print("Do you know Java (y/n)? "); if ("y".equals(stdin.readLine())) iq += 20; System.out.print("Do you know QuickBasic (y/n)? "); if ("y".equals(stdin.readLine())) iq += 20; System.out.print("Do you use the Basic GOTO statement (y/n)? "); if ("y".equals(stdin.readLine())) iq -= 30; System.out.print("Do you frequently use Java reflection (y/n)? "); if ("y".equals(stdin.readLine())) iq -= 50; callback.result(new Integer(iq)); } catch(java.io.IOException ex) { callback.exception(ex); } } }; } /** This test class demonstrates how to call the method on the interface. */ public class CodeInsideInterfaceTest implements CodeInsideInterface { public static void main(String[] args) { CodeInsideInterfaceTest test = new CodeInsideInterfaceTest(); test.calculateIQ.run(new CodeInsideInterface.Result() { public void result(Object answer) { System.out.println("Your IQ is " + answer); } public void exception(Exception ex) { ex.printStackTrace(); } }); } } Well, there you go. Try and understand what is happening in the code, because it will teach you something about inner classes and how the callback mechanism works. In the first newsletter I mentioned something about having multiple event queues in AWT / Swing and how I didn't know what the purpose is. Last Sunday I was pondering how I could possibly catch ALL events that occur in AWT / Swing and after playing around for a few hours managed to figure out how the event queues work. Next week I will show you the answer to my question in the first newsletter, i.e. why does AWT allow more than one event queue, how does it work, and what practical application is there... Send me email if you want to get back copies of newsletters. We are working on a web archive. Regards Heinz Language Articles Related Java Course
http://www.javaspecialists.eu/archive/Issue006.html
CC-MAIN-2016-44
refinedweb
928
54.73
Hi, there! Problem: I am writing to ask for guidance and advice on a situation that I dealing with on the Serial Monitor in conjunction with the Print/Write Commands. The problem I have is the text that I want to display (which is data from a PIC microcontroller) will not completely display - every other letter/number/symbol is removed. Example the phrase “I’m going somewhere to eat.” will read on the Serial Monitor as “Imgigsmweet a.”. What would cause this particular situation? Any and all advice would be greatly appreciated. Background: I am using a PIC 18F4550 microcontroller and the Adafruit Huzzah32 - ESP32 Breakout Board (Bluetooth Device). The PIC 18F4550 is being used to collect voltage readings and convert them to analog and digital values from a variable power supply. The PIC 18F4550 is connected to the ESP32 using serial communication. The objective of the ESP32 Bluetooth Device is to collect the data from the PIC 18F4550 and send it wirelessly (i.e. Bluetooth) to my cell phone. The results of the data being displayed on my Cell Phone are the same as the Serial Monitor. I do use the Serial Monitor as a means to check my code. Conclusion: I would like to know why the data from the PIC microcontroller would have every other letter/number/symbol removed. What concepts or specs or codes am I misunderstanding or lacking in knowledge with Arduino/PIC/ESP32 that would help solve this situation? I have attached my code, a diagram of the general layout of my hardware, and both the Serial Monitor and my Cell phone as it displays the data from the PIC 18F4550. I hope that I covered the necessary items needed for your help and if not then please let me know. I do thank you for your time and any and all help on this. #include <BluetoothSerial.h> //Header File for Serial Bluetooth, //will be added by default into Arduino. BluetoothSerial ESP_32; //Object for Bluetooth. int INCOMING_DATA; //Designated variable Integer that represents //ASCII value from CELL PHONE. String SERIAL_DATA; //created a character variable for BT. void setup() { Serial.begin(115200); //Activates Serial Port. Serial1.begin(115200); //Activates Serial1 Port. ESP_32.begin("ESP32 BLUETOOTH"); //Activates Bluetooth and designates ID //for BT signal when pairing w/cell phone. Serial.println("ESP32 is initialized. Proceed to pair using bluetooth."); //Phrase is read on Serial Monitor. pinMode (13, OUTPUT); //GPIO Pin is set as an LED output } void loop() { if (ESP_32.available()) //Checks if Bluetooth is receiving data. { INCOMING_DATA = ESP_32.read(); //Reads incoming data from CELL PHONE and //stores incoming data in INCOMING_DATA. //NOTE: the data value from CELL PHONE is //in the char form so on SERIAL MONITOR //the value is in decimal value. Serial.print("Received: "); //Phrase is printed on SERIAL MONITOR as //readable ASCII text. Serial.println(INCOMING_DATA); //Prints data on SERIAL MONITOR & used to //verify data sent from CELL PHONE. //NOTE: will receive DEC 13 and DEC 10 at //end of each data from CELL PHONE that //represent a RETURN & END of Line of text. } if (INCOMING_DATA == 97) //a on the keypad { while (Serial1.available()) { ESP_32.write(Serial1.read()); Serial.write(Serial1.read()); //Previous two codes write data from PIC and //display it on CELL PHONE & SERIAL MONITOR. } } ////****This is the ESP32 LED On/Off Section****//// if (INCOMING_DATA == 49) //1 on the keypad. { digitalWrite(13, HIGH); //LED reads high. ESP_32.println("LED turned ON\nAnd will Remain ON!!"); //Indicates ouput status on CELL PHONE. ESP_32.println(" "); //Places a space inbetween data. } if (INCOMING_DATA == 48) //0 on the keypad. { digitalWrite(13, LOW); //LED reads low. ESP_32.println("LED turned OFF\nAnd will Remain OFF!!"); //Indicates ouput status on CELL PHONE. ESP_32.println(" "); //Places a space inbetween data. } delay(1); }
https://forum.arduino.cc/t/clarity-on-serial-monitor-and-print-write-commands/623572
CC-MAIN-2021-43
refinedweb
624
59.19
Huey Extensions¶ The huey.contrib package contains modules that provide extra functionality beyond the core APIs. Mini-Huey¶ MiniHuey provides a very lightweight huey-like API that may be useful for certain classes of applications. Unlike Huey, the MiniHuey consumer runs inside a greenlet in your main application process. This means there is no separate consumer process to run, not is there any persistence for the enqueued/scheduled tasks; whenever a task is enqueued or is scheduled to run, a new greenlet is spawned to execute the task. Usage and task declaration: from huey import crontab from huey.contrib.minimal import MiniHuey huey = MiniHuey() @huey.task() def fetch_url(url): return urllib2.urlopen(url).read() @huey.task(crontab(minute='0', hour='4')) def run_backup(): pass Note There is not a separate decorator for periodic, or crontab, tasks. Just use MiniHuey.task() and pass in a validation function. When your application starts, be sure to start the MiniHuey scheduler: from gevent import monkey; monkey.patch_all() huey.start() # Kicks off scheduler in a new greenlet. start_wsgi_server() # Or whatever your main application is doing... Warning Tasks enqueued manually for immediate execution will be run regardless of whether the scheduler is running. If you want to be able to schedule tasks in the future or run periodic tasks, you will need to call start(). Calling tasks and getting results works about the same as regular huey: async_result = fetch_url('') html = async_result.get() # Block until task is executed. # Fetch the Yahoo! page in 30 seconds. async_result = fetch_url.schedule(args=('',), delay=30) html = async_result.get() # Blocks for ~30s. SQLite Storage¶ The SqliteHuey and the associated SqliteStorage can be used instead of the default RedisHuey. SqliteHuey is implemented in such a way that it can safely be used with a multi-process, multi-thread, or multi-greenlet consumer. Using SqliteHuey is almost exactly the same as using RedisHuey. Begin by instantiating the Huey object, passing in the name of the queue and the filename of the SQLite database: from huey.contrib.sqlitedb import SqliteHuey huey = SqliteHuey('my_app', filename='/var/www/my_app/huey.db') Note The SQLite storage engine depends on peewee. For information on installing peewee, see the peewee installation documentation, or simply run: pip install peewee. Dj = { 'name': settings.DATABASES['default']['NAME'], # Use db name for huey. 'result_store': True, # Store return values of tasks. 'events': True, # Consumer emits events allowing real-time monitoring. 'store_none': False, # If a task returns None, do not save to results. 'always_eager': settings.DEBUG, # If DEBUG=True, run synchronously. 'store_errors': True, # Store error info if task throws exception. 'blocking': False, # Poll the queue rather than do blocking pop. 'connection': { 'host': 'localhost', 'port': 6379, 'db': 0, 'connection_pool': None, # Definitely you should use pooling! # ... tons of other options, see redis-py for details. # huey-specific connection parameters. 'read_timeout': 1, # If not polling (blocking pop), use timeout. 'max_errors': 1000, # Only store the 1000 most recent errors. 'url': None, # Allow Redis config via a DSN. }, 'consumer': { 'workers': 1, 'worker_type': 'thread', 'initial_delay': 0.1, # Smallest polling interval, same as -d. 'backoff': 1.15, # Exponential backoff using this rate, -b. 'max_delay': 10.0, # Max possible polling interval, -m. 'utc': True, # Treat ETAs and schedules as UTC datetimes. 'scheduler_interval': 1, # Check schedule every second, -s. 'periodic': True, # Enable crontab feature. 'check_worker_health': True, # Enable worker health checks. 'health_check_interval': 1, # Check worker health every second. }, }, however, you would like to enqueue tasks regardless of whether DEBUG = True, then explicitly specify always_eager=False in your huey settings: # settings.py HUEY = { 'name': 'my-app', # Other settings ... 'always_eager':')
http://huey.readthedocs.io/en/latest/contrib.html
CC-MAIN-2017-47
refinedweb
582
52.97
I'm really confused as to how to set up this program. The program is to have a function "trap", so I'm guessing that means I have to include a function that solves the integral before my main function? #include <stdio.h> #include <math.h> double f(double x) { return exp(-x*x); } double f(double x) { return exp(-x); } float a; float b; float x; float h; float sum; float s; int n; int i; int trapeze(int n, int i) { h=(b-a)/n; s=(0.5*h)*(f(a)+f(b)); for (i = 1; i < n; i++) { sum = s+h*f(a+(i*h)); } } int main(void) { printf("Enter the number of intervals: "); scanf("%d", &n); return 0; } So basically we're given 2 functions: f(x) = e^(-x^2) and f(x) e^(-x). The program is suppose to solve both them them depending on number of interval the user inputs. I've sat here for 3 hours trying to figure this out, and I've been just throwing codes together. Hoping to get a good insight on how to better approach this. I believe I have the function that inputs the trapezoidal rule correctly.
https://www.daniweb.com/programming/software-development/threads/394971/trapezoidal-rule-integration-in-c-solving-two-functions
CC-MAIN-2019-22
refinedweb
200
69.92
namespace(n) Tcl Built-In Commands namespace(n) ______________________________________________________________________________ NAME namespace - create and manipulate contexts for commands and variables SYNOPSIS namespace ?option? ?arg ...? _________________________________________________________________ DESCRIPTION The namespace command lets you create, access, and destroy separate contexts for commands and variables. See the section WHAT IS A NAMES‐ PACE? below for a brief overview of namespaces. The legal option's are listed below. Note that you can abbreviate the option's. namespace children ?namespace? ?pattern? Returns a list of all child namespaces that belong to the names‐ pace namespace. If namespace is not specified, then the chil‐ dren are returned for the current namespace. This command returns fully-qualified names, which start with ::. If the optional pattern is given, then this command returns only the names that match the glob-style pattern. The actual pattern used is determined as follows: a pattern that starts with :: is used directly, otherwise the namespace namespace (or the fully- qualified name of the current namespace) is prepended onto the‐ pace code {foo bar}] is invoked in namespace ::a::b. Then eval "$script x y" can be executed in any namespace (assuming the value of script has been passed in properly) and will have the same effect as the command ::namespace eval ::a::b {foo bar x y}. This command is needed because extensions like Tk normally execute callback scripts in the global namespace. A scoped com‐ mand captures a command together with its namespace context in a way that allows it to be executed properly later. See the sec‐ tion SCOPED VALUES for some examples of how this is used to cre‐ ate‐ dures, and child namespaces contained in the namespace are deleted. If a procedure is currently executing inside the namespace, the namespace will be kept alive until the procedure returns; however, the namespace is marked to prevent other code from looking it up by name. If a namespace doesn't exist, this command returns an error. If no namespace names are given, this command does nothing. namespace eval namespace arg ?arg ...? Activates a namespace called namespace and evaluates some code in that context. If the namespace does not already exist, it is created. If more than one arg argument is specified, the argu‐ ments are concatenated together with a space between each one in the same fashion as the eval command, and the result is evalu‐ ated. If namespace has leading namespace qualifiers and any leading namespaces do not exist, they are automatically created. namespace exists namespace Returns 1 if namespace is a valid namespace in the current con‐ text, returns 0 otherwise. namespace export ?-clear? ?pattern pattern ...? Specifies which commands are exported from a namespace. The exported commands are those that can be later imported into another namespace using a namespace import command. Both com‐ mands defined in a namespace and commands the namespace has pre‐ viously imported can be exported by a namespace. The commands do not have to be defined at the time the namespace export com‐ mand is executed. Each pattern may contain glob-style special characters, but it may not include any namespace qualifiers. That is, the pattern can only specify commands in the current (exporting) namespace. Each pattern is appended onto the names‐ pace's list of export patterns. If the -clear flag is given, the namespace's export pattern list is reset to empty before any pattern arguments are appended. If no patterns are given and the -clear flag isn't given, this command returns the names‐ pace's current export list. namespace names‐ pace name. For each simple pattern this command deletes the matching commands of the current namespace that were imported from a different namespace. For qualified patterns, this com‐ mand first finds the matching exported commands. It then checks whether any of those commands were previously imported by the current namespace. If so, this command deletes the correspond‐ ing imported commands. In effect, this un-does the action of a namespace import command. namespace import ?-force? ?pattern pattern ...? Imports commands into a namespace. Each pattern is a qualified name like foo::x or a::p*. That is, it includes the name of an exporting namespace and may have glob-style special characters in the command name at the end of the qualified name. Glob characters may not appear in a namespace name. com‐ mand. This command normally returns an error if an imported command conflicts with an existing command. However, if the -force option is given, imported commands will silently replace existing commands. The namespace import command‐ pace inscope command is much like the namespace eval command except that the namespace must already exist, and namespace inscope appends additional args as proper list elements. namespace inscope ::foo $script $x $y $z is equivalent to names‐ pace‐ qualifiers string Returns any leading namespace qualifiers for string. Qualifiers are namespace names separated by ::s.‐ ifiers are namespace names separated by ::s. For the string ::foo::bar::x, this command returns x, and for :: it returns an empty string. This command is the complement of the namespace qualifiers command. It does not check whether the namespace names are, in fact, the names of currently defined namespaces. namespace which ?-command? ?-variable? name Looks up name as either a command or variable and returns its fully-qualified name. For example, if name does not exist in the current namespace but does exist in the global namespace, this command returns a fully-qualified name in the global names‐ pace. If the command or variable does not exist, this command returns an empty string. If the variable has been created but not defined, such as with the variable command or through a trace on the variable, this command will return the fully-quali‐ won‐ mand named bump in the global namespace, for example, it will be dif‐ ferent from the command bump in the Counter namespace. Namespace variables resemble global variables in Tcl. They exist out‐ side of the procedures in a namespace but can be accessed in a proce‐‐ chically. A nested namespace is encapsulated inside its parent names‐ pace and can not interfere with other namespaces. QUALIFIED NAMES Each namespace has a textual name such as history or ::safe::interp. Since namespaces may nest, qualified names are used to refer to com‐ of namespace ::safe, which in turn is a child of the global namespace ::. If you want to access commands and variables from another namespace, you must use some extra syntax. Names must be qualified by the names‐ pace that contains them. From the global namespace, we might access the Counter procedures like this: Counter::bump 5 Counter::Reset We could access the current count like this: puts "count = $Counter::num" When one namespace contains another, you may need more than one quali‐ :s in a qualified name are ignored; that is, two or more :s are treated as a namespace separator. A trailing :: in a qualified variable or command name refers to the variable or command named {}. However, a trailing :: in a qualified namespace name is ignored. NAME RESOLUTION In general, all Tcl commands that take variable and command names sup‐ a fixed rule for looking it up: Command and variable names are always resolved by looking first in the current namespace, and then in the global names‐ pace. Namespace names, on the other hand, are always resolved by look‐ ing in only the current‐ a ::. Tcl has no access control to limit what variables, commands, or names‐ paces you can reference. If you provide a qualified name that resolves to an element by the name resolution rule above, you can access the element. You can access a namespace variable from a procedure in the same names‐‐ mands are used so frequently that it is a nuisance to type their quali‐ don't know what you will get. It is better to import just the spe‐ cific‐. SEE ALSO variable(n) KEYWORDS exported, internal, variable Tcl 8.0 namespace(n)[top]
http://www.polarhome.com/service/man/?qf=namespace&tf=2&of=OpenDarwin&sf=n
CC-MAIN-2018-05
refinedweb
1,325
61.97
Bugs item #995347, was opened at 2004-07-21 09:14 Message generated for change (Tracker Item Submitted) made by Item Submitter You can respond by visiting: Category: None Group: None Status: Open Resolution: None Priority: 5 Submitted By: Nobody/Anonymous (nobody) Assigned to: Nobody/Anonymous (nobody) Summary: Waste mov in GenCast Initial Comment: SDCC codegeneration error: Source: #include <8051.h> static unsigned int work1; void test(unsigned char arg1, unsigned char arg2) { register unsigned int tmp1; //Waste mov in typecasting! tmp1=arg1 << 8; tmp1|=arg2; work1=tmp1; } void main(void) { test(7,3); } SDCC run command: sdcc --verbose --model-small --peep-asm -mmcs51 -- iram-size 256 --xram-size 0 --code-size 12288 --nojtbound test.c SDCC version: SDCC : mcs51/gbz80/z80/avr/ds390/pic16/pic14/TININative/xa51 /ds400/hc08 2.4.2 (Jul 16 2004) (MINGW32) Asm list: 306 ;------------------------------ ------------------------------ 307 ;Allocation info for local variables in function 'test' 308 ;------------------------------ ------------------------------ 309 ;arg2 Allocated with name '_test_PARM_2' 310 ;arg1 Allocated to registers r2 311 ;tmp1 Allocated to registers r2 r3 312 ;------------------------------ ------------------------------ 313 ;test.c:5: void test(unsigned char arg1, unsigned char arg2) 314 ; --------------------------- -------------- 315 ; function test 316 ; --------------------------- -------------- 0031 317 _test: 0002 318 ar2 = 0x02 0003 319 ar3 = 0x03 0004 320 ar4 = 0x04 0005 321 ar5 = 0x05 0006 322 ar6 = 0x06 0007 323 ar7 = 0x07 0000 324 ar0 = 0x00 0001 325 ar1 = 0x01 326 ; genReceive 0031 AA 82 327 mov r2,dpl 328 ;test.c:9: tmp1=arg1 << 8; 329 ; genCast ------------------------------------------------------- --- 0033 7B 00 330 mov r3,#0x00 Waste mov! ------------------------------------------------------- --- 331 ; genLeftShift 332 ; genLeftShiftLiteral 333 ; genlshTwo ------------------------------------------------------- --- 0035 8A 03 334 mov ar3,r2 0037 7A 00 335 mov r2,#0x00 ------------------------------------------------------- --- 336 ;test.c:10: tmp1|=arg2; 337 ; genCast 0039 AC*00 338 mov r4,_test_PARM_2 003B 7D 00 339 mov r5,#0x00 340 ; genOr 003D EC 341 mov a,r4 003E 4A 342 orl a,r2 003F F5*00 343 mov _work1,a 0041 ED 344 mov a,r5 0042 4B 345 orl a,r3 0043 F5*01 346 mov (_work1 + 1),a 347 ;test.c:11: work1=tmp1; 0045 348 00101$: 0045 22 349 ret I'm fix this bug by peephole rule: replace { mov %1,%2 mov a%1,%3 } by { ; peephole r.1 mov a%1,%3 } ---------------------------------------------------------------------- You can respond by visiting: > I have an updated version of the zeropad regression test which > includes a test-case for bug 984229, the truncating of excessive > initializers for arrays. Now SDCC generates a warning for this, which is > fine for normal use. But I'm not sure if all code that parses the output > of the regression tests can handle this. SDCC shouldn't emit any warning in the regression tests. The test suite only checks the return code of SDCC. If you want to test, if SDCC correctly emits warnings and/or errors, please use the Eric's test suite located in support/valdiag. Bernhard Feature Requests item #920165, was opened at 2004-03-20 19:58 Message generated for change (Comment added) made by maartenbrock You can respond by visiting: Category: None Group: None Status: Open Priority: 5 Submitted By: Stas Sergeev (stsp) Assigned to: Nobody/Anonymous (nobody) Summary: Optimize away movs between the same loc Initial Comment: Hi. Sometimes sdcc produces the movs where the source and dest are the same operands. The peephole rule 206 removes the "mov %1,%1" cases, but the following code: --- struct { unsigned char a; unsigned char b; } c; char main() { c.a &= 0xff; c.b &= 0xff; return 0; } --- generates this: --- ; genAssign ; genPointerSet ; genNearPointerSet ; genDataPointerSet mov (_c + 0x0001),0x0001 + _c --- which can be troublesome to catch with peephole, given the other variations are possible. Instead, genAssign() of mcs51/gen.c calls operandsEqu() to skip the redundant movs (I suppose). But for some reasons operandsEqu() doesn't seem to recognize those as the similar ones. It would be nice to have the (mcs51) codegen to optimize such a code without a help from peephole. I suppose this will require only extending/fixing the operandsEqu() function, which seems to be intended exactly for that but somehow doesn't do the trick. ---------------------------------------------------------------------- >Comment By: Maarten Brock (maartenbrock) Date: 2004-07-21 09:21 Logged In: YES user_id=888171 Stas, Maybe it can be optimized by peephole, but no further than below since you don't know if r2 will be used or not in the following code. step1: mov r2,_c mov r2,(_c + 1) step2: mov r2,(_c + 1) iCode optimization can however take liveranges into account. Maarten ---------------------------------------------------------------------- Comment By: Stas Sergeev (stsp) Date: 2004-07-20 23:00 Logged In: YES user_id=501371 Hi Maarten. I think this RFE can be closed. The code it now generates, looks like this: mov r2,_c mov _c,r2 mov r2,(_c + 1) mov (_c + 1), r2 This have nothing to do with the code I showed, and this can be trivially optimized by peephole (but why not yet?). > Just took a quick peek, but operandsEqu() is not called for > this testcase. operandsEqu() seems to be *always* called for genAssign(). However, this code no longer hits the genAssign(), so I guess you are right. However, as you can see from the original code snip, it used to pass the genAssign(), so operandsEqu() was called. Something have been changed. This RFE is no longer valid. I am only wondering now why the code it now generates, is not optimized by peephole. ---------------------------------------------------------------------- Comment By: Maarten Brock (maartenbrock) Date: 2004-07-20 20:30 Logged In: YES user_id=888171 Just took a quick peek, but operandsEqu() is not called for this testcase. So it's hard for this function recognize anything ;-) When looking at the dump output I think this should be solved in iCode optimization. iTemp4 ... {unsigned-char}[r2 ] = @[iTemp0 ... {struct __00010000 near* }[remat]] *(iTemp0 ... {struct __00010000 near* }[remat]) := iTemp4 ... {unsigned-char}[r2 ] ---------------------------------------------------------------------- You can respond by visiting: Hi all, Sorry for chiping in late. This generated so much response that I am interested to look more into it. I think u guys have missed a point that the use of macros (#define) should be minimized, and in such case, I think its better for everyone that: const unsigned char RS485_POWER_MASK = 0x08; would that solve all the problems of inefficiencies? since much of the question revolves around whether 0x08 is signed or unsigned. I looked into enum at first, but later realized that enums are actually signed also. I guess 'const' made way into C for a reason. If #define are used, go ahead and make it inefficient or inaccruate, since macros are continuously warned by books to produce unpredicatable results, some of the time. Cheers, Phuah Yee Keat SourceForge.net wrote: > Bugs item #979599, was opened at 2004-06-25 10:44 > Message generated for change (Comment added) made by bernhardheld > You can respond by visiting: > > > Category: C-Front End > Group: fixed > >>Status: Open > > Resolution: Fixed > Priority: 5 > Submitted By: Josef Pavlik (jetset) > Assigned to: Maarten Brock (maartenbrock) > Summary: inefficent/wrong code for PORT&=~mask > > Initial Comment: > hello > I found, that the expression > PORT &= ~mask > is not compiled efficently, in some cases this code can make unpredictable result. I expect, that the resulting code will be > anl PORT, #~mask > but the value of the port is loaded to the register, then anded with mask and is reloaded to the port. If the port value change or if this is some input signals on the port, the 0 read from input signal will be written as 0 to output and will block the input port. > The expression PORT |= mask is compiled OK > > I'm using the last version of compiler (15.6.04) with --model-large > > see the piece of resulting code in attachment > > > #define RS485_POWER_PORT P3 > #define RS485_POWER_MASK 0x08 > > ;rs485.c:321: RS485_POWER_PORT|=RS485_POWER_MASK; > ; genOr > orl _P3,#0x08 > ; Peephole 112.b changed ljmp to sjmp > ; Peephole 251.b replaced sjmp to ret with ret > ret > 00102$: > ;rs485.c:325: RS485_POWER_PORT&=~RS485_POWER_MASK; > ; genAssign > mov r2,_P3 > ; genAnd > mov a,#0xF7 > anl a,r2 > mov _P3,a > 00104$:
https://sourceforge.net/p/sdcc/mailman/sdcc-devel/?viewmonth=200407&viewday=21
CC-MAIN-2017-39
refinedweb
1,329
67.79
Today we are starting the new CLion 2018.3 Early Access Program! There are big plans for this release, and we will do our best to achieve as much as possible. We welcome all of you to give the new features and enhancements a try, and share your feedback with us. Find below a detailed description of the following new features and improvements: - Initial remote development support - Unit testing improvements - Quick Documentation: formatted macro expansion - A scheme to validate compile_command.json files - New Search Everywhere - Universal Run Anything - Other improvements: C++17 features, mark as plain text, and more Download CLion 2018.3 EAP Initial remote development support A while ago we started working on remote development support in CLion. And in this EAP we are excited to announce that we have already been able to add initial support which is ready for you to try! It works macOS, Linux or Windows local client machines and Linux as a remote host. We assume that your source files are on the local machine and that CLion will automatically synchronize them to the remote host. With just a simple configuration step you can get CLion, which runs locally, to build, run, and debug your application and its tests on a remote machine. For more details, please, refer to this detailed blog post. Unit testing Performance CLion integrates with Google Test, Boost.Test, and Catch frameworks for unit testing. The integration provides you with a built-in test runner, framework specific Run/Debug configurations, icons in the left gutter which report the status of the tests. In the case of Google Test, there is also a test generating feature that helps to create test and test fixture stubs. In this EAP we’ve reworked the whole integration in order to resolve dozens of performance issues (UI freezes when navigating to test results, performance issues when completing test macros, etc.). There has been a huge amount of work gone into reworking the whole integration which will hopefully make your work with unit tests in CLion much more pleasant thanks to the more responsive UI. Show Test List Test detection in CLion is implemented in a lazy manner to reduce indexing times. Thus for diagnostic purposes, we’ve implemented a new action “Show Test List”. You can call it from the Find Action dialog, and it will open a text file with a list of all the tests (Google Test, Boost.Test or Catch frameworks are detected) currently detected in the project. Note, the action currently doesn’t trigger test indexing. Output processing We have introduced a few fixes in this build to get more accurate test results’ processing: - Google Test: Problems with the colored output (CPP-10823) - Google test: cerroutput not shown in UI (CPP-10821) - Tests with a non-ascii name are now recognized (CPP-11497) - Google Test: printing in stdout/err breaks output (CPP-4780) - CLion now supports OpenCV GTest modification (CPP-13680) Quick Documentation: formatted macro expansion The Quick Documentation popup is really handy when you work with macros, as it shows you the final macro replacement, so you can quickly understand the code that will be substituted after the preprocessor pass. But when you have a complicated deeply nested macro, the final replacement might not work for you if not formatted properly. That’s why CLion now formats the macro replacement in the Quick Documentation popup and also highlights strings and keywords used in the final substitution. For example, this is how it looks for the Boost.Test macro: And here is the replacement for the Catch test macro: Validation for compilation database files CLion 2018.2 introduced compilation database project model support. Which meant that you could now open compile_command.json files, created in advance, as project files in CLion. In this version, we’ve added specific inspections to check the compliance with the compilation database JSON schema. For example, it notices when you use a wrong type: or miss the property completely: New Search Everywhere The new Search Everywhere popup was introduced in all IntelliJ-based IDEs in 2018.3 EAP. Our main goal was to solve a lot of the annoying issues with dialog performance, losing focus, incorrect resize, and other things like this. Moreover, now this popup incorporates several actions at once: Search Everywhere ( Double Shift), Find Action ( Ctrl+Shift+A / ⇧⌘A), Go to class ( Ctrl+N / ⌘O), Go to file ( Ctrl+Shift+N / ⇧⌘O), and Go to symbol ( Ctrl+Alt+Shift+N / ⌥⌘O) action. Each one has its own separate tab in the dialog, and you can use TAB to switch between these tabs. And all the specific action shortcuts still work, so for example, Ctrl+N / ⌘O will open Classes tab: Universal Run Anything dialog Another universal dialog in IntelliJ-platform IDEs is called Run Anything, and you can open it with Double Ctrl. It allows you to: - Search and launch any configuration - Open a project (just type “Open” and select the desired project from the list) - And even debug any configuration of your choice (hold down the Shiftkey, and the dialog will switch to Debug Anything mode) Other improvements Among the other important changes we’d like to highlight: - The “Mark as Plain Text” action is now available in CLion. It allows you to remove big and complicated files from indexing, so disabling smart assistance for such files (for example, code completion, navigation, refactorings) and improving the IDE’s performance. And you can easily revert the files back at any time from the context menu. - CLion now parses C++17 fold expressions and C++17 deduction guides correctly. For the user this means not only less false code highlighting, but also better code assistance, for example, for the user-defined deduction guides: - Bundled GDB version was updated to 8.2. - An important issue with CMAKE_TOOLCHAIN_FILE was fixed in this version. A bug caused system include directories and system #defines to be incorrectly detected, which lead to the incorrect coding assistance (CPP-11250). That’s it for now! The full release notes are available by the link. Get the new build from our site and give it a try today! Your feedback is very welcome here in the comments and in our tracker. Download CLion 2018.3 EAP Your CLion Team JetBrains The Drive to Develop Debugger memory view please! I’m glad to say it’s under development now It’s really great that so many bugs are fixed! Question please, not related to this: how can I set the path for external clang-tidy file? What path does CLion use? The main CMakeLists or project root? Set via CMake-Change Project Root? CLion uses bundled Clang-Tidy executable. If you wish to change it, you can switch in Settings | Languages & Frameworks | C/C++ | Clang-Tidy. Quick question though, why do you need it? Do you have some custom checks implemented over clang-tidy? I want to change the clang-tidy configuration file, not clang-tidy binary, sorry for the confusion. Please check also this fresh bug: CPP-14239, it’s really annoying to have a red folder in the explorer. There are two ways to configure Clang-Tidy checks: 1) in CLion settings: Settings | Editor | Inspections | C/C++ | General | Clang-Tidy 2) specify there that you are using .clang-tidy config files. Find more details in our webhelp: We do keep an eye on the issue tracker, processing all the requests as soon as possible, at least to suggest some workaround or request additional details. But please be patient. We have a whole bunch of newly created tickets there after the first EAP was started yesterday. I think the option for aligning multiline function parameters is broken. When I write this: void foobar (std::string a, std::string b) { ---------------------------^ Hit Enter here Then I get void foobar (std::string a, std::string b) { //Indented with 8 spaces but I am expecting: void foobar (std::string a, std::string b) { //Aligned with s of std If you call reformat with Wrapping and Braces | Function Declaration Parameters | Align when multiline option set, should be aligned properly. It’s indeed not aligned while typing and we have a few issues related:,,. If you could fix CPP-1194 this cycle that would be really great. We’ll check I’m really sad that the ctest ingratiation is not in the road map. We are a paying costumer with an increasing number of licences. we manage huge number of test and execution variation with ctest -> like remote execution on target devices. Today with Clion I have to setup each test deployment, execution in the ide by clicking around. With ctest integration all this would be avoided. Please try to consider ctest integration with higher priority. Thank you for your feedback! We do have it in our plans. However in this cycle we are focused on improving the unit testing frameworks integration, especially in terms of performance, but also focusing on unified API. When it’s done, it will be much easier to get CTest on board. Or even open a public API for unit test subsystem in CLion. Google Test is still ridiculously slow… I was experiencing a lot of freezes due to some google test calculations… Now with this EAP it doesn’t freeze anymore. But now I’m just waiting for more than 15 mins to ‘Prepare Test Run’… that just prints “Processing file: file_name.cpp” multiple times (with exactly same file name). Could you please tell us, do you use all-tests(…) pattern or simply list the tests to run in the configuration? Let me explain: we need to find all tests in the file file_name.cpp. if you are using ‘All in file_name.cpp’ configuration with meta-pattern all-tests(). There is the way to accelerate the run and replace the all-tests()pattern to the explicite test-list-pattern from Messages|Prepare Test Run|Pattern to run:after the first run. I’ve just opened cpp file with gtests. Observed that there is no ‘run’ marks near line numbers as before. Then I’ve right clicked on editor tab and selected ‘Run all in file_name.cpp’. It’s already more than 1 hour since I tried to run it. And it still prepares something… So I was not able to run it first time… I’ve posted my comment to CPP-11409 (which is resolved). PS. At the same time I was able to run unit tests on small hello-world size project. So it’s some sort of scalability issue. PPS. I’ve also tried to add #if 0 / #endif after includes. And it doesn’t help Let’s proceed in the ticket. Please consider this small but very helpful Doxygen parameter coloring feature: It’s already implemented in IntelliJ, and CLion already understands parameter names enough to refactor them, so I would hope it would not be terribly difficult. This would make reading Doxygen comments much more pleasant for all C and C++ projects. Thanks, we’ll do. Not in the nearest plans unfortunately, but will definitely check if we can incorporate it soon. I’m surprised that CPP-7361 is still not fixed. For me it makes generators unusable: 1) Have to wait 1-2 seconds before can I invoke generator 2) Generated code very often uses wrong signature Roman, thank you for reminding us about this issue. We’ll check when we can cover it. Why is it taking so much time to build the symbols after creating new and opening existing project? My CPU goes to 100% on my laptop which annoys me. I don’t have this with VS. CLion takes all the CPU resources to make the initial indexing or open an existing project and prepare it for using in the IDE. If you feel it’s using too much of the resources, please make and report a CPU snapshot to us. I see. It also takes about 14% of the memory, or about 1.3 GB which is huge. Why is it so resource hungry compared to other IDE’s I don’t know. Thank you for the response! How do you estimate the memory? CLion is JVM process and by default it reserves 2Gb of RAM. You can turn on the built-in memory indicator in Settings/Preferences | Appearance & Behavior | Appearance | Windows option | Show memory indicator and check the real usage. Those numbers came from Task Manager. Please check what built-in memory indicator shows. Task manager shows the pre-allocated memory size for java process and a real usage for clangd. Clion maintains two separate code models : in Java and in Clangd. So expect that it will take 2 times more memory than other IDEs. In my project for example Clangd consumes about 1 GB, and Clion/JVM usually use about 2GB. BTW, we plan to get deeper with analysing how clangd acquires memory and work in this direction to improve the usage. Does ‘remote development’ planned to work with local docker containers? I mean, is it possible to work more straight way having in mind the possibility to directly access sources (via exported folder – no need to explicitly copy/sync them); and also shell access via direct docker execinstead of using ssh? Yes, we plan to add docker support in nearest feature, but can’t provide exact estimations here. Here’s the ticket, feel free to vote: Any plans to implement CPP-154? Reported 5 years ago… Nice and useful addition indeed. Thanks for reminding about it. Let us consider and see if we can fit it into some upcoming roadmap. Any update on? We’ll check with the team. Should be possible, but just currently busy with other tasks. I have the following issue in Android Studio that I think is related to Clion’s CMake support: If my CMakeLists.txt (and thus all of my cpp files) are located outside of a module: ./Root/Project->Module ./Root/Sources/CppSources The code inspections turn everything red. I should check if there is similar issue in Clion. Can that be fixed? CLion expects project sources to the located in the Project Root directory. Project Root by default is a folder with the top-level CMakeLists.txt files. You can change it in Tools | CMake | Change project root in CLion. AS however supports only the Android C++ projects, not the general CMake projects, so additional issues might be possible. After further investigation I concluded that this issue might be gradle/AS only. Anyway CLion shouldn’t assume that all project sources are in the same source root directory. The use case I see is if you have external libraries (maybe even shared between projects) that you don’t want to be part of your project but still be available for viewing/editing. But libraries are fine, they can be outside of the project of course. Can we have mouse zoom level be remembered between sessions? Even better when the mouse wheel is used to increase the font size in a tab all other tabs also get the increase font setting and this gets saved between sessions. Feel free to put this ideas into the request here:. The remote development support is great, is it possible to bring this to windows-WSL as well? Right now I have to run it under a linux VM. What do you mean by that? WSL is supported in CLion as a local toolchain. It is a huge difficulty right now to work with CLion on Windows, because of lack of MSVC debugger. For a very long time I’m waiting for this feature, and I’m really disappointed every single release. Could you please help us better understanding the case? You are on Windows with windows environment, MSVC, and what’s the build system? CMake? Is it initial or you’ve build it especially to open project in CLion? is your development fully Windows specific or you just use Windows as a development platform? Hello, Anastasia! Thanks for the quick reply. We’re a team of many people, developing a cross-platform application. Our build system is CMake. On Windows our compiler is MSVC (on Mac it’s clang, so people, whose development platform is Mac, are already happy with CLion). We use pre-built libraries, and our continious integration on Windows is running on MSVC (so there’s no way I can use MinGW as a compiler). There’s a working workflow that I found for myself: writing code and building in CLion, and debugging in Visual Studio Code. But it’s such a pain to switch between these 2 IDEs all the time. Using Visual Studio is also not a good option for me, because I switch operation systems very often and it’s not available for other operation systems. Thank you. This is very helpful indeed. We can’t estimate the task, but the work was already started. The problem is that we have to implement the debugger on our own, as VS debugger is proprietary. We hope we will be able to run some preview in 2018-beginning 2019. Hi Anastasia, Can you comments on environment variable expansion in the Cmake: Generation Path-field. I am a little confused as the closest to this became ticket: I believe that is not really what I am looking for. Neither I care if it is saved with the project, nor do I care for “special” variable expansion. However we have a dedicated build system that dictates the build paths, but sets them in an environment var. Having to manually copy this relative/absolute path is kind of a pain. I know that this particular system (rez) is quite widely used in the vfx/animation industry, I can’t be the only one struggling. If we could just expand environment variables it would be a second to make a clion project compatible, so the build would reuse existing temporary files. Is this something I should reflect in a separate issue? I fear that the one mentioned is bigger than my request and will delay a possible easy fix. Thanks. We’ll check and reply in the ticket. how can I set the code style “int *num” to “int* num”? If that’s CLion’s native formatter: Settings/Preferences | Editor | Code Style | C/C++ | Spaces | Befor ‘*’ in declarations, After ‘*’ in declarations.
https://blog.jetbrains.com/clion/2018/09/clion-2018-3-eap-remote-dev-unit-testing-performance-new-actions/?replytocom=73475
CC-MAIN-2019-47
refinedweb
3,065
63.9
Convert GMT to IST C:\unique>java GMTtoIST GMT Time: 8/4/07 9:49 AM IST... Convert GMT to IST In this section, you will learn to convert a GMT to IST format Java get GMT Time Java get GMT Time In this section, you will study how to obtain the GMT time. GMT.... The following example helps you to obtain the IST and GMT time on the console. The method Convert Date to GMT Convert Date to GMT In this section, you will learn to convert a date into the GMT format. The GMT stands for Greenwich Mean Time Convert PST Convert GMT to PST In this section, you will learn to convert a GMT to PST format. The GMT... of program: This example helps you in converting a GMT time to PST time java conversion java conversion how do i convert String date="Aug 31, 2012 19:23:17.907339000 IST" to long value Java Conversion to convert a GMT to CST format. The GMT stands for Greenwich Mean Time and CST stands...Java Conversion  ...() method to get time/date as long return type. Convert Date String to Date Conversion - Java Beginners )); For read more information : to Date Conversion Hi , I am retreiving time stamp of a file.... But I dont want the date/time field of access database to be changed to text Java Date conversion - Date Calendar Java Date conversion How do I convert 'Mon Mar 28 00:00:00 IST 1983' which is a java.util.Date or String to yyyy/MM/dd date format in sql Java Time Zone Example a java program which will take two Time Zone IDs as its argument and then convert... Java Time Zone Example  ... have provided two command line arguments as IST and GMT. C:\DateExample> Type Conversion - Java Beginners Type Conversion Hai, rajanikanth, Please explain how to convert from integer value to a string value .In a database operation i want to convert... for conversion how to convert time in milliseconds in to hours - Java Beginners how to convert time in milliseconds in to hours hello, can anyone tell me how i can convert the time in milliseconds into hours or to display it in seconds in java PDF to Word Conversion - Java Beginners PDF to Word Conversion Hello, Can we convert a PDF document to Microsoft word document thru Java. If its not possible in Java, is it possible in any other language C GMT Time C GMT Time In this section, you will study how to get the gmt time in C. GMT stands for Greenwich Mean Time. In the given example, the time() function determines Convert Time to Seconds Convert Time to Seconds In this section, you will learn to convert Time to seconds. An hour has...: This example helps you in converting a Time to seconds. Here, first of all we have HSSFCell to String type conversion HSSFCell to String type conversion Hello, Can anyone help me convert HSSFCell type to string. There is a solution in the following URL...:// String to Date ; In this example we are going to convert String into date. In java date... class of JDK 1.1 is used to convert between dates and time fields... Standard Time In this example we are going to convert string into date. We Casting (Type Conversion) are there in java. Some circumstances requires automatic type conversion, while in other cases... Java performs automatic type conversion when the type of the expression... Casting (Type Conversion)   Convert Time to Milliseconds Convert Time to Milliseconds In this section, you will learn to convert Time... thousand part of a second i.e. an unit for measuring the time.  time time how to find the current system time between the user login and logout using java Convert Date to Milliseconds . The Date() constructor represents the current date (time) in GMT... Convert Date to Milliseconds In this section, you will learn to convert a date How to convert date to time in PHP? How to convert date to time in PHP? Hi, programmer. The PHP... Time (GMT). This number is handy for generating unique and random numbers... and time. The PHP "time()" function is used to get the current Unix timestamp Java Conversion Convert String to Date C:\convert\rajesh\completed>java StringToTimeExample The date and Time: Thu... Convert String to Date In this example we are going to convert string into date We hexadecimal conversion java compilation - UML hexadecimal conversion java compilation write a simple program..., Please visit the following links: Miles To Kilometers program in java Convert Miles To Kilometers program in java Write a program... places. You will need to write a separate method to convert a single distance.... Extend your program to support conversion from kilometres to miles. Use an extra conversion - Java Beginners Java : String Case Conversion Java : String Case Conversion In this section we will discuss how to convert a String from one case into another case. Upper to Lower case Conversion : By using toLowerCase() method you can convert any upper case char/String Convert Char To Byte Convert Char To Byte This section illustrate the conversion from char to Byte. Here, we are going to convert a char type variable into byte type  time conversion - Date Calendar time conversion hoe to add time in php like 01:30:00 and 00:45:20 and 02:50:40 How to convert into to String in Java? How to convert into to String in Java? Hi, How to convert into to String in Java? Thanks Convert String into long in java Convert String into long in java In this section you will learn about conversion of numeric type String data into long in java. Converting string to long is similar to converting string to int in java, if you convert string to integer convert to decimal convert to decimal f42a4 convert to decimal by using java Convert Date To Calendar to represent a time in milliseconds after January 1, 1970 00:00:00 GMT. ... Convert Date To Calendar  ... into Calendar. Here we are using format method to convert date into string.  time to int convert date time to int convert date time to int Convert InputStream to ByteArray Convert InputStream to ByteArray Here we will learn the conversion of an input stream into a byte array. To convert the InputStream java util date - Time Zone throwing illegal argument exception :57:52 IST 2011"; Date d2 = new Date(timestamp2); System.out.println(d2.toString()); The date object is not getting created for IST time zone. Java...java util date - Time Zone throwing illegal argument exception   get absolute time java get absolute time java How to get absolute time in java Convert Double To String Convert Double To String  ...; This section learns you the conversion of double into string. The following program... a variable of double type and convert it into the string form by using toString Convert Array to Vector Convert Array to Vector In this section, you will learn to convert an Array to Vector...:\unique>java ArrToVector Tamana Aggrawal Mon Jul 30 Java program - convert words into numbers? Java program - convert words into numbers? convert words into numbers? had no answer sir java program to convert decimal in words java program to convert decimal in words write a java program to convert a decimal no. in words.Ex: give input as 12 output must be twelve Convert Inputstream to ByteArrayInputStream Convert Inputstream to ByteArrayInputStream In this example we are going to convert.... Then convert this input stream into string and then string into byte by using Java run time polymorphism Java run time polymorphism What is run-time polymorphism or dynamic method dispatch Convert String to Calendar Convert String to Calendar In this section, you will learn to convert the string... through some Java methods and APIs. Your given date is taken as a string Convert Date to Long Convert Date to Long In this section you will learn to convert the date... to convert a date type into a long type. Description of program Example program to get all the available time zones to get all the available time zones using java program. This example is very simple java code that will list all the available time zones. We have used... Example program to get all the available time zones currency conversion currency conversion hi frds.. I wan jsp code to convert currency in different formats??... if u know plz plz plz post it Please visit the following link: convert .txt file in .csv format - Java Beginners convert .txt file in .csv format Dear all, I hope you are doing good. I am looking to convert .txt file in .csv format. The contents might have.... At the same time, I also want the stored name:value pairs should be exported to .csv java time - Java Beginners java time Hi, Iam created a desktop login application using swings. pls observe the following code: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.*; class LoginDemo{ JButton Convert Inputstream to OutputStream Convert Inputstream to OutputStream  ... to convert an InputStream to OutputStream. Here we are trying to make understand the conversion of an input stream into an output stream Convert a String into an Integer Data convert, String to Float, String to Double. Java API provide static method...Convert a String into an Integer Data In this section you will learn to convert a string type of data to integer type data. Converting string to integer Time Table in Java Time Table in Java Hi, Deepak i am developing a time table for a school on java,but i am confuse how to start so please give me idea about To convert Speech to Text in java To convert Speech to Text in java package abc; import javax.speech.*; import javax.speech.recognition.*; import java.io.FileReader; import java.util.Locale; public class HelloWorld extends ResultAdapter { static Recognizer Convert To Java Program - Java Beginners Convert To Java Program Can anyone convert this C program codes to Java codes,please...thanks! #include int array[20]; int dcn; int cntr=0; void add(); void del(); void insert(); void display(); void exit(); void Formatting a Message Containing a Time PM and UTC is 5:30:00 AM The time is 3:36:55 PM GMT+05:30 and UTC is 5:30:00 AM GMT+05:30 The time is 3:36:55 PM GMT+05:30 and UTC is 5:30:00 AM GMT+05:30 The time is 15:36:55 and UTC is 05:30:00 javascript conversion javascript conversion how to convert war file into dll file Class File to .java File - Java Beginners Convert Class File to .java File Sir, How To Convert .class file to .java File. Please Help me Use cavaj software ,which is freeware, to convert .class to .java Use jd-gui to convert ur .class to .java
http://www.roseindia.net/tutorialhelp/comment/84861
CC-MAIN-2013-48
refinedweb
1,824
62.27
LV What is this application? A tool to assist in writing tcl code? A tool to assist in generating tcl code? A tool to browse tcl code? I'm trying to figure out a high level description of what this does.TV In short, what the title page says, making commands by mouse clicks, and only typing the argument values you want to fill in. That's handy for commands with a lot of possible arguments, where you don't want to keep your finger in the manual to type all the right options, of which often you only want to change a few.Also, it's sometimes easier to see all the arguments and function which are available (which you already made) to use them without typos, and without having to type long commands all the time. The main reason for the type of thinking is functional (de) composition, where you make a certain total function by repeated and nested calls of smaller functions. The idea of the command line is that it can also become an aid for that, which by this tool is made possible in a graphical way, by generating blocks based on functions (procedures can be used as functions, if assumed they don't store things) which can graphically be connected together.This is the window which starts to deal with the function (procedures) definition and calling, by clicking for the main part, and which can generate blocks from the commands you formed. I changed the image above, maybe a bit clearer, except it deludes in that here the procedure call which is formed and expected as command itself makes a bwise block. The bottom button 'block' would make a (simpler) block which makes this block when 'fired'.LV Ah - sort of an intelligent syntax knowledgeable editor. I see.TV Well eeh, not exactly, it's more listing the things which make up procedures, and maybe indeed graphically editing what you want, and then generate a command or a block. The idea of functional (de) composition can often be maintained or used pretty far in programming or problem solving, and in fact lisp and many other programming languages consist for a big part of calling function like entities which call other function like entities, so its a valid fairly general application of the mathematical idea. The below procedures generate the window shown here, at least they did for me on windows XP with tcl/tk 8.4.4 .The meaning of the widget elements is as follows:The left upper list Contains all procedures defined in tcl (in the main namespace/interpreter) without all procedures starting with tcl or tk or pkg and a few more (which are defined when tcl is started up), unless you loaded packages, then all procedures from there are also listed.By clicking on a procedure name, its arguments are listed in the right upper list, while also the procedure definition, in correct tcl (but see below) appears in the lower edit window, and the command line contains the name of the procedure.The Form Command line contains a prefixed call to pro_args, which takes its arguments, and produces a command from the options it is presented with, and the tcl procedures' default argument list, such that when the button is pressed, a command is formed in the shortest form possible given the default arguments, which can be executed from the Execute line by pressing the <execute> button when satisfied with the formed command.Each time an argument is double clicked from the argument list, it appears in the form command editable line, with the right braces around it, and with the cursor ready to fill in the parameter value. This can be repeated in any order until all arguments needed are filled in, and after that <Form Command> creates a well-formed tcl command with those arguments.The lower procedure edit window contains the procedure last double clicked on in the upper left procedure list. The double-click simply overrides the contents of the window, regardless of what changes you had made, be sure to <Update Proc> regularly when you edit!Left next to Save Procs Button, an entry can contain a file name, possibly with full path, where all procedures which have been updated with the <Update Proc> during the session will be saved when the button is pressed.The Refresh list updates the procedure list to become up to date.The Update Proc basically sources in (evals) the content from the text window, usually containing a single procedure definition, which at that point becomes the actual tcl procedure definition. While editing, the old procedure stays called.A new procedure can easily be made by editing an old one, by changing name and what else needs change, and pressing <Update Proc>.The code below assumes you loaded bwise first, command: destroy .fto get rid of the old function window, unless you replace the procedure in the 0.34 source, and re-invoke the procedure to set up the procedure list window by procs_window proc procs_window { } { global defaultprocs # The procedures which are listed in this list are not shown if {[info exists defaultprocs] != 1} { set defaultprocs {bgerror history loadvfs unknown} } # get_procvanilla toplevel .f wm title .f "Procedure Window" frame .f.fu ; pack .f.fu -expand n -fill x; # top frame with two scrollable lists listbox .f.fu.l -height 5 -yscroll ".f.fu.s set"; # left list pack .f.fu.l -expand y -fill x -side left scrollbar .f.fu.s -command ".f.fu.l yview" pack .f.fu.s -side left -expand n -fill y listbox .f.fu.lr -height 5 -yscroll ".f.fu.sr set"; # right list pack .f.fu.lr -expand y -fill x -side left scrollbar .f.fu.sr -command ".f.fu.lr yview" pack .f.fu.sr -side left -expand n -fill y frame .f.fe ; pack .f.fe -expand n -fill x ; # Entries proc_entry fargs {set fcom [pro_args [lindex $fcom 0] $fargs]} "Form Command" proc_entry fcom {} Execute frame .f.ft ; pack .f.ft -expand y -fill both ; # Text area pack .f.ft -expand y -fill both text .f.ft.t -width 20 -height 4 -wrap none -yscroll ".f.ft.s set";; pack .f.ft.t -expand y -fill both -side left scrollbar .f.ft.s -command ".f.ft.t yview" pack .f.ft.s -side right -expand n -fill y frame .f.f; pack .f.f -expand n -fill x button .f.f.b -text {Update Proc} -command { global procs; set p [.f.ft.t get 0.0 end]; eval $p; set procs([lindex $p 1]) $p } pack .f.f.b -side right bind .f.fu.l <Double-Button-1> { global cf; set cf [selection get]; .f.ft.t del 0.0 end; .f.ft.t insert end "proc $cf \{" .f.fu.lr del 0 end; foreach i [info args $cf] { .f.fu.lr insert end $i } foreach a [info args $cf] { if { [info default $cf $a b] == 1} { .f.ft.t insert end " {$a {$b}}" } { .f.ft.t insert end " {$a}" } } .f.ft.t insert end " \} \{[info body $cf]\} " global fargs fcom set fcom $cf set fargs "pro_args " } button .f.f.b2 -text "Refresh List" -command { set o {}; # Don't list certain procs foreach i [info procs] { if {[string match {tk*} $i] == 0 && [string match {tcl*} $i] == 0 && [string match {pkg_*} $i] == 0 && [string match {auto_*} $i] == 0 && [lsearch $defaultprocs $i] == -1 } { lappend o $i } }; .f.fu.l del 0 end; foreach i [lsort $o] {.f.fu.l insert end $i} }; pack .f.f.b2 -side right entry .f.f.f -width 15 -textvar procsfile pack .f.f.f -side left button .f.f.bs -text {Save Procs} -command { global procsfile procs set o {} foreach i [lsort [array names procs]] { eval append o { $procs($i) } \n } set f [open $procsfile w]; puts $f $o; close $f } pack .f.f.bs -side left bind .f.fu.lr <Double-Button-1> { append fargs " \{" [selection get] " \{" .f.fe.ffargs.e icursor end append fargs "\}\} " # Some time ago this started to be necessary, I don´t know about the backward # compatibility, and I only tested on windows that now again the cursor # remains in the entry, at the right place: focus .f.fe.ffargs.e } bind .f.fu.l <F1> [bind .f.fu.l [bind .f.fu.l ]] .f.f.b2 invoke .f.ft.t insert end "Use refresh list when you made a new procedure.\n" .f.ft.t insert end "Double click a procedure name to make it appear \n" .f.ft.t insert end "in the bottom window.\n\n" .f.ft.t insert end "After editing it, press Update to resource the proc.\n\n" .f.ft.t insert end "There is no extra storage except regular tcl procs,\n" .f.ft.t insert end "loading another proc destroys you edits: \nUPDATE FIRST.\n\n" .f.ft.t insert end "Save button saves EDITED procs, \nsee filebox entry on the left.\n" .f.ft.t insert end "Most Bwise regular windows can be resized." } proc proc_entry {var {command {}} {buttontext Do}} { set w .f.fe.f$var frame $w ; pack $w -expand yes -fill x entry $w.e -textvar $var ; pack $w.e -side left -expand y -fill x if {$command == {}} {set command "eval \$$var"} button $w.b -command $command -text $buttontext pack $w.b -side right -expand n -fill none }In fact, the above 2 procedures can also be used without bwise, by themselves, as long as this one is added: proc pro_args { {p } {ar } } { set o {} set c 0; set maxc -1 foreach a [info args $p] { set m {}; foreach j $ar { if [string match $a [lindex $j 0]] { set m 1 set arr [lindex $j 1] set maxc $c } } if {$m == {}} { if { [info default $p $a b] == 1} { append o " [list $b]" } { append o " {}" } } { append o " [list $arr]" } incr c } set o "$p [lrange $o 0 $maxc]" return $o }When Bwise is not loaded, the number of visible procedures which are shown are limited to these 3 procedures themselves, and any other procedures you add, so that it is like a fresh session, where all procedures you make, for instance by clearing the bottom window, writing a new procedure in it, and pressing <Update Proc> to create it. After that press <Refresh List> to get a list including the new procedure.It seems that the example in Quoting and function arguments works when the procedure is double clicked and executed, though the procedure editor doesn't deal with the first argument right.Putting the the default argument in position for editing is of course on the to-do list, or as an exercise to the reader.More importantly, integration with bwise blocks is on the agenda (DV), and certainly a history, maybe integration with console, and a database of argument values.Manual pages and search possibilities would be nice, and of course I want to make a direct link with bwise blocks, preferably both ways, from tcl function to block decomposition, and vice versa. KPV nice little tool. One suggestion: how about marking all new procedures say in red. By new I mean procedures loaded or altered after running procs_window. TV Thanks.In combination with bwise, I wanted to be able to make a procedure, preferably any procedure into a bwise-block, that is one of those yellow rectangles with short blue lines as pins and a name on a tk canvas, which are held together by tag naming conventions, and can be moved around and connected through wires.I made a function, which takes a procedure as argument, which makes a block of that procedure, with an 'out' pin for the result, and for each argument, a corresponding input pin, named after the arguments: proc proc_toblock {procname} { set c "$procname" foreach i [info args $procname] { append c " \$\{$procname.[list $i]\}" } set ret [eval pro_args newproc "{{f {set $procname.out \[$c\] }} \ {in {[info args $procname]}} {out {out}} \ {x {300}} {y {200}} {name $procname} \ } " ] puts $ret eval $ret foreach i [info args $procname] { uplevel #0 "info default $procname $i $procname.$i" } return $procname }That looks short...After having started bwise, source the procedure, and call it with a self defined (non-tcl builtin) procedure name, for instance proc_toblock newprocA bwise block is created with the name of the proc as name, and with block pin variables (made of blockname.pinname) for each argument of the procedure, where the pin variables are initialized with the proc's default argument values.for the example, using the right or middle mouse pop-up menu on the generated block, and selecting 'date' the following list of block variables is automatically shown by bwise, showing this:
http://wiki.tcl.tk/10344
CC-MAIN-2017-17
refinedweb
2,120
70.23
Event Hubs Pricing Cloud-scale telemetry ingestion from websites, apps and devices - No upfront cost - No termination fees - Pay only for what you use.). Event Hubs, is designed to ingest millions of events per second so you can process and analyse massive amounts of data from connected devices and applications. See what else it does Support and SLA - Free billing and subscription management support - Flexible support plans starting at $29.0/month. Shop for a plan - Guaranteed 99.9% or greater availability. Read the SLA - What are ingress events and how are they billed? An ingress event is a unit of data of 64 KB or less. Each one is a billable event. Larger messages are billed in multiples of 64 KB. For example, 8 KB is billed as one event, but a 96 KB message is billed as two events. Events consumed from an Event Hub, as well as management operations and “control calls” such as checkpoints, are not counted as billable ingress events, but accrue to the throughput unit allowance. - What are throughput units and how are they billed? Throughput units are explicitly selected by the customer, either through the Azure portal or Event Hub management APIs. Throughput units apply to all Event Hubs in a namespace, and each throughput unit). - Up to 84 GB of event storage (sufficient for the default 24-hour retention period). Throughput units are billed hourly, based on the maximum number of units selected during this hour. - How are Event Hub throughput units enforced? If the total ingress throughput or the total ingress event rate across all Event Hubs in a namespace exceeds the aggregate throughput unit allowances, senders will get throttled and receive errors indicating that the ingress quota has been exceeded. If the total egress throughput or the total event egress rate across all Event Hubs in a namespace exceeds the aggregate throughput unit allowances, receivers will get throttled and receive errors indicating that the egress quota has been exceeded. Ingress and egress quotas are enforced separately, so that no sender can cause event consumption to slow down, nor a receiver can prevent events from being sent into Event Hub. Note that the throughput unit selection is independent of the number of Event Hub Partitions (sometimes referred to as shards in similar systems). While each Partition offers a maximum throughput of 1 MB per second, 1,000 events per second ingress, and 2 MB per second egress, there is no fixed charge for the partitions themselves. The charge is for the aggregate throughput units on all Event Hubs in a namespace. With this, customers can create enough Partitions to support the anticipated maximum load for their systems, without incurring any Throughput Unit charges until the Event load on the system actually requires higher throughput numbers, and without having to change the structure and architecture of their systems as the load on the system increases. Example: Suppose you chose 8 throughput unit on a namespace and create a single Event Hub with 32 partitions. If all partitions in this Event Hub see even load, each partition gets approximately 0.25 MB/s ingress throughput for a total aggregate throughput of 8 MB/s. If a single partition sees a usage spike to 1 MB/s, while 8 other partitions only see half their peak load (0.125 MB/s), no throttling will occur. However, if the single partition spiked beyond 1 MB/s, it will get throttled due to the per-partition limit, even if the aggregate throughput of all partitions is below 8 MB/s. - Is there a limit on the number of throughput units that can be selected? Yes. Basic and Standard tier Namespaces can have a maximum of 20 Throughput Units.. - What is the maximum retention period? We provide a maximum of a 7-day retention period upon general availability. Note that Event Hubs are not intended as a permanent data store. Retention periods > 24 hours are intended for scenarios where it is convenient to replay an event stream into the same systems, to for example train or verify a new machine learning model on existing data. - Is there a charge for retaining Event Hub events for more than 24 hours? In many cases, yes. If the size of the total number. - How is Event Hub storage size calculated and charged? The total size of all stored events, including any internal overhead for event headers or on disk storage structures in all Event Hubs in a namespace daily storage allowance, the excess storage is billed using Azure blob storage rates (at the Locally Redundant Storage rate). - Do Brokered Connections charges apply to Event Hubs? There are no connection charges for sending events using HTTP, regardless of the number of sending systems/devices. AMQP connections are metered, but the first 100 concurrent connections are free for every Basic Event Hubs namespace, and the first 1,000 concurrent connections per subscription are free for Standard Event Hubs. These allowances cover most receive scenarios and many service to service scenarios. Brokered Connections charges usually only become significant if you plan to use AMQP on a large number of clients, i.e. to achieve more efficient event streaming or to enable bi-directional communication (Internet of Things Command & Control scenarios). Please refer to the Service Bus Connections pricing information for details on what constitutes a Brokered Connection and how they are metered. - How is Event Hubs Archive billed? Event Hubs Archive is enabled when any Event Hub in the namespace has the Archive feature enabled. Archive is billed hourly per purchased Throughput Unit. As the Throughput Unit count is increased or decreased, Event Hubs Archive billing will reflect these changes in whole hour increments. - How does Event Hubs Archive affect my egress from Event Hubs? Event Hubs Archive does not impact egress rates for Event Hubs Throughput Units. You can still read at the full Throughput Unit rate of 2000 events per second/2 MBps per Throughput Unit. - How do storage charges apply for the storage account I select for Event Hubs Archive? Event Hubs Archives uses a storage account you provide on a schedule you provide. Because this is your storage account any usage charges for this storage account will be billed to your Azure subscription. The shorter your Archive Window the more frequent storage transactions will occur.
https://azure.microsoft.com/en-gb/pricing/details/event-hubs/
CC-MAIN-2017-13
refinedweb
1,056
62.17
Variables We can create a new Python variable by assigning a value to a label, using the = assignment operator. In this example we assign a string with the value “Roger” to the name label: name = "Roger" Here’s an example with a number: age = 8 A variable name can be composed by characters, numbers, the _ underscore character. It can’t start with a number. These are all valid variable names: name1 AGE aGE a11111 my_name _name These are invalid variable names: 123 test! name% Other than that, anything is valid unless it’s a Python keyword. There are some keywords like for, if, while, import and more. There’s no need to memorize them, as Python will alert you if you use one of those as a variable, and you will gradually recognize them as part of the Python programming language syntax. Expressions and statements We can expression any sort of code that returns a value. For example 1 + 1 "Roger" A statement on the other hand is an operation on a value, for example these are 2 statements: name = "Roger" print(name) A program is formed by a series of statements. Each statement is put on its own line, but you can use a semicolon to have more than one statement on a single line: name = "Roger"; print(name) In a Python program, everything after a hash mark is ignored, and considered a comment: #this is a commented line name = "Roger" # this is an inline comment Indentation Indentation in Python is meaningful. You cannot indent randomly like this: name = "Flavio" print(name) Some other languages do not have meaningful whitespace, but in Python, indentation matters. In this case, if you try to run this program you would get a IndentationError: unexpected indent error, because indenting has a special meaning. Everything indented belongs to a block, like a control statement or conditional block, or a function or class body. We’ll see more about those later on. Download my free Python Handbook More python tutorials: - How to install Pygame Zero on macOS - Python Lists - Python, the `with` statement - Python Recursion - How to use Python map() - Python, how to create a list from a string - How to use Python reduce() - Django in VS Code, fix the error `Unable to import django.db` - Python Polymorphism
https://flaviocopes.com/python-basics/
CC-MAIN-2021-17
refinedweb
384
64.64
Hi all, Before I go forward, I wanted to say this topic is approach from the things I personally know of. So if I skip stuff others are working on please forgive me. I know I cannot speak for naming, janus and the kerberos server. Vince asked me on IM if there were any tests that he could write for the server to start to get up to speed with it. I thought I'd take this opportunity to post to the list the various places where more unit tests or some test refinement is needed. Who am I kidding? Every line of code needs to be tested! I've been a lazy bad boy. Eve Server UnitTests (high priority) ==================================== In the server there are two areas proper that can be tested. First is the SEDA frontend's LDAP protocol provider which has yet to be factored out of old frontend code. Note that we just factored out from what used to be the frontend this entirely new project called SEDA which is a generalized SEDA frontend for any protocol server. The second is the backend code. The Eve backend really is a LDAP namespace JNDI provider however it does not go through the protocol but instead translates JNDI calls to operations on a BTree based database on disk. This covers the server proper. So Vince if you wanted to specifically write test cases for the server code the best place would be the backend code. Vince note that I probably already have some test cases for some of this stuff in the sandbox which I shall be moving into the trunc/core shortly. Here's the JIRA for that: If you would like you can start after I do this in the next couple of days or start this yourself. Some of it will be throw away or saved for use in Merlin wrapper project tests. Once this is done basically any red line of code in clover is fair game for a test I would imagine. SEDA Framework UnitTests (high priority) ======================================== Unit tests can also be written for the SEDA framework that we factored out of the original frontend. There's a good amount of test cases here but we're not even close to 100% and that's where we want to be. Furthermore Trustin will be agressively refactoring SEDA over the next few weeks so these UnitTests may be moot for now. I'd wait until Trustin finishes the UDP and PIPE transports for protocol services. Snickers UnitTests (highest priority) ===================================== Snickers has some really good unit test coverage. Probably the best because this code is the nastiest of all. These unit tests are great with one exception. The use Snacc4J generated protocol message images (called PDUs) to test Snickers which is the library replacing Snacc4J. We really need to make this code load PDU's pregenerated by Snacc4J and saved in files rather than creating them dynamically using Snacc4J. Basically this is the only reason why we have Snacc4J sticking around and I would love to just get it completely out of the picture 100%. There is a JIRA about how this can be done here: Who ever chooses to take up this task I can reassign it to you. Wes was going to try to do it but I don't think he's going to be around much after speaking to him tonight. LDAP Commons (higher priority) ============================== This library is at the heart of everything that is LDAP/X.500. It's common code that is used by clients and by servers. It contains several things like a filter parser, LDAP message stubs (interfaces for operations like AddRequest etcetera) and other useful classes. This code base is in dire need of being tested. Since this code is used by almost everything tests here are the most important because they can propagate bugs to so many dependees. Plus this code is the least tested of all. Ironically its the most stable I guess because I have used it so much already. ---o--- So that's the breakdown on what can be done with testing which is well, quite a lot. It can be daunting now that I think of it but with testing you just do it cuz you really like to see clover light up green :). FYI anyone interested in a getting their hands on our clover license for the directory project let me know I have it in my home directory at the moment. Cheers, Alex P.S. I know I should have tested more than I have - forgive me! Getting better at it. Snickers my last major thing was seriously tested and is close to 100% covered. FYI that was when I got the clover license btw.
http://mail-archives.apache.org/mod_mbox/directory-dev/200409.mbox/%3C1096619888.3358.78.camel@fermi.trunk.joshua-tree.org%3E
CC-MAIN-2016-26
refinedweb
795
79.7
Continuing on from the previous blog entry, The Futility of Commenting Code, I’d like to address the dissenting comment of Sandman, who claims to have only seen the kind of caricature comments I made up in posts about commenting. Well, here goes reality. A Real Example Consider the following real example, which I chose because I knew the source for Apache projects was available online, and suspecting Apache Commons would be less heavily checked than more popular projects. I dove into the e-mail package, because it’s the first one I actually use. I found this example right away: - source for org.apache.commons.mail.ByteArrayDataSource(revision 782475) pieces of which I repeat here: /** * Create a datasource from a String. * * @param data A String. * @param aType A String. * @throws IOException IOException */ public ByteArrayDataSource(String data, String aType) throws IOException { this.type = aType; try { baos = new ByteArrayOutputStream(); // Assumption that the string contains only ASCII // characters! Else just pass in a charset into this // constructor and use it in getBytes(). baos.write(data.getBytes("iso-8859-1")); baos.flush(); baos.close(); } catch (UnsupportedEncodingException uex) { throw new IOException("The Character Encoding is not supported."); } finally { if (baos != null) { baos.close(); } } } I wasn’t talking about API comments, but these display the same problem. This public constructor is documented with “Create a datasource from a String”, but in fact, there are two string parameters, both documented as “a String”. That’s what the delcaration says, so this is exactly the kind of redundant comment I was talking about. Next, consider the one code comment. It starts on the wrong foot, with “Assumption that the string contains only ASCII characters!”. If you look at the method call, data.getBytes("iso-8859-1"), you’ll see that it’s actually more general than documented, in that it’ll work for any ISO-8859-1 characters (aka Latin1). The second part of the comment, “Else just pass in a charset into this constructor and use it in getBytes()” makes no sense, because the bytes are hard coded, and there is no char encoding argument to the constructor. Furthermore, the catch block (with its throw) should just be removed. It’s catching an UnsupportedEncodingException, which extends IOException, then throwing a fresh IOException. It should just be removed, at which point an unsupported encoding throws an unsupported encoding exception; you don’t even need to change the signature, because unsupported encoding exceptions are kinds of I/O exceptions. There are two problems with the code as is. First, the the IOException reports an unhelpful message; the unsupported encoding exception has the info on what went wrong in its message. Second, it’s returning a more general type, making it harder for catchers to do the right thing. You might also consider the fact that the original stack trace is lost a problem. Another instance of (almost) commenting the language is later in the same file: try { int length = 0; byte[] buffer = new byte[ByteArrayDataSource.BUFFER_SIZE]; bis = new BufferedInputStream(aIs); baos = new ByteArrayOutputStream(); osWriter = new BufferedOutputStream(baos); //Write the InputData to OutputStream while ((length = bis.read(buffer)) != -1) { osWriter.write(buffer, 0, length); } osWriter.flush(); osWriter.close(); } ... I’d argue comments like “Write the InputData to OutputStream” are useless, because this is the idiom for buffered writes. Aside on Bad Code Maybe you think you should always buffer streams. In this case, that’s wrong. Both bufferings simply cause twice as many assignments as necessary. Buffering the input stream is useless because you’re already reading into the byte array buffer. Buffering the output stream is useless, because you’re writing to a byte array output stream baos. Furthermore, you don’t need to close or flush a byte array output stream, because both are no-ops (see the ByteArrayOutputStreamjavadoc). Finally, the naming is wonky, because osWriteris not a writer, it’s an output stream. This isn’t an isolated case. Other files in this package have similar problems with doc. Another Example While we’re picking on Apache Commons, I checked out another package I’ve used, fileUpload. public class DiskFileUpload extends FileUploadBase { // ------------------------------------ Data members /** * The factory to use to create new form items. */ private DefaultFileItemFactory fileItemFactory; // ------------------------------------ Constructors That’s the kind of pre-formatted useless stuff I was talking about. We know what a member variable and constructor look like in Java. There weren’t any other code comments in that file. In that same package, the fileupload.ParameterParser class has some, though, and I’m guessing they’re of the kind that others mentioned as “good” comments, such as: ... // Trim leading white spaces while ((i1 < i2) && (Character.isWhitespace(chars[i1]))) { i1++; } ... I’d argue that perhaps a method called trimLeadingWhiteSpace() implemented the same way would be clearer. But if you’re not going to define new methods, I’d say this kind of comment helps. But always verify that the code does what it says it does; don’t take the comment’s word (or method name’s word) for it. I couldn’t leave that file without commenting on their return-only-at-the-end-of-a-function style: String result = null; if (i2 > i1) { result = new String(chars, i1, i2 - i1); } return result; I have no idea why people do it, but as you can see in this case, it just makes the code hard to follow. More Examples I thought only a couple wouldn’t be convincing. So here’s some links and examples: public boolean isFull() { // size() is synchronized return (size() == maxSize()); } Documenting what’s clear from the code. (And nice section divider comments.) // Return the parser we already created (if any) if (parser != null) { return (parser); } ... } catch (RuntimeException e) { // rethrow, after logging log.error(e.getMessage(), e); throw e; } Yes, that’s what return, log, and throw do. public LogFactoryImpl() { super(); initDiagnostics(); // method on this object Yes, it really says “method on this object”. There’s lots more, so I’ll leave finding them as an exercise. It’s Not All Bad There were useful code comments in those packages that explained how the code corresponded to an algorithm in Knuth, or how complex invariants were being preserved in complex loops. I’m really not saying don’t comment code at all. October 19, 2009 at 3:42 pm | A place I worked had a Quality Assurance group, who I’m certain were all failed programmers. There quality assurance was to assure that programs had lots of comments, we didn’t do certain things that had been decided were impossible to maintain and everything was tidy. Unfortunately many couldn’t read the code well and made up for it by requiring lots of comments. October 22, 2009 at 9:03 am | Some of these comments seem like pseudocode. “the function here should do so and so”. It’s been gradually replaced with real code but the pseudocode-comments remain.
https://lingpipe-blog.com/2009/10/19/examples-of-futility-of-commenting-cod/
CC-MAIN-2019-35
refinedweb
1,149
56.25
Weighted average cost of capital Please help with the WACC problems: The Bigelow Company has a cost of equity of 12 percent, a pre-tax cost of debt of 7 percent, and a tax rate of 35 percent. What is the firm's weighted average cost of capital if the debt-equity ratio is .60? 2. Carter & Carter (C&C) is considering a project that requires an initial cash outlay for equipment of $6.3 million. The equipment will be depreciated to a zero book value over the 4-year life of the project. At the end of the project, C&C expects to sell the equipment for $1 million. The project will produce cash inflows of $1.5 million a year for the first 2 years and $2.2 million a year for the following 2 years. C&C has a cost of equity of 12 percent and a pre-tax cost of debt of 8 percent. The debt-equity ratio is .75 and the tax rate is 35 percent. The company has decided that they will accept the project if the project's internal rate of return (IRR) exceeds the firm's weighted average cost of capital (WACC) by 2 percent or more. Should C&C accept this project and why or why not? Solution Summary Excel file contains calculations of weighted average cost of capital and Internal rate of return.
https://brainmass.com/business/capital-budgeting/weighted-average-cost-of-capital-157883
CC-MAIN-2018-13
refinedweb
233
72.56
Provided by: manpages-dev_5.10-1ubuntu1: · shm_atime is set to the current time. · shm_lpid is set to the process-ID of the calling process. · shm_nattch is incremented by one. shmdt():. in the user namespace that governs its IPC namespace. POSIX.1-2001, POSIX.1-2008, SVr4. In SVID 3 (or perhaps earlier), the type of the shmaddr argument was changed from char * into const void *, and the returned type of shmat() from char * into void *. NOTES():, SHMLBA is the same as the system page size.) The implementation places no intrinsic per-process limit on the number of shared memory segments (SHMSEG). EXAMPLES Program source: svshm_string.h The following header file is included by the "reader" and "writer" programs. }; .10 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
https://manpages.ubuntu.com/manpages/impish/en/man2/shmat.2.html
CC-MAIN-2022-27
refinedweb
145
68.57
Professor Windows - January 2001 This is the second of a two-part series of columns on Windows 2000 DNS. The first column appeared last month. In this column, I will focus on integration of Active Directory services in your existing DNS hierarchy, planning for DNS servers, and some zone transfer issues. Integrating AD in Existing DNS Hierarchy When it comes to integrating Active Directory in your existing DNS hierarchy you need to decide whether the Active Directory namespace will overlap your DNS namespace or you will simply join your existing DNS namespace. Overlapping in this context means that you want an Active Directory domain (e.g. microsoft.com) integrated with a DNS domain of the same name (microsoft.com). When there is an overlap, your existing DNS services will either be implemented on Windows NT 4.0 (in which case you should upgrade it to Windows 2000 DNS services) or on a non-Microsoft DNS server (in which case you should upgrade it to Windows 2000 DNS if the non-Microsoft DNS server doesn't support SRV records - and optionally dynamic updates). If non-Microsoft DNS servers in your existing environment cannot be upgraded to Windows 2000 DNS for whatever reason (e.g. hardware requirements can't be met) then you need to add an additional DNS server that does support SRV records (which are required for Active Directory implementation) and dynamic updates (which are not required but highly recommended) and delegate zones to this new server. When there is no overlap and you plan to join your existing DNS namespace, you can delegate a Windows 2000 DNS namespace from your existing DNS namespace. In this scenario, the existing DNS server will become the primary master for the Active Directory namespace. Although not a requirement, the recommendation is that the zone name on your existing DNS server should correspond to the root domain of your Active Directory. This is not a requirement as I've pointed out. In fact, if your existing DNS server supports SRV records and dynamic updates then you don't really need to delegate Active Directory namespace. You can successfully integrate Active Directory with non-Microsoft DNS servers (e.g. BIND 8.2.2). The domain controller will properly register all SRV records with the BIND server. However, I strongly recommend that you use Windows 2000's DNS server because it adds several additional features to the standard RFCs that are not necessarily found in non-Microsoft DNS servers. Features such as integration with WINS, dynamic registration of downlevel clients with the help of Windows 2000 DHCP server, and support for UTF-8 characters to name a few. Planning for DNS servers There are a number of things to consider when planning for DNS servers in your organization. Assuming that the hardware requirements are met, you need to decide how many DNS servers are required? Where will you place the primary and secondary zones? What will be the impact of replication traffic on the network? Would you be implementing DNS on non-Microsoft DNS servers as well? Will the DNS server be a domain controller or a member server? Will the zones be integrated in Active Directory? How many queries do you expect your DNS servers to receive? Answering these questions during the planning phase will help you in designing your DNS services. Depending on the complexity of the routing in your environment, especially when you are dealing with zone transfers over slower links, you should consider placing cache-only DNS servers at remote locations. Even though Windows 2000 DNS supports incremental zone transfers and the resource records are cached on the DNS servers as well as the clients, in larger enterprises increased DNS traffic can have an impact on network performance. For example, if you shorten your DHCP leases, the DNS server will have to perform dynamic updates more frequently, which will generate more traffic. For fault tolerance, consider configuring at least two DNS servers for each zone regardless of the size of the network one as a primary and the other as a secondary server. Ideally, for each subnet you should have at least two Windows 2000 DNS servers that are domain controllers and configure them with Active Directory integrated zones and secure dynamic updates, as shown in Screen 1. If your browser does not support inline frames, click here to view on a separate page. There is a misconception that by default Windows 2000 DNS server is configured for dynamic updates. This is not true. Here's the gotcha! By default Active Directory integrated zones are configured for dynamic updates, but default standard zones are not. Because by default only the Active Directory integrated zones are configured for dynamic updates, you need to manually configure your standard zones for dynamic updates. Capacity Planning One of the best measures you can take to improve DNS server's performance is to add additional memory. When you start DNS service, all the zones are loaded into RAM. This means that adding additional RAM will improve performance when you have a large number of zones and when the clients' records are dynamically updated on more frequent bases. The Windows 2000 Help file states that for each resource record added to the DNS server, an estimated 100 bytes of memory is consumed. Adding the 4 MB of RAM that is consumed when the DNS server is started, you can use these numbers as a guideline when capacity planning your DNS servers. For example, if a DNS server contains four zones, each with 2,600 resource records, the server will require approximately 5 MB of RAM 4 MB for starting the services and 1 MB for the resources records (10,400 x 100 bytes = 1,016 KB, or approximately 1 MB). Please keep in mind that these numbers should be used only as a guideline, your mileage may vary depending on several factors: your server configuration, number of zones, the type of resource records, etc. The DNS development and testing team at Microsoft performed certain tests (documented in the Windows 2000 Help file) that you will find useful in capacity planning your DNS servers. The tests performed on a 400 MHz dual-Pentium II server with 256 MB of RAM and 4 GB of hard disk space revealed that the server was able to handle 900 queries/sec and 100 dynamic updates/sec with the processor utilization of 30 percent. The DNS server was a dedicated server with no additional services running on that machine. Again, your mileage may vary so use these numbers only as a guideline. Here are some other issues that you should consider in large networks. Performance of an Active Directory zone will be slightly lower compared to a standard primary zone because the DNS server will have to write to the Active Directory database instead of a simple text file. Furthermore, if you configure the Active Directory integrated zone for secure dynamic updates, the rate of dynamic update may suffer even more. For small to medium size organizations, the impact may not be significant, but in larger organizations you should monitor your server performance to obtain numbers that more accurately reflect your own environment. Do a search on "DNS server performance counters" in Windows 2000 Help to see a detailed listing of performance counters that you can monitor. Zone Transfer Issues By default, Windows 2000 DNS servers use a fast transfer method and compress data when zone transfers take place between Windows 2000 DNS servers. Non-Microsoft servers (e.g. BIND 4.9.4 or earlier) may not support fast transfers. Therefore, you should ensure that Windows 2000 DNS server is properly configured to operate with these non-Microsoft servers. To configure the zone transfer mode so it won't use fast transfers, enable the Bind Secondaries option, as shown in Screen 2. The default option has BIND secondaries enabled (i.e. the selection box is checked). Windows 2000 DNS Help and Microsoft's white paper on DNS () incorrectly states that by default BIND secondaries option is disabled. If your browser does not support inline frames, click here to view on a separate page. Windows 2000 supports both full zone transfers (AXFR), where the entire zone file is transferred to a secondary DNS server, as well as incremental zone transfers (IXFR), where only the modified records are transferred. In last month's column (Part 1 of this two-part series), I discussed primary, secondary and Active Directory integrated zones. Unlike standard primary zones, Active Directory integrated zones allow you to modify the DNS database on any domain controller. One problem that you may encounter is when various master name servers apply zone changes in different order. For example, lets say domain controller Mars is master for domain controller Jupiter and provides incremental zone transfers. If Mars becomes unavailable and Jupiter ends up requesting an IXFR from another server, the changes will be applied in a different order and the integrity of the database on Jupiter will be questionable. In that situation Jupiter will request an AXFR from the master server. This concludes this two-part series column on DNS planning. Hopefully, the information in these two columns helps you implement DNS successfully on your network and assist you in preparing for your Active Directory installation. When it comes to Active Directory and DNS, there are too many variables and my best advice to you is to cover all your bases and make sure DNS is working like a charm before you install Active Directory. For any questions or feedback, please write to Microsoft TechNet at mailto: technet@microsoft.com.
https://technet.microsoft.com/en-us/library/bb877972.aspx
CC-MAIN-2015-14
refinedweb
1,605
50.36
my code is giving me this error and I can't for the life of me figure out why it's telling me "NameError: name 'Button' is not defined." In Tkinter I thought Button was supposed to add a button? import Tkinter gameConsole = Tkinter.Tk() #code to add widgets will go below #creates the "number 1" Button b1 = Button(win,text="One") gameConsole.wm_title("Console") gameConsole.mainloop() A few options available to source the namespace: from Tkinter import Button Import the specific class. import Tkinter -> b1 = Tkinter.Button(win,text="One") Specify the the namespace inline. from Tkinter import * Imports everything from the module.
https://codedump.io/share/OkfjafHtUNIj/1/why-is-my-code-returning-quotname-39button39-is-not-definedquot
CC-MAIN-2017-17
refinedweb
104
51.44
Plastic SCM – DVCS at Enterprise Level DVCS was born in the OSS ecosystem and is about to cross the chasm to the enterprise world, unleashing new levels of productivity for the happier-than-ever developers embracing it. While Git is king among DVCS enthusiast, many argue it is still not ready for the enterprise, that’s why some well-known tool developers are racing to complete their enterprise-oriented Git wrappers. In contrast, Plastic SCM was born to fill in the blanks that its OSS counterparts didn’t care about and growing from a .NET based, enterprise oriented foundation that doesn’t share a line with the OSS DVCS its competitors are fighting to shrink wrap. What does it have to offer? Plastic core pillars Plastic SCM has been designed to cover the following cornerstone concepts: - Designed for teams developing commercial software (focused on usability, security and tools). - Very strong branching and merging to enable fast feature and task branches (parallel development ). - Fully distributed version control (DVCS) Provide visual tools. - Integrate with the enterprise infrastructure. - Includes a wide set of the required tools used on a daily basis. Fully distributed is key in the enterprise to enable a wide range of possible working scenarios: from developers working with their local replica (at home, roaming, at the customer site), to distant teams using servers at different locations for speed and flexibility, but always considering the flexibility required by enterprises: distributed when required, and fully centralized when not, with the two models coexisting in harmony. Visual tools to re-think version control operations searching for more clarity, ease of learning and ease of use. The command line is available too, although all common SCM operations are provided in a visually, trying to reduce the learning curve. Considering the focus on the enterprise, it us integrated with the enterprise infrastructure which means supporting LDAP, Active Directory, rely on standard database systems for storage and in-house expertise profitability, and scaling servers up and down depending on the work load A big development effort has been invested not only in the core SCM system but also in the surrounding tools such as diff and merge, so that the full pack is available from the start. Addressing the enterprise DVCS concerns If you look at my previous article on enterprise DVCS, you’ll find the typical concerns that arise when most enterprises consider adopting DVCS. The following table explains how Plastic SCM addresses each of them. Focused on visualization and usability If I had to choose a single feature to describe the visual approach to DVCS of Plastic SCM, I’d definitely go for the Branch Explorer: (Click on the image to enlarge it) Figure 1 It is able to render the evolution of a repository, showing the changesets, branches and merge links and enabling the developer to: - Diff every changeset or branch - Explore the changesets pending to be pulled from remote repositories, and diff them - Run merges - Create branches - Push and pull branches - Switch to different branches or changesets At the end of the day, most of version control operations can be run in a fully visual fashion from the Branch Explorer. A story of trees and branches Back in late 2004, months before the version control wars inside the Linux Kernel, a group of engineers wanted to close a gap: huge development teams had ClearCase, good for branching and merging, while small ones had to live with Subversion. They wanted to come up with an SCM good enough to implement "feature branches" and "task branches" for teams building commercial software products and affordable enough for 20 people teams or less. In November 2006, Barcelona, during the Microsoft Tech Ed Developers event, Plastic SCM 1.0 was first unveiled. It was far from the current 4.1 release, but had a solid foundation: creating branches was fast, easy, efficient, and allowed any team to go for the branch per task pattern. Back then, branches were considered evil by most SCM developers, from OSS to commercial (except ClearCase; not including its UCM version). Plastic SCM has evolved through many releases, focusing on ease of use, graphical user interfaces, and repository visualization (i.e., Branch Explorer), performance and flexibility, while also heavily investing in one of its core values: merging. Making the merge process as straightforward as possible, yet powerful enough to deal with the most complex cases, has been a long term obsession for the Plastic SCM dev team. A .NET background Plastic SCM, as a whole, is written in a variety of languages ranging from C++ to Java, including C# and shell scripts. Nevertheless, the core of the system is written in C#. At first, the C# choice can seem counter-intuitive for version control software, which sits deep in the developer’s tool backbone. Most of the version control packages out there are written in C/C++ for maximum performance and multi-platform support. We decided to use C# for its increased productivity, code simplicity, and ease of learning. It paid off: not only is Plastic SCM is able to consistently outperform even the fastest C written version control systems, but the team was able to evolve the product at a pace hard to achieve with lower level languages. Therefore, .NET was key for Microsoft environments while Mono enables clients and servers to run on Mac OS X and Linux. At the end of the day, design is a bigger performance driver than programming language alone. Specific tools for .NET developers While Plastic SCM targets many environments, it is clear we’ve put in special effort to target the .NET developers using Visual Studio. All the operations Plastic SCM can do are available within the VStudio IDE, including the latest VS2012 (Figure 2 shows Branch Explorer running within the latest VS in black theme). (Click on the image to enlarge it) Figure 2.Branch Explorer running inside VS2012 in black theme Pushing and pulling branches, synchronizing entire repositories, running complex merges, browsing repositories, annotating files, diffing changes, and more are operations doable from the VStudio interface. It is important to highlight the Visual Studio Add-in is able to track files moved across different projects, which is not supported by the API and is solved using the "transparent SCM" capability of Plastic SCM. One of the most cutting edge features the team is working on is available for Visual Studio users only: the "method history": 90% of times a developer browses the history of a file, he’s really looking for an specific method. Method history parses the C# code across the history of a file, looking for the requested method and displaying how it evolved through time. Transparent SCM If you’re working with Visual Studio, Plastic SCM can deal with files moved across different projects, something out of the scope of VS API. We are able to handle this scenario thanks to the "transparent SCM," an initiative we focused on to make common version control operations as unobtrusive as possible. The goal was to focus on coding, forget about everything else, and let the SCM figure out what you did. You moved a file? Ok, no problem: it will compare your current workspace status against the previous saved one and find modified, added or deleted files. Easy so far, but what about the files being moved? The algorithm for move detection is quite simple: take all the "potential adds" and all the "potential deletes" and try to match them somehow, if they do match; you have a move. Let’s now go to the "match somehow." We use the following technique: for each pair we compare the content using the diff algorithm but looking for a similarity percentage factor instead of differences. Are they similar enough? Then they’re the same file and we have a move operation. This is extremely effective for refactors. Even if you don’t have a plugin, or if your IDE doesn’t track moved files, like VS, Plastic SCM will be able to track what you’ve been doing and make your day a little bit easier. It is extremely interesting during the refactor process. If you move a class to a different namespace or directory, the similarity factor will be your friend. Now, one of the clear advantages here is the ability to track directories too: if you move src/kernel into src/render many SCMs out there will produce a list of moves containing each file inside src/kernel. We tweaked the algorithm to be able to detect directory moves too, which is quite convenient in a case like this. Instead of hundreds of files moved, you just get the right directory move. It is true even when you have made changes inside the directory (more renames, added and so on) since it also used a modified similarity factor, this time based on directory operations. (Click on the image to enlarge it) Figure 3 The "transparent scm" is based on the Xdiff/Xmerge foundation, which is able to detect moved or modified code inside a file. (Click on the image to enlarge it) Figure 4 Method-history Here’s the deal: 95% of the time you look to the history of a given file you’re just looking for the history of a given method in a class. But since we didn’t have a better tool, we had to go through the entire file history and find our method there. If we combine traditional version control with programming language parsing technology, we can solve the problem. Here is what you get: (Click on the image to enlarge it) Figure 5 In order to "show the history of a given file", Plastic SCM parses each revision of the file, looks for the method, and shows only the piece of code where the method is. (Click on the image to enlarge it) Figure 6 Conclusion Enterprise is the next frontier of Distributed Version Control. Plastic SCM is positioning itself as the only system specifically designed with commercial teams in mind, with ease of use, flexibility, and graphical interfaces built on top of a high performance core as key differentiators.. I still don't get... by Augusto Rodriguez The only benefit I can see compared to git, is that it can handle big files (does anyone have a 1TB source code file?). I understand that this might be useful to version documents or other assets (images in high definition), but there are other, very good alternatives for
http://www.infoq.com/articles/PlasticSCM
CC-MAIN-2014-52
refinedweb
1,752
56.08
This is a document with tips and usage details about Jython that I've come across. I intend to document handy features of Python as well as some clever inter-op facilities provided by Jython. I'm going to assume you're not a complete beginner to Java and Python languages. If you find anything off or have a suggestion to add, please do write to me. Thanks! Logging and Printing¶ When using Apache's log4j, we can get an instance of a Logger using the API just as we would in Java: >>> from org.apache.log4j import Logger >>> log = Logger.getLogger('jython_script') When getting a Logger instance for a module that is imported, a logger with a category specific to that module can be obtained using the following code: log = Logger.getLogger(__name__) The __name__ name is a variable containing the current module's name as a string. Note that __name__ is set to the string '__main__' if the module is run as a script and not imported from another script. This should be kept in mind when using the above code. The standard printing functions of Java can be imported into Python and used directly in the following way: >>> from java.lang import System >>> System.out.println('Hola') Hola >>> System.err.println('Hello there') Hello there >>> System.out.print('Hola\n') Hola However, it's usually more convenient to use Python's print 'Hello world!' Here's a table illustrating the print* functions: Bean Properties¶ Jython can implicitly call the .get* and .set* methods that are widely used in Java classes to get and set the values of instance attributes. Here's an illustration of how this inter-op works: Of course, when such .get* and .set* methods are not available, this falls back gracefully to trying get/set the property values directly, just as Java would treat those statements. Strings¶ Strings in Java (i.e., objects of type java.lang.String) are converted to unicode objects when passed in to Python world. Whereas str and unicode objects in Python are converted to java.lang.String instances when passed in to Java world. This conversion is seamless and we usually don't have to worry about it. However, if needed, we can explicitly create an instance of java.lang.String from a unicode object in Python: >>> from java.lang import String >>> greeting = String('Hello') >>> greeting Hello >>> type(greeting) <type 'java.lang.String'> String formatting using % operator in Python cannot be applied to Java String objects. They have to converted to str or unicode first. Maps as Dictionaries¶ For the purposes of the following examples, let's work with the following Map: java.util.Map<String, Integer> data = new java.util.HashMap<>(); data.put("a", 1); data.put("b", 2); data.put("c", 3); Maps support the getitem syntax very well so it is usually convenient to think of them as python-style dictionaries. Here's an example: >>> print data['a'] # data.get("a") 1 >>> print data['b'] # data.get("b") 2 >>> data['d'] = 4 # data.put("d", 4) >>> data['d'] # data.get("d") 4 >>> len(data) # data.size() 4 >>> 'c' in data # data.containsKey("c") True >>> del data['c'] # data.remove("c") >>> 'c' in data # data.containsKey("c") False >>> data {a=1, b=2, d=4} >>> len(data) # data.size() 3 Although this resembles the usage of a traditional python dictionary, the methods you'd expect in a dictionary are not all available. This is a Map object after all and it has the methods of the Map class. However, it is easy to get see the parallels among some of the most used methods. The dict builtin can be called on the Map object to get a python-style dictionary, if needed. Additionally, just like a python dictionary, calling list (or set) on the Map object gives a list (or set) of the keys in the Map. Using for loops to iterate over Maps yields the keys in the Map, which is consistent with how for loops work with python dictionaries. for key in data: print key, data[key] Prints the following: a 1 b 2 d 4 In python, the .items method returns each entry as a tuple which lets us write the for loop like the following: # !!! Only works if `data` is a python-style dictionary, not if it is a `Map`. for key, value in data.items(): print key, value But unfortunately, since Map doesn't have the .items method, this is not possible. However, we can use the .entrySet method to construct something slightly similar. for entry in data.entrySet(): print entry.key, entry.value To iterate over the values of a Map, since the method is called .values in both dict and Map, the same piece of code would work with any object. for value in data.values(): print value Empty Map objects are treated as False in boolean contexts, just as with python's dictionaries. Collections¶ The two main collection types in Python are list and set. The equivalents in java are the interfaces List and Set. Let's prepare some data for our examples. java.util.List<String> planets = new java.util.ArrayList<>(); planets.add("Mercury"); planets.add("Venus"); planets.add("Earth"); java.util.Set<String> colors = new java.util.HashSet<>(); colors.add("White"); colors.add("Black"); colors.add("Red"); colors.add("Green"); colors.add("Blue"); The getitem syntax can be used with Lists seamlessly: >>> planets[0] u'Mercury' >>> planets[1] u'Venus' The slicing syntax, returns Lists of the same type, not python-style lists. >>> planets[:2] [Mercury, Venus] >>> type(_) # `_` is a variable set to the return value of last expression. <type 'java.util.ArrayList'> >>> planets[::-1] [Earth, Venus, Mercury] >>> type(_) <type 'java.util.ArrayList'> However, the getitem syntax is not supported for Sets as it doesn't make sense there since Sets are unordered collections. But the operator support available for sets in python are available with Java Set objects as well. >>> 'Red' in colors True >>> len(colors) 5 The for loop can be used on any Collection type objects to iterate over the object's contents. >>> for x in planets: ... print x ... Mercury Venus Earth >>> for x in enumerate(planets): ... print x ... (0, u'Mercury') (1, u'Venus') (2, u'Earth') Here's equivalents for some of the methods available in Java's Collections and Python's collection types. Empty Collections are treated as False in boolean contexts, just as with python's collections. Java Arrays¶ Just as Java's List is mirrored in Python with list, Java's arrays are mirrored using the array structure available in Jython's array module. That official documentation is quite exhaustive on this topic, so I suggest going over it to get an idea of handling arrays in Jython. The Iteration Protocol¶ Java's Iterator style iteration is supported by Jython's for statements. For example, consider the following Java Iterator that's trying to emulate a small fraction of Python's range function: package ssk.experiments; import java.util.Iterator; public class RangeIterator implements Iterator<Integer> { private Integer current = 0, max; public RangeIterator(int max) { this.max = max; } @Override public boolean hasNext() { return current < max; } @Override public Integer next() { return current++; } } Since classes are instantiated without a new keyword in Python, combined with the fact that Jython's for statement supports Java's Iterators, we can use the above in the following way: from ssk.experiments import RangeIterator for n in RangeIterator(5): print n This gives the following output: 0 1 2 3 4 Since Jython's for statement supports iterating over Java's Enumeration type, the above same for loop would work with a RangeEnumeration class as defined below: package ssk.experiments; import java.util.Enumeration; public class RangeEnumeration implements Enumeration<Integer> { private Integer current = 0, max; public RangeEnumeration(int max) { this.max = max; } @Override public boolean hasMoreElements() { return current < max; } @Override public Integer nextElement() { return current++; } } Jython seamlessly handles the getting of an instance of an Iterator from a Java Iterable. This is actually how the for statement works with the List and Set collections discussed earlier ( Collection is a sub-interface of Iterable). Patching Java Classes¶ In Python, new methods and attributes can be added to existing classes. This comes from the dynamic nature of the programming language and the runtime. The JVM is also a dynamic runtime, but the Java language doesn't allow us to modify existing classes. This is where Jython comes in. Jython lets us add and override methods on existing Java classes. Although this is seldom needed, this can illustrate the extent of Jython's integration with the JVM. Here's a Java class: package ssk.experiments; import java.util.List; public class Country { private String name; public Country(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } There's nothing fancy with the above class. It's a regular class with one property with a .get and .set methods. Now, let's add a new method to this class. from ssk.experiments import Country def upcase(self): self.name = self.name.upper() Country.upcase = upcase # Create a `Country` object and call `upper_name` method. largest_country = Country('Russia') largest_country.upcase() print largest_country.name This would print RUSSIA, as expected. Note that this is an advanced feature and should be used with caution. In almost all cases, it is probably a better idea to modify the original Java class definition directly. But when that is not an option, creating a simple Python function that works with these objects should be considered. Modifying existing classes should only be used as a last resort. Operator Overloading¶ One nice and practical case for adding methods on existing Java classes is to leverage Python's support for operator overloading with Java classes. One good example for this is with the BigDecimal class. Mathematical operations on objects of BigDecimal are provided as individual methods like .add, .subtract etc. We can add operator support (in Jython) for these objects by adding the appropriate methods to the BigDecimal class. For instance, here's how we can add support for the + operator: from java.math import BigDecimal BigDecimal.__add__ = lambda self, other: self.add(other) print BigDecimal(42) + BigDecimal(10) This would print 52, as expected. More methods can be added to support all the mathematical operators such as __sub__ for subtraction and __mul__ for multiplication etc. The full list of such method names can be found on the official data model documentation page. Conclusion¶ This is not intended to be an exhaustive guide to what Jython can do. I hoped to give you a taste of how well Jython handles inter-op with Java and hopefully I've helped you write better Python - Java inter-op code. Thank you and any suggestions and feedback are very welcome. View comments at
https://sharats.me/posts/jython-pillow-guide/
CC-MAIN-2020-10
refinedweb
1,813
58.58
Hey guys, I'm not entirely new to java, but how it handles jar files puzzles me a bit. I want to be able to back up an already existing jar file (which I have working great), then detect and add all of the class files I have in my program's jar into the other jar, and finally delete a specific folder in the other jar. How may I do this? (This is what I have so far): import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class Patcher { public static void main(String[] args) { File minecraftJar=new File(System.getenv("APPDATA")+"/.minecraft/bin/minecraft.jar"); File backup=new File(System.getenv("APPDATA")+"/.minecraft/bin/minecraft.backup"); File[] test={new File("config.txt")}; try { backup.createNewFile(); copy(minecraftJar,backup); addFiles(minecraftJar,test); } catch (IOException e) { e.printStackTrace(); } } public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } public static void addFiles(File zipFile,File[] files) throws IOException { File tempFile = File.createTempFile(zipFile.getName(), null); tempFile.delete(); boolean renameOk=zipFile.renameTo(tempFile); if (!renameOk) { throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath()); } byte[] buf = new byte[1024]; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile)); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String name = entry.getName(); boolean notInFiles = true; for (File f : files) { if (f.getName().equals(name)) { notInFiles = false; break; } } if (notInFiles) { out.putNextEntry(new ZipEntry(name)); int len; //The line below is where java gives me an EOFException while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } } entry = zin.getNextEntry(); } zin.close(); for (int i = 0; i < files.length; i++) { InputStream in = new FileInputStream(files[i]); out.putNextEntry(new ZipEntry(files[i].getName())); int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.closeEntry(); in.close(); } out.close(); tempFile.delete(); } } Where are you in your project? What does the posted code do? Does it give errors when executed? So far, I've made the backup work. That's what the copy method does. I then looked up how to put files into a jar (Which it mostly just gave me tutorials on how to alter the jar from the command line), which is what the addFiles method is (but this doesn't work, it throws an EOFException at line 73, so I need to learn how to 1)Detect all of the files in my jar that I want to add 2)copy those files into the other jar and 2)Delete the folder in the other jar So the "my jar" is the R/O source and the "other jar" is the one being changed. Yes I compiled and executed the code and got no exceptions. I started with a jar file and a text file. I end up with three files: a new jar file containing the old jar file's contents plus the text file, a backup of the old jar file and the text file. Oh, I accidentally had a corrupted jar I was trying to insert the file into, thanks. Now I need to know how to detect all of the files in my jar (besides the actual code) and delete a folder in a jar Since you are copying all the files from one jar to the other, skip copying those you do not want to be in the output jar. But how do I get the files in my jar? Please explain. Your code currently gets all the files in my jar. Pseudo code begin loop get my jar entry if (to skip this one) continue; // skip copying this entry to other jar write this entry to other jar end loop How would I get the jar though? I know how to find the other jar, but I don't know how to get the jar I'm using. Also, how do I tell if an entry is what I want to copy over? Is there a way to detect if it's in a folder? How would I get the jar though Your program has it hard coded. Why not use the JFileChooser to "get" the name and path to the my jar. I know how to find the other jar Now this is confusing. Earlier I asked about the jars being used. There were two, my jar and the other jar. The other jar was created by copying from my jar and adding a file. Is there now a third jar? Also, how do I tell if an entry is what I want to copy over This is really a hard one to answer. What determines what files you want to copy? That is an question I can not answer. You have to provide that. Is there a way to detect if it's in a folder? Where is this folder? In the my jar? You need to read the API doc for the zip file classes to see what information is available about the contents of a zip file Okay, thanks. That makes it easy =D Now I just need to know how to delete a folder from the other jar (The jar I'm copying files into) Why copy a file if you are going to delete it? Don't copy it. No, the jar already has files/folders inside of it, I'm making a patcher, so I want to be able to delete one of the folders already in it. I understood that there are two jar files being being used. The 'my' was R/O, the 'other' jar was a copy of the 'my' jar. When you copy from the 'my' jar to the 'other'jar do NOT copy the files you do not want in the 'other' jar. If you don't copy the files, you will not have to delete them.
http://www.daniweb.com/software-development/java/threads/374438/help-with-manipulating-files-in-a-jar
CC-MAIN-2014-15
refinedweb
1,039
76.32
{- | Module : Data.Set.BKTree Copyright : (c) Josef Svenningsson 2007-2010 (c) Henning Günter 2007 License : BSD-style Maintainer : josef.svenningsson@gmail.com Stability : Alpha quality. Interface may change without notice. Portability : portable Burk an undirected graph and the Hamming distance between two binary strings. Any euclidean space also has a metric. However, in this module we use int-valued metrics and that's not compatible(..) -- ,null,size,empty ,fromList,singleton ,insert ,member,memberDistance ,delete ,union,unions ,elems,elemsDistance ,closest #ifdef DEBUG ,runTests #endif )where import Data.Set.BKTree.Internal -- -------- -- | Test if the tree is empty. null :: BKTree a -> Bool null (Empty) = True null (Node _ _ _) = False -- | Size of the tree. size :: BKTree a -> Int size (Empty) = 0 size (Node _ s _) = s -- | The empty tree. empty :: BKTree a empty = Empty -- | The tree with a single element singleton :: a -> BKTree a singleton a = Node a 1 M.empty -- | Inserts an element into the tree. If an element is inserted several times -- it will be stored several times. insert :: Metric a => a -> BKTree a -> BKTree a insert a Empty = Node a 1 M.empty insert a (Node b size map) = Node b (size+1) map' where map' = M.insertWith recurse d (Node a tree then only one occurrence will be deleted. delete :: Metric a => a -> BKTree a -> BKTree a delete a Empty = Empty delete a t@(Node b _ map) | d == 0 = unions (M.elems map) | otherwise = Node b sz subtrees where d = distance a b subtrees = M.update (Just . delete a) d map sz = sum (L.map size (M.elems subtrees)) + xs = L.foldl' (flip insert) empty xs -- | Merges several trees unions :: Metric a => [BKTree a] -> BKTree a unions xs = fromList $ concat $ map elems x -- N.B. This code requires QuickCheck 2.0 {- Testing using algebraic specification. The idea is that we have this naive inefficient distance function. But instead of comparing it to our actual implementation we take each clause in the definition and make it into an equation. We also change each occurrence of the name naive to a call to the distance function. naive [] ys = length ys naive xs [] = length xs naive (x:xs) (y:ys) | x == y = naive xs ys naive (x:xs) (y:ys) = 1 + minimum [naive (x:xs) ys ,naive (x:xs) (x:ys) ,naive xs (y:ys)] For example, the third clause becomes: distance (x:xs) (x:ys) == distance xs ys That way we can construct a quickCheck property from it. So, one property for each equation in the naive algorithm. Pretty sweet! Credits go to Koen. -} -- Way too inefficient! -- prop_naive xs ys = distance xs ys == naive xs (ys :: [Int]) prop_naiveEmpty xs = distance [] xs == length xs && distance xs [] == length (xs::[Int]) prop_naiveCons x xs ys = distance (x:xs) (x:ys) == distance xs (ys::[Int]) prop_naiveDiff x y xs ys = x /= y ==> distance (x:xs) (y:ys) == 1 + minimum [distance (x:xs) (ys :: [Int]) ,distance (x:xs) (x:ys) ,distance xs (y:ys)] -- ---------------------------------------------------- -- Semantics of BKTrees. Just a boring list of integers sem tree = L.sort (elems tree) :: [Int] -- For testing functions that transform trees trans f xs = sem (f (fromList xs)) invariant t = inv [] t inv dict Empty = True inv dict (Node a _ imap) = all (\ (d,b) -> distance a b == d) dict && all (\ (d,t) -> inv ((d,a):dict) t) (M.toList imap) -- Tests for individual functions prop_empty n = not (member (n::Int) empty) prop_null xs = null (fromList xs) == Prelude.null (xs :: [Int]) prop_singleton n = elems (fromList [n]) == [n :: Int] prop_fromList xs = sem (fromList xs) == L.sort xs prop_fromListInv xs = invariant (fromList (xs :: [Int])) prop_insert n xs = trans (insert n) xs == L.sort (n:xs) prop_insertInv n xs = invariant (insert n (fromList (xs :: [Int])))_deleteInv n xs = invariant (delete n (fromList (xs :: _unionsInv xss = invariant (unions (map fromList (xss :: [[Int]]))) prop_union xs ys = sem (union (fromList xs) (fromList ys)) == L.sort (xs ++ (ys::[Int])) prop_unionInv xs ys = invariant (union (fromList (xs :: [Int])) (fromList (ys :: [Int]))) -- Error case : 0 [1073741824,0] -- QuickCheck 2.1 finds this easily. -- The above error case hit the limit of Int. -- Maybe I should use Integer after all? prop_closest n xs = -- Some arbitrary level so that we don't hit the limit of Int all (\x -> abs x < 100000)]) prop_sizeEmpty = size empty == 0 prop_sizeFromList xs = size (fromList xs) == length (xs :: [Int]) prop_sizeSucc n xs = size (insert (n::Int) tree) == size tree + 1 where tree = fromList xs prop_sizeDelete n xs = size (delete (n::Int) tree) == size tree - (if n `member` tree then 1 else 0) where tree = fromList xs prop_sizeUnion xs ys = size (union treeXs treeYs) == size treeXs + size treeYs where (treeXs,treeYs) = (fromList xs, fromList (ys :: [Int])) prop_sizeUnions xss = size (unions trees) == sum (map size trees) where trees = map fromList (xss :: [[Int]]) prop_unionsMember xss = all (\x -> member x tree) (concat (xss :: [[Int]])) where tree = unions (map fromList xss) prop_fromListMember xs = all (\x -> member x tree) (xs :: [Int]) where tree = fromList xs -- All the tests data TestCase = forall prop. Testable prop => Tc String prop tests = [Tc "empty" prop_empty ,Tc "null" prop_null ,Tc "singleton" prop_singleton ,Tc "fromList" prop_fromList ,Tc "fromList inv" prop_fromListInv ,Tc "insert" prop_insert ,Tc "insert inv" prop_insertInv ,Tc "member" prop_member ,Tc "memberDistance" prop_memberDistance ,Tc "delete" prop_delete ,Tc "delete inv" prop_deleteInv ,Tc "elems" prop_elems ,Tc "elemsDistance" prop_elemsDistance ,Tc "unions" prop_unions ,Tc "unions inv" prop_unionsInv ,Tc "union" prop_union ,Tc "union inv" prop_unionInv ,Tc "closest" prop_closest ,Tc "size/empty" prop_sizeEmpty ,Tc "size/fromList" prop_sizeFromList ,Tc "size/succ" prop_sizeSucc ,Tc "size/delete" prop_sizeDelete ,Tc "size/union" prop_sizeUnion ,Tc "size/unions" prop_sizeUnions ,Tc "insert/delete" prop_insertDelete ,Tc "fromList/member" prop_fromListMember ,Tc "unions/member" prop_unionsMember ,Tc "naiveEmpty" prop_naiveEmpty ,Tc "naiveCons" prop_naiveCons ,Tc "naiveDiff" prop_naiveDiff ] runTests = mapM_ runTest tests where runTest (Tc s prop) = do printf "%-25s :" s result <- quickCheckResult prop case result of Success _ -> return () GaveUp _ _ -> return () _ -> exitFailure #endif
http://hackage.haskell.org/package/bktrees-0.3/docs/src/Data-Set-BKTree.html
CC-MAIN-2016-40
refinedweb
961
59.64
When you have created a table using pyqt, you may find this table will have a default width. However, this width can not changed when resizing window. To fix this problem, we will tell you how to do in this tutorial. For example, the table with default width likes: When resizing widow, you may find the width of table is not changed. What is table adaptive width? It means the width of table is changed when resizing window. How to set pyqt table adaptive width? It is very simple in pyqt5. Here is an example. First, import some libraries. from PyQt5.QtWidgets import QTableWidget,QTableWidgetItem, QHeaderView Set adaptive width for table hheader = table.horizontalHeader() hheader.setSectionResizeMode(QHeaderView.Stretch) Where table is QTableWidget object. Run this code, you will find the effect: Goodness me, I took my time finding this. Perfect thank you!!
https://www.tutorialexample.com/pyqt-table-set-adaptive-width-to-fit-resized-window-a-beginner-guide-pyqt-tutorial/
CC-MAIN-2021-31
refinedweb
142
70.09
7 Mar 01:24 2005 FAILED LOGIN RYAN vAN GINNEKEN <luck <at> computerking.ca> 2005-03-07 00:24:49 GMT 2005-03-07 00:24:49 GMT I use FreeBSD 4.10 stable and am having some problems logging into MIMP CVS 0.1 is this the correct version ?? as i cannot get cvs to work right now please help. I use BincIMAP bincimap-1.2.6 and have included the output of my test.php as a txt attachment for you to glean what you can from it. Please let me know if i can send you anything else that may help solve this problem. Directly below is the contains of my server.php, conf.php and the output of my horde.log file. Please forgive me if this has been answered before but i have looked in the mailing list archives and the related FAQ's but could not seem to find anything that would help. server.php $servers['imap'] = array( 'name' => 'IMAP Server', 'server' => 'mail1.shoemasters.com', 'protocol' => 'imap', 'port' => 143, 'folders' => '', 'namespace' => '', 'realm' => '', 'maildomain' => 'shoemasters.com', 'preferred' => '' ); conf.php <?php /* CONFIG START. DO NOT CHANGE ANYTHING IN OR AFTER THIS LINE. */ // $Horde: mimp/config/conf.xml,v 1.9 2004/10/26 07:06:42 slusarz Exp $ $conf['user']['allow_folders'] = true; $conf['user']['alternate_login'] = false;(Continue reading)
http://blog.gmane.org/gmane.comp.horde.mimp/month=20050301
CC-MAIN-2014-15
refinedweb
222
69.68
One of the main issues people seem to have been hit by in penta is the save button not appearing when they edit a text field (and then them not realising that the contents haven't been saved). The problem seems to be with the use of this construct from the prototype.js library in the output page: new Form.EventObserver('content_form', function(element, value ) { enable_save_button() } ); This doesn't work ('in all browsers') to detect changes in text fields. For that to work, we need to use a timer instead: new Form.Observer('content_form', 2, function(element, value ) { enable_save_button() } ); I've tested this using a greasemonkey script, in Iceweasel, and it made the save button appear after any text editing. It will waste some CPU polling for changes, but this seems a price worth paying for not encouraging people to lose data. Can someone with access try putting this change into Penta? Thanks, -- Moray P.S. Here's the Greasemonkey script I used for testing: // ==UserScript== // @name Save button fix test // @namespace // @include // ==/UserScript== Form = unsafeWindow['Form']; enable_save_button = unsafeWindow['enable_save_button']; new Form.Observer('content_form', 1, function(element, value ) { enable_save_button() } );
https://lists.debian.org/debconf-team/2011/06/msg00234.html
CC-MAIN-2019-51
refinedweb
189
64.1
Django REST framework has a nice html-based interface that, for every one of your REST views, renders the docstring as an explanation at the top of the page. Those views, they’re class based views, at least the ones I use. I’m making views that ought to be base views for other Django app’s API. We have a bunch of django apps for various data sources that can present their data in more or less the same way. So... I’ve put a decent docstring, explaining the API, in my base views. Only... they didn’t show up in the interface for the subclasses. Apparently docstrings aren’t inherited by subclasses! So I asked a question on stack overflow and promptly got an answer. What I ended up doing was modifying .get_description(), the method Django REST framework uses to grab and render the docstring: import inspect # Fancy standardlibrary Python internal inspection tool. import docutils from django.contrib.admindocs.utils import trim_docstring from django.utils.safestring import mark_safe .... class MyBaseAPIView(...): def get_description(self, html=False): description = self.__doc__ # Our docstring. if description is None: # Try and grab it from our parents. try: description = next( cls.__doc__ for cls in inspect.getmro(type(self)) if cls.__doc__ is not None) except StopIteration: pass description = trim_docstring(description) if html: # Render with restructured text instead of markdown. parts = docutils.core.publish_parts(description, writer_name='html') return mark_safe(parts['fragment']) return description This method is a customization of Django REST framework’s. There are two changes: Hurray for class based views! Because it is an object oriented structure, it is easy to overwrite parts of functionality. And easy to provide methods to actually do so (like the .get_description() I modified).):
http://reinout.vanrees.org/weblog/2012/12/19/docstring-inheritance-djangorestframework.html
CC-MAIN-2014-41
refinedweb
287
60.92
Tech developing Windows applications, as well as OS X and the many flavors of UNIX/Linux. What is Mono? Mono is based on the fact that the C# language and the CLI (Command Language Infrastructure) have been accepted as standards by ECMA. The Mono libraries include .NET compatibility libraries (including ADO.NET, System.Windows.Forms, and ASP.NET) and Mono-specific third-party class libraries. It's also possible to embed Mono's runtime into applications for simplified packaging and shipping. In addition, the Mono project offers an IDE, a debugger, and a documentation browser. How to install Mono Mono is freely available from the project's Web site, with downloads available for Linux (a generic installation, SUSE, and Red Hat), Windows, and OS X. You can download the complete source code and compile it (which is the only choice if your platform isn't supported) or download the appropriate installation package. We'll stick to the installation package route in this article. Once you download the appropriate package for your platform, the installation process varies by operating system. Currently, I have Mono running on Windows XP and SUSE Linux 9.2 machines. The Windows installation is as simple as downloading the installation package and running it on your machine, whereas the other distributions are not as easy. The Linux installations include individual files for the various aspects of the Mono platform. Here is a sample of the parts of Mono available for download for SUSE: - mono-devel-1.0.6-1.ximian.9.1.i586.rpm—Mono core package with C# compiler - mono-core-1.0.6-1.ximian.9.1.i586.rpm—Mono core runtime - mono-data-1.0.6-1.ximian.9.1.i586.rpm—Database core Each file in the list is a RPM (Red Hat Package Manager) file. You may install these files on the Linux box with the rpm command-line tool. For example, you can install the core Mono runtime with the following command: rpm – i mono-core-1.0.6-1.ximian.9.1.i586.rpm After installing Mono, you should add it to your system's path so you can easily issue commands without specifying the complete path. You can do this via the Window's control panel or using the export PATH command on Linux. Tip: If you're experiencing any Mono installation problems at this point, I recommend visiting the Got Mono? Web site for excellent install troubleshooting tips. The Mono toolset Once you install Mono, you may utilize its various tools. Here's a look at some of these tools: - mono—The mono interpreter that allows for the execution of applications without using JIT. This allows you to run applications from the command line. There is no corresponding tool in the Microsoft .NET Framework. - mcs—The C# compiler that accepts all the same command line options that the Microsoft C# compiler (csc.exe) does. - monodies—A tool that allows you to disassemble applications into IL (Intermediate Language). It provides functionality similar to Microsoft's ildasm.exe. Please refer to the Mono documentation for a more complete list of tools, along with a discussion of each command's options. Build a Mono application Now we'll build a simple Mono application to see how to use a few of these tools. The following code prints a sample message to the console: using System; namespace Builder.Samples { public class MonoDemo { public static void Main(string[] args) { Console.WriteLine("Check out TechRepublic.com"); } } } We'll save this simple example as MonoDemo.cs, which may be compiled with Mono's C# compiler: mcsMonoDemo.cs The result of the compilation is the file MonoDemo.exe. The .exe file extension is common on a Windows system, but it is an odd occurrence on a Linux system. Therefore, we'll run our example with this command-line interpreter: mono MonoDemo.exe The great aspect of this example is that we may run the compiled file on a Windows, Linux, Mac OS X, or any platform running Mono or the Windows .NET Framework. This is because the Mono compiler compiles code into an intermediary form known as IL. The Microsoft C# compiler does the same thing. However, Mono doesn't have a complete implementation of the .NET class libraries; it does have additional Mono-specific libraries. Consequently, not all applications developed with Mono can be run in the Microsoft .NET Framework and vice versa. You will have to take this into consideration during development by understanding the target platforms and future demands for compatibility. Likewise, you should visit the Mono site frequently to stay up-to-date with the project since new features (like class libraries) are continuously being added. This is true on the Microsoft side as well. Concerns While I love the ability to transfer my C# knowledge from the Windows platform to the many flavors of Linux and other platforms, I am hesitant about full-blown .NET development on anything but Windows. Basically, Microsoft donated the C# language as well as the CLI to the community but other technologies like ADO.NET and ASP.NET were not submitted. This makes me wonder if Microsoft will make a move to squash the ASP.NET and ADO.NET engines currently available in Mono. Applications hosted on Web servers other than IIS and Windows hurt Microsoft's bottom line. This may be my paranoia, but it is something I will keep an eye on. One last issue is the lack of support for non-C# languages; this leaves VB.NET programmers in the cold. Dive in The Mono project is an impressive feat accomplished within the open source framework. It supports many features of the .NET Framework, with 2.0 features currently supported or in the process of being supported. In addition, Mono's specific libraries for developing Linux-based applications (the gnome interface) are a boost for Linux development. Mono is a good reason for Windows developers to take a peek at Linux..
http://www.techrepublic.com/article/take-the-open-source-development-plunge-with-mono/
CC-MAIN-2017-34
refinedweb
998
58.58
Like C and C++, C# includes support for creating structure types. A structure is an aggregate type that combines members of multiple types into a single new type. As with classes, members of a structure are private by default and must be explicitly made public to grant access to clients. A structure is declared using the struct keyword, as shown here: struct Point { public int x; public int y; } Structures can’t be inherited. struct Point { public int x; public int y; } // Not allowed; can't inherit from a struct. class ThreeDPoint: Point { public int z; } This is in contrast to C++, in which there’s very little real difference between a class and a structure. In C#, structures can inherit from interfaces, but they’re not allowed to inherit from classes or other structures. Unlike instances of classes, structures are never heap-allocated; they’re allocated on the stack. Staying out of the heap makes a structure instance much more efficient at runtime than a class instance in some cases. For example, creating large numbers of temporary structures that are used and discarded within a single method call is more efficient than creating objects from the heap. On the other hand, passing a structure as a parameter in a method call requires a copy of the structure to be created, which is less efficient than passing an object reference. Creating an instance of a structure is just like creating a new class instance, as shown here: Point pt = new Point(); Always use the dot operator to gain access to members of a structure. pt.y = 5; Structures can have member functions in addition to member fields. Structures can also have constructors, but the constructor must have at least one parameter, as shown here: struct Rect { public Rect(Point topLeft, Point bottomRight) { top = topLeft.y; left = topLeft.x; bottom = bottomRight.y; right = bottomRight.x; } // Assumes a normalized rectangle public int Area() { return (bottom - top)*(right - left); } // Rectangle edges int top, bottom, left, right; } Structures aren’t allowed to declare a destructor.
http://etutorials.org/Programming/visual-c-sharp/Part+I+Introducing+Microsoft+Visual+C+.NET/Chapter+2+C+Basics/Structures/
CC-MAIN-2017-22
refinedweb
341
61.46
This week Java 11 was released! It feels like only yesterday that we was saying the same thing about Java 9. This new six monthly release cadence is a big change for the Java community, and a welcome one – Java developers are getting small drops of interesting new features regularly. Java 11 Java 11, like Java 10 before it, has a fairly short list of new features, which is a good thing for us developers as it’s much easier to see what may be interesting and useful to us. From an IntelliJ IDEA point of view, there’s really only one feature that benefited from some extra support in the IDE, and that was JEP 323: Local-Variable Syntax for Lambda Parameters. We’ve already blogged about this in the context of Java 11 support in IntelliJ IDEA 2018.2, but let’s cover it again quickly. When lambda expressions were introduced in Java 8, you could write something like this: The type information is included for the x and y parameters. But you didn’t need to include this type information as it was already known – in this case, the BiConsumer on the left declares these two types with generics. IntelliJ IDEA lets you remove these types if you wish: Java 10 introduced var for local variable types, which we’ll talk about a bit later in this post, and Java 11 took this further to allow var on lambda expression parameters. The main use case for this is when a parameter requires an annotation. Annotations appear next to the type, so prior to Java 11 this would have meant code with an annotation might look something like: In Java 11, we can make this a little shorter using var instead of the parameter types, and IntelliJ IDEA can do this conversion for you. Note that this is suggested when you press Alt+Enter on the type, it’s not flagged as a warning in the code. Java 11: Be aware, the APIs you use may not be there any more As well as new language features, it’s important to understand that Java 11 actually removes features. This step not only affects deprecated features and functionality that wasn’t used much, it also aims to simplify the core of the language by moving some large sections into separate dependencies (e.g. JavaFX), or expecting applications to use external dependencies that were already available (e.g. Java EE). Both the Java EE and CORBA modules have been removed. While CORBA is probably not highly used, many applications do, of course, make use of Java EE. Usually this is in the context of an application server, or some other specific implementation of Java EE, but some applications and libraries make use of small sections of Java EE for specific purposes. For example JAXB is now not in the core language, you’ll need to add a specific dependency on it. There’s more information on possible replacement dependencies on this StackOverflow question. Java 10 Java 10 was released only six months ago, and many of us may not have started using it yet. As a reminder, the main new feature from Java 10 was the introduction of var, which, as we saw above, lets us use var instead of a specific type. This is not introducing dynamic typing into Java, instead it’s continuing a trend of reducing boilerplate in Java, similar to the introduction of the diamond operator which meant we no longer had to declare generic types on both sides of the equals sign. IntelliJ IDEA supports var in a number of ways. Firstly, inspections give you the option of replacing types with var, or var with types. By default the inspection won’t give you a warning about code that can use var (or code that should have an explicit type), but as usual the inspection can be configured according to your team’s style. IntelliJ IDEA can also help you to navigate code that uses var. Holding down Ctrl/⌘ and hovering over var will show the type of the variable. Like any other type, we can click here and navigate to the declaration, or we can use Ctrl+B/⌘B to navigate to the declaration via var. We can also use Quick Documentation (Ctrl+Q/F1) or Quick Definition (Ctrl+Shift+I/⌥Space) on var to see the type. We covered using var in quite a lot of depth in our webinar on IntelliJ IDEA and Java 10. Java 10 also came with a few nice additions to Optional and Collectors, so if you use the Streams API it’s worth having a look at these new methods. Java 9 Last September’s Java 9 release was a big one, and people may be surprised to learn that both 10 and 11 effectively replace 9 – some JDK providers (e.g. Oracle) will not be offering long term support for Java 9 (or Java 10). Teams looking to jump straight from Java 8 to Java 11, skipping out the versions without long term support, still need to understand the changes that came in to Java 9 as obviously they’ll be part of Java 11. We have already covered Java 9 and IntelliJ IDEA a number of times on this blog, and we have a recording of a webinar which covers many Java 9 features that may be interesting to developers. Of course modularity is the most famous feature, but there are lots of other additions, including the new Convenience Factory Methods for Collections. Personally this is my favorite feature from Java 9, and conveniently IntelliJ IDEA inspections can offer to migrate code to use the new methods. A note on migration While the goal of this post has been to show features in IntelliJ IDEA that make working with Java 9, 10, and 11 easier, and not specifically to help developers to migrate their code to these versions, we can’t help but throw in a bit of advice in this area. If you are looking to use Java 11 in the near future, you should start by making sure all of your dependencies are up to date. Many JVM languages, libraries and frameworks had to make big changes to work with Java 9, and yet more to keep up with changes from Java 10 and Java 11. You should be able to update the versions of the libraries you’re using with minimal impact on your own application and be a significant step closer to being able to use the latest version of Java. If you are interested in migrating from Java 8, I wrote a couple of articles on the topic elsewhere, specifically tackling migrating to Java 9 (which will, of course, apply also to Java 11): - Migrating from Java 8 to Java 9 for Oracle’s Java Magazine, using IntelliJ IDEA of course. - Painlessly Migrating to Java Jigsaw Modules – a case study for InfoQ, looking at introducing modularity to your application. Java 11 may only have only just been released, but IntelliJ IDEA already fully supports it, and makes it easier to use the new features in Java 11, 10, and 9. Try it out today! You can download the open source OpenJDK build (provided by Oracle) which is ready for production use now. Please note that I have suggested the OpenJDK build here, as Oracle have changed their license and now produce a commercial and an open source JDK. Please do read this post for more information, it’s very important to understand. Are there plans for proper OpenJFX 11 support? Especially now that JavaFX is not bundled in the JDK 11 anymore. I’m not sure of our plans, but I can tell you I’m doing a demo with OpenJFK next month, so I’ll be able to show what support is there and feed back any ideas for improving it. Thank you, that sounds great! Would definitely love to take a look at it. Where do you plan to release it? It would be nice if you could provide a link. Of course, I’ve managed to port most of the apps I had to openjdk 11 + openjfx, but I feel like it needed more configuration than I’m used to (spoiled by) on IntelliJ Idea. I’ll be giving the demo at Oracle Code One, I’m not sure if/when any videos will be available. But I will definitely be able to write up my experiences in a blog and maybe produce a screencast as well. Will try and have something by the end of the year (no promises, this time of year is busy with conferences and releases). Can you let me know what sort of extra support you were expecting from IntelliJ IDEA? I managed to get my JavaFX app working in IntelliJ IDEA, and I found a lot of the features I wanted worked as expected. What did you need? building and deploying the app as jar doesn’t work anymore take a look at this question: How does Oracle’s new license on Java 11 affect JetBrains and their users? I really don’t think it does affect us as long as we use the OpenJDK version which is totally free. Oracle’s version is based on the OpenJDK with basically commercial support and I guess some extra enterprise commercial features. See also here: Yes, this. IntelliJ IDEA runs on a JetBrains-specific OpenJDK build, and then the JDK that our users develop against is completely up to them. As per the above blog post, my recommendation would be that for Java 11 and onwards, our users should make sure they’re using an OpenJDK build and not the commercial Oracle JDK. yeah, company I work for has decided that for now at least nobody is to install Oracle JVMs. Legal is still trying to figure out if OpenJDK is safe for us to use without infecting our code with the GPL, which is a major concern for both us and our customers. I am just getting into java 11. I am using openjdk and openjfx. My program compiles fine but it will not run. I get the following message: JavaFX runtime components are missing, and are required to run this application Is there a tutorial for setting up a project with Javafx 11? Edit the Run/Debug Configuration and edit the VM Options field by adding the modules you used for your project. Eg: –module-path /home/Smeeagain/Development/Java/javafx-sdk-11/lib –add-modules=javafx.controls,javafx.fxml I’m starting right now in java 11. I’m using OpenJDK and OpenJFX. My program compiles and starts without errors. But when I run Build Artifacts, I get the following error message. Error: Java FX Packager: BUILD FAILED /Users/frankgeissler/Library/Caches/IntelliJIdea2018.2/compile-server/halloweltfx_78a3503b/_temp_/build.xml:3: Problem: failed to create task or type javafx: com.sun.javafx.tools.ant: fileset Cause: The name is undefined. Action: Check the spelling. Action: Check any custom tasks / types have been declared. Action: Check that any / declarations have taken place. No types or tasks have been defined in this namespace yet Total time: 0 seconds I have the same problem as you, Frank. I tried a few things here and there, but nothing really worked. I gave up for now, hoping it’s actually a bug on Idea’s side. It was working fine before with Java 8, 9 and 10. I’ll look into this soon and get back to you I’m working on this problem right now. I will come back to you when I can replicate the problem. If you could point me to some example code that fails, that would be really helpful. Have you checked out these similar issues? There are some fixes and workarounds for those problems. Maybe that can help. It’s really not about the code. I also tried the starting point of a sample JavaFX project with the exactly same results. I simply added the static javafx library under modules -> dependencies. The error I get when building the artifact is: Information:Java FX Packager: [/usr/java/jdk-11/bin/java, -Dant.home=/home/smee/Devel/ideaIU/lib/ant, -classpath, /home/smee/Devel/ideaIU/lib/ant/lib/ant.jar:/home/smee/Devel/ideaIU/lib/ant/lib/ant-launcher.jar:/usr/java/jdk-11/lib/ant-javafx.jar:/usr/java/jdk-11/jre/lib/jfxrt.jar, org.apache.tools.ant.launch.Launcher, -f, /home/smee/.IntelliJIdea2018.2/system/compile-server/testfxone_73734fd0/_temp_/build.xml] Information:Java FX Packager: Buildfile: /home/smee/.IntelliJIdea2018.2/system/compile-server/testfxone_73734fd0/_temp_/build.xml Information:Java FX Packager: [taskdef] Could not load definitions from resource com/sun/javafx/tools/ant/antlib.xml. It could not be found. Information:Java FX Packager: Information:Java FX Packager: build artifact: Information:javac 11 was used to compile java sources Information:10/18/18 12:44 AM – Compilation completed with 2 errors and 0 warnings in 3 s 528 ms Error:Java FX Packager: BUILD FAILED /home/smee/.IntelliJIdea2018.2/system/compile-server/testfxone_73734fd0/_temp_/build.xml:3: Problem: failed to create task or type javafx:com.sun.javafx.tools.ant:fileset Cause: The name is undefined. Action: Check the spelling. Action: Check that any custom tasks/types have been declared. Action: Check that any / declarations have taken place. No types or tasks have been defined in this namespace yet Total time: 0 seconds Error:Java FX Packager: fx:deploy task has failed. Thanks very much for creating the issue with the details in, this has been assigned to someone who should be able to help. Feel free to poke the issue or reply here if the issue isn’t moving fast enough for you. Would be great to provide type hints for local variable types like in kotlin var/val. Always there is sidestepping of IntelliJ IDEA producing jmod artifacts with jmod, or custom runtime artifacts via jlink. As of Java 11 there is no standard JRE only assemblies of reduced custom JRE’s. the JDK is a build and packaging toolset akin to Maven or Gradle which is supported. Announce or confirm interest or disinterest in support for the direction that Java is taking so that I and others can decide if paying for this product is something that we want to continue. I see you’ve found and commented on our issue tracker for this feature request: I can’t comment on what’s on the roadmap, but I will find out what I can. I understand it’s frustrating not having a useful feature like this (I myself wanted this a few months back when I wanted to try out the new JavaFX stuff), I’ll get back to you when I have some more information. Turn on sarcasm. IntelliJ: Hello Community, Java 11 may have just been released, but IntelliJ IDEA already supports it completely. Community: Great, but if I want to build an Artifact, I get the following error: Error: Java FX Packager: BUILD FAILED … IntelliJ: Hello Community, Java 12 may have just been released, but IntelliJ IDEA already supports it completely. Community: Great, but if I want to build an Artifact, I get the following error: Error: Java FX Packager: BUILD FAILED … IntelliJ: Hello Community, Java 13 may have just been released, but IntelliJ IDEA already supports it completely. Community: Great, but if I want to build an Artifact, I get the following error: Error: Java FX Packager: BUILD FAILED … IntelliJ: Hello Community, Java 14 may have just been released, but IntelliJ IDEA already supports it completely. Community: Great, but if I want to build an Artifact, I get the following error: Error: Java FX Packager: BUILD FAILED … Is this the beginning of the end of Java OpenJDK? Will the InteliJ IDE be an IDE like Emabrcadero RAD Studio IDE? Turn off sarcasm. Please see my reply to your earlier comment. Please note that the fastest way to get support for problems with IntelliJ IDEA is to raise an issue in our issue tracker: This is constantly monitored, whereas blog comments are answered on a best-efforts basis. I really like Java 11, the var thing is really really helpful, i am so glad to upgrade all my projects to the newest java 11, i think java will live forever, not like the rumor outside I really like Java 11 too, if it works properly again. Hi Trisha, Every time I google for IntelliJ and Java 11, your name is in Could you expand one of your blog posts or write a new elaborating on what is the ideal configuration for IntelliJ runtime JVM and project JVM? I see a lot around new features that IntelliJ has for Java 11 including var, lambda etc, but nothing about using Java 11 as IDE JVM. Everytime I search on how to switch the runtime JVM, I only recommendations to stick with bundled JVM (although search results are all pre Java 11 release). I have most up-to-date IntelliJ but JVM is still based on OpenJDK 8. I found how to force IDE JVM to OpenJDK 11. So far everything looks fine, but I want to hear if that is the recommended way. On one side, Jetbrains recommends using bundled JVM. On the other side, doesn’t sound right run IDE on Java 8 to build Java 11 apps though. Java 11 sounds very attractive, LTS, var keyword, and Oracle JDK vs OpenJDK interchangeability. Btw, I love your video that you dedicated 1 hour just to talk about var on Java 10, not only what is syntactically correct, but also your focus on what makes sense for code readability. Hi, thanks a lot for your feedback, particularly the nice things you said For now, the recommendation is to stick with the bundled JVM for running IntelliJ IDEA. It appears the reasons are many and complicated (and of course we are working on getting it to work with an updated JVM), and some are to do with writing UI-specific code in Java. There’s absolutely nothing to stop you writing your own code in Java 9, 10, 11 or even 12 in IntelliJ IDEA while the IDE runs on 8. As you’ve probably seen, I myself use much later versions than 8 without any problems.
https://blog.jetbrains.com/idea/2018/09/java-11-and-intellij-idea/?replytocom=453975
CC-MAIN-2019-35
refinedweb
3,072
60.24
getprogname, setprogname -- get or set the program name Standard C Library (libc, -lc) #include <stdlib.h> const char * getprogname(void); void setprogname(const char *progname); The getprogname() and setprogname() functions manipulate the name of the current program. They are used by error-reporting routines to produce consistent output. The getprogname() function returns the name of the program. If the name has not been set yet, it will return NULL. The setprogname() function sets the name of the program to be the last component of the progname argument. Since a pointer to the given string is kept as the program name, it should not be modified for the rest of the program's lifetime. In FreeBSD, the name of the program is set by the start-up code that is run before main(); thus, running setprogname() is not necessary. Programs that desire maximum portability should still call it; on another operating system, these functions may be implemented in a portability library. Calling setprogname() allows the aforementioned library to learn the program name without modifications to the start-up code. err(3), setproctitle(3) These functions first appeared in NetBSD 1.6, and made their way into FreeBSD 4.4. FreeBSD 5.2.1 May 1, 2001 FreeBSD 5.2.1
http://nixdoc.net/man-pages/FreeBSD/man3/setprogname.3.html
CC-MAIN-2019-43
refinedweb
209
56.35
. I'm not aware of any API functions to show previews except for the quick panel preview. You could try something like this that shows the quick panel with one entry (the image from your json file) and previews it, then hides the preview when the quick panel is closed. It is a bit of a hack but should work... class PreviewImageCommand(sublime_plugin.TextCommand): def run(self, edit): # Get the file path from the json file imagepath = '/path/to/image.jpg' self.files = [imagepath] sublime.active_window().show_quick_panel(self.files, lambda s: self.on_done(s), selected_index=0, on_highlight=lambda s: self.show_preview(s) ) def on_done(self, index): sublime.active_window().focus_view( self.view ) def show_preview(self, index): if index >= 0: file_path = self.files[index] sublime.active_window().open_file(file_path, sublime.TRANSIENT) HI thereNowadays,there are mant third party Image SDK which provides comprehensive and powerful APIs for developers to view image, edit, annotate and process variable image and document formats in commonly used modern browsers, such as IE, Chrome, Firefox, and Safari. So you can just google for it.Most of them offer a free trial for new users.So you can just try the free trial to help you out.Hope to help you. Thank you for the quick and helpful reply, jbjornson, the code pointed me to the right direction. For future readers, here's the solution and details: ST3 doesn't really have an "image view" API, it just "opens" it like any other files. And I think that's a good thing. Below is the code, which is for my specific use case. In run(), defaults are set (best practice is to set them in a settings file), where file_path_label specifies the file to be opened in a new view in new row, and common_path specifies the common path of viewed file and file to open. open_new_row() opens the file in new row if there isn't one already. import sublime, sublime_plugin, io, os class ViewLabeledFileCommand(sublime_plugin.TextCommand): def run(self, edit): file_path_label = 'imgurl: ' # label for path to file to open common_path = 'articles' # common path of viewed file and file to open max_files = 1 selection = sublime.Region(0, self.view.size()) text = self.view.substr(selection) buf = io.StringIO(text) sep = os.sep line = buf.readline() files = ] while line: if file_path_label in line: relpath = line.split(': ')[1] rootpath = self.view.file_name().split(sep+common_path+sep)[0] path = os.path.join(rootpath, relpath.strip().strip(sep)) files.append(path) if len(files) >= max_files: break line = buf.readline() self.open_new_row(files) def open_new_row(self, files): window = sublime.active_window() ngroups = window.num_groups() # create new row if there isn't one if ngroups == 1: window.run_command('set_layout', # 2 rows { "rows": [0, 0.5, 1], "cols": [0, 1], "cells": [0,0,1,1],[0,1,1,2]] }) active_group = window.active_group() self.group = active_group other_group = 1 if active_group==0 else 0 window.focus_group(other_group) if len(files) == 1: window.open_file(files[0], sublime.TRANSIENT) else: self.files = files window.show_quick_panel(self.files, self.files, lambda i: self.on_done(i), selected_index=0, on_highlight=lambda i: self.show_preview(i) ) window.focus_group(self.group) window.focus_view(self.view) def on_done(self, index): # doesn't seem to be called sublime.active_window().focus_view(self.view) def show_preview(self, index): if index >= 0: file_path = self.files[index] sublime.active_window().open_file(file_path, sublime.TRANSIENT) I actually wanted to code this in on_load() EventListener instead of TextCommand, based on file type loaded (eg. json, md, etc.) so I don't have to type in a command. But it doesn't work with goto anything search since the file is actually loaded during smart file find, so any continuation of typing in the goto anything panel results in typing in the newly opened file instead. To make it work, I'll either need to disable file preview on goto anything search, or bring focus back to the input panel, both of which doesn't seem to be available. If anyone knows, please reply. thanks.john I didn't review your code but based of your explication of the issue I think you can use something similar to this code: In brief, the on_load event define a setting in the view to tell it must be processed and the on_activated event check this setting (and remove it) and process the view.
https://forum.sublimetext.com/t/image-view-preview-api/12609/2
CC-MAIN-2016-36
refinedweb
716
59.6
Why? Because they can be thousands of times slower than method return values! Can you guess why? First here's an example of what not to do. (from the Patterns & Practices Guidance article) static void ProductExists( string ProductId) { if ( dr.Read(ProductId) ==0 ) // no record found, ask to create { throw( new Exception("Product Not found")); } } This should have been handled with a meaningful method return value (such as 'null' or '-1' for example) and is a bad idea for couple of reasons: - Not being able to find a product is not an exceptional circumstance. The program logic should be able to handle this with a method return value rather than an Exception. I’m sure you can think of other similar cases where Exceptions have been used inappropriately. - Exceptions are excellent when used correctly but they come with a price - execution overhead. The CLR is much, much slower to process Exceptions than it is to process normal program flow and method return values. What actually happens when an Exception is thrown?(from the 'Exceptions Overview' section of the .NET Framework Developer's Guide) "When an exception occurs, the runtime begins a two-step process: 1. The runtime searches the array for the first protected block that: · Protects a region that includes the currently executing instruction, and · Contains an exception handler or contains a filter that handles the exception. 2.." That’s alot of non-program related processing going on. You can imagine how convoluted that can get with a deep call stack and nested Exceptions. I was curious as to the real effect of all this processing compared to a plain old return value so I whipped up some embarrassingly crummy code to test it (code included below). I was astonished at the results! Here’s a copy of the results of a test run on my dual core 2.2GHz 4GB T61p Lenovo Thinkpad running Visual Studio 2008. Return value elapsed time = 10 uSec Return value elapsed time = 9 uSec Return value elapsed time = 8 uSec Exception handling elapsed time = 2104 mSec Exception handling elapsed time = 2066 mSec Exception handling elapsed time = 2078 mSec On average return values was 231407 times faster than exception handling. Return value elapsed time = 8 uSec Return value elapsed time = 8 uSec Return value elapsed time = 8 uSec Exception handling elapsed time = 2084 mSec Exception handling elapsed time = 2099 mSec Exception handling elapsed time = 2100 mSec On average return values was 245705 times faster than exception handling. Completed 2 timing tests. Press any key to exit... What a huge difference in performance! A few things to note about the output shown here: 1. There are two timing test runs. Two is an arbitrary number. I just wanted to show that it varies slightly between runs. 2. Each run is comprised of three return value test runs and three exception handler test runs. I did this to allow the execution environment to stabliize . You can see the slight bump in the first set of numbers. 3. I do a quick calculation at the end of each run to estimate the overall performance difference and what a difference there is - 8 microseconds vs 2,100,000 microseconds. Then I realised I had compiled in Debug mode. “Of course it’s going to be slow” I thought to myself. So I recompiled and ran it in Release mode ... the difference was even greater! Return value elapsed time = 6 uSec Return value elapsed time = 5 uSec Return value elapsed time = 4 uSec Exception handling elapsed time = 2184 mSec Exception handling elapsed time = 2142 mSec Exception handling elapsed time = 2167 mSec On average return values was 432866 times faster than exception handling. Return value elapsed time = 4 uSec Return value elapsed time = 4 uSec Return value elapsed time = 4 uSec Exception handling elapsed time = 2506 mSec Exception handling elapsed time = 2175 mSec Exception handling elapsed time = 2156 mSec On average return values was 493703 times faster than exception handling. Completed 2 timing tests. Press any key to exit... Notice the return value timings are roughly half what they were in Debug mode. My guess is that because Debug code is full of MSIL ‘NOP’ (no-op) instructions (so break points can be inserted if needed), it takes longer to process the MSIL where every second instruction is a NOP. Maybe that slows the “return values” timing test down in Debug mode. It doesn’t seem to make much difference to the Exception processing time though. So it’s clear to me: (A “Note to self” that I thought I’d share with you) “Exceptions are an exceptionally J good tool for dealing with exceptional circumstances at runtime but should rarely, if ever, be used for routine program flow control.” Anyway, I found this little excursion into the land of Exception processing performance enlightening - I hope you did too. Here's the C# code I used... using System; namespace ExceptionsVsreturnValues { class Program { static int itterations = 1000; static int nStabilizeLoops = 3; static int nTestLoops = 2; static DateTime start, end; static TimeSpan retElapsed, retElapsedTotal, exceptionElapsed, exceptionElapsedTotal; static void Main(string[] args) { for (int i = 0; i < nTestLoops; i++) { // First the return value timing returnValueTimingTest(); // Next the exception handling timing exceptionHandlingTimingtest(); // Report the results Console.WriteLine("\nOn average return values was " + (int)(exceptionElapsedTotal.TotalMilliseconds / retElapsedTotal.TotalMilliseconds * 1000) + " times faster than exception handling."); } Console.Write("Completed " + nTestLoops + " timing tests. Press any key to exit..."); Console.ReadKey(false); } private static void exceptionHandlingTimingtest() { // Run the test 'nLoop' times to allow the executio nenvironment to stabilise for (int i = 0; i < nStabilizeLoops; i++) { start = DateTime.Now; for (int j = 0; j < itterations; j++) { try { // Deliberatley send a null in place of the expected string // to cause a null pointer exception to be thrown findCustomerWithExceptions(null); } catch //(Exception e) { // Uncomment this and above if you want proof that an exception is being thrown // Console.WriteLine("Exception \"" + e.Message + "\" caught"); } } end = DateTime.Now; exceptionElapsed = end - start; if (exceptionElapsedTotal == null) exceptionElapsedTotal = exceptionElapsed; else exceptionElapsedTotal += exceptionElapsed; Console.WriteLine("Exception handling elapsed time = " + exceptionElapsed.TotalMilliseconds + " mSec"); } } private static void returnValueTimingTest() { // Run the test 'nLoop' times to allow the executio nenvironment to stabilise for (int i = 0; i < nStabilizeLoops; i++) { start = DateTime.Now; for (int j = 0; j < itterations * 1000 /* need to scale up the time from uSec to mSec because this is too fast for raw comparison! */; j++) { findCustomer("fred"); } end = DateTime.Now; retElapsed = end - start; if (retElapsedTotal == null) retElapsedTotal = retElapsed; else retElapsedTotal += retElapsed; Console.WriteLine("Return value elapsed time = " + retElapsed.TotalMilliseconds + " uSec"); } } private static void findCustomerWithExceptions(string p) { // causes a null pointer exception if p == null p.Trim(); } private static int findCustomer(string p) { return 0; } } } P.S. The story is similar with Java. I did a quick port to JDK 6 Update 4 and found return values are in the order of 4,000 times faster than Exception handling in the Sun JVM. Not as wide a gap as the CLR but still enough to avoid using Exceptions inappropriately no matter what platform you choose. PingBack from I applaud this post. The title is absolutely correct: exceptions should not be used for application flow. However, making the argument in terms of performance is like saying you shouldn’t run red lights because you might get a ticket, when the real reason is that it’s dangerous and wrong. If making the performance argument convinces some developers to abandon exception abuse, that’s good. But the real meat of the argument is that it is wrong. The example given is a good one: not finding a product (or any other type of lookup) is not an exceptional condition, it is one of many legitimate outcomes of a lookup, and should be handled as such. Treating it as an exception introduces a subjective bias into the outcome, based on some human viewpoint about what it is ‘normal’ or ‘better’. The real problem with abusing execptions like this is not runtime performance, but sloppy thinking. Hi. 1. The return value of the ProductExists() method should not be a null and surely not -1. It should be a boolean false. 2. You should not use exceptions for controlling the normal flow of the application even if they are 100 times faster than a return in the next generation of the CLR. Exceptions are for another thing than controlling the successful flow of your programs. They are for handling errors. Sorry, but I decidedly disagree. Exception handling isn’t necessarily significantly slower than standard control structures. This is just an implementation issue, which might change. I measured the times for a JVM as well, and while that was about 2 years ago, I still remember that the difference wasn’t high enough to justify altering my designs. You really should not base the decision to use exceptions or standard control flow mechanisms on performance. Exceptions are called "exceptions" because they are intended for exceptional control flow, and you should use them for these cases. For example, they can be very useful to signal an invalid state through several layers of application code. Using return values is a very impractical alternative. Just choose the right tool for the job, and don’t impede your judgement with useless microbenchmarks. Donald Knuth wrote "We should forget about small efficiencies, about 97% of the time. Premature optimization is the root of all evil." In my experience, he was damn right about that. Excellent points guys. Thanks for the comments.
https://blogs.msdn.microsoft.com/chris.green/2008/02/10/dont-use-exceptions-to-control-application-flow/
CC-MAIN-2018-05
refinedweb
1,570
55.13
HOUSTON (ICIS)--US base oil spot prices are rising on snug supply in some viscosity grades and tight supply in the heavy neutral grades, sources said on Wednesday. “Heavy neutral supply is very tight,” one source said. “We have no material for spot business,” a supplier commented. Heavy neutral Group I 600 viscosity grade base stocks were most recently assessed at $3.85-4.00/gal FOB (free on board) USG (US Gulf), rising over 25 cents/gal from February/March prices on the strength of narrow supply and March/April posted price increases by all base oil producers. Group I brightstock spot prices were most recently assessed at $4.15-4.25/gal FOB US Gulf, also gaining about 20 cents/gal over first quarter prices on similar fundamentals. Base oil producers cut back on production during the first quarter as high feedstock vacuum gas oil (VGO) costs erased profit margins, causing refiners to push the crude oil to make fuels rather than the base stocks, sources said. The tight supply situation is also underpinned by several maintenance turnarounds, including one at Paulsboro Refining Company (PRC) in March and ?xml:namespace> “We are entering the turnaround on very low inventories,”
http://www.icis.com/resources/news/2014/04/23/9774600/us-base-oil-spot-prices-rise-on-snug-supply/
CC-MAIN-2015-22
refinedweb
201
60.95
This article is paired with a companion repository. Get your free code while it is fresh. Why WebAssembly is Relevant? For a long answer to this question read our introduction on WebAssembly: Why should you care? The short answer is that WebAssembly can permit to compile seriously complex application into an efficient binary format, that can be run in web browsers with good performance. So far we had just JavaScript, now we have an assembly for the web and we can compile all sort of languages to WebAssembly (WASM for its friends). Think of C, C++, Rust, and… Kotlin, obviously. All compilable to WASM. WASM Support in Browsers At the time of writing 71% of browsers support WASM. Edge, Firefox, Chrome, Safari: they all support WASM. People on IE or weird mobile browsers are left out in the cold but every desktop users who bothered to get its browser from this century has support for WASM. In some browsers WASM could be supported but be disabled by default. On recent Chrome and Firefox it should be enabled by default. It is time to get ready for WASM. Or do you want to left behind to play with Cobol & Fortran? The Current Status of Kotlin Support for WASM The first thing we should notice is that Kotlin supports WASM through its Kotlin/Native compiler. The Kotlin/Native compiler is based on LLVM and LLVM supports WebAssembly, ergo we can get WASM files from Kotlin source code. Great, however that is not all we need. We need far more things to be productive when writing Kotlin to be compiled to WASM and things are very rough around the edges at the moment. We need great support and we are getting there but so far when compiling to WASM things are more difficult than when we compile Kotlin for the JVM or to JavaScript. You like living on the edge and take a look at the future? Cool, but do not expect first class service while doing so. How to Run the Kotlin Native Compiler from the Command Line You will need to run Kotlin Native compiler from the command line in two cases: - If you do not want to build your project using Gradle and the Konan plugin - If you want to compile the libraries using jsinterop (but you can find them precompiled in the companion repository) Anyway, if you still want to be able to call the compiler directly this is what you need to do. First of all you need to download the Kotlin/Native binaries. You can find them here. Once you have downloaded the binaries you unpack them and you add the binaries to the PATH. Yes, pretty old style, but that still works. Perhaps you can write your own little script to do that: #!/usr/bin/env bash KOTLIN_NATIVE_HOME=/Users/federico/tools/kotlin-native-macos-0.6.2 export PATH=$KOTLIN_NATIVE_HOME/bin:$PATH Now we can move to see how things work when using Gradle. How to Build Your Kotlin WASM Project Using Gradle That is pretty simple. This is all you need is to type this code into your build.gradle file: buildscript { repositories { jcenter() maven { url "" } maven { url "" } maven { url "" } } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "com.moowork.gradle:gradle-node-plugin:$gradle_node_version" classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$kotlin_native_version" } } apply plugin: 'konan' konanArtifacts { program('stats', targets: ['wasm32']) { srcDir 'src/main/kotlin' libraries { useRepo 'lib' klib 'dom' } } } At this point you can just use the build target and you are good to go. Well, almost, you still need the DOM library. The DOM Library Currently there are two libraries you may want to use with WASM. You can build them using the jsinterop tool which is distributed with Kotlin Native. Let’s try it: Ok, this is not really super flexible, is it? It seems that there are two libraries supported when running Kotlin and WASM. So what you can do is build those two libraries and forget about the jsinterop tool. To save time I just built the dom and math libraries and added to the lib directory of the repository. Ok, now we can really get started, we have just to fire our IDE, right? Well, yes, there is something I have to tell you… The IDE Issue Currently there is an IDE with support for Kotlin/Native, ergo one IDE with support for writing Kotlin applications which compile to WebAssembly. That IDE is CLion, from Jetbrains and… it is not available for free. So, it is an issue? Yes, it is… but it is not as bad as you think. First of all many of us are professionals that work in companies making money out of software, so it should not be a taboo to pay for some tools. Should it be? Still, I understand that it is a problem for all the kids out there that are learning and cannot afford paying for a license. Well, there are two things to consider. 1 – Life outside an IDE is possible You can just use IntelliJ IDEA to get Kotlin syntax highlighting but IDEA will not understand the WASM libraries and it will not know how to compile to wasm, so you will have to do that from the command line. Basically you will be using IntelliJ IDEA as it was an humble editor, not a full IDE. 2 – The free IDE seems to be coming So, do not stress too much about the IDE. Great things are going to happen if you keep your heart pure and you keep wishing for it real hard. In the meantime, let’s program as our fathers used to do. Or as the weird guy still using vim is doing. Our Example Our example is based on the application used by Jetbrains at the first KotlinConf. This application reads some data on votes and update constantly a graph to show the distribution of votes between five teams. It looks like this: Ok, how can we build this thing? File src/main/kotlin/main.kt Let’s start with the main: import kotlinx.interop.wasm.dom.* import kotlinx.wasm.jsinterop.* fun loop(canvas: Canvas) { fetch("/stats.json"). then { args: ArrayList -> val response = Response(args[0]) response.json() }. then { args: ArrayList -> val json = args[0] val colors = JsArray(json.getProperty("colors")) assert(colors.size == Model.tupleSize) val tuple = arrayOf(0, 0, 0, 0, 0) for (i in 0 until colors.size) { val color = colors[i].getInt("color") val counter = colors[i].getInt("counter") tuple[color - 1] = counter } Model.push(tuple) }. then { View(canvas).render() } } fun main(args: Array<String>) { val canvas = document.getElementById("myCanvas").asCanvas setInterval(100) { loop(canvas) } } So the main basically find the canvas element in the DOM, then it starts an infinite loop. In this loop every 100ms the function is called. What the function does? - retrieve data from stats.json, - take that data and push them into the Model, - then it ask the view to update itself to show the new data. File src/main/kotlin/model.kt So now we can take a look at the model. Note that this is an , not a . That means we have just one instance of and the rest of the system (most importantly the ) can access it without the need of a reference.>) { assert(new.size == tupleSize) new.forEachIndexed { index, it -> backLog[offset(current, index)] = it } current = (current+1) % backLogSize new.forEach { if (it > maximal) maximal = it } } } What the model does? The model simply receive an array of data (one value for each “team”) and add it to its backlog. The backlog it is basically an array of 500 values, or in other words the last 100 entries of 5 values each. Initially it is set to contain just zeros but over time it start to be filled with the actual values received through . File src/main/kotlin/view.kt Wonderful, now that we have data it is time to show that data. In the view file we have one object and two classes: - Style contains some constants about colors - Layout contains constants about the positions of elements, the padding, sizes, etc - View is where the funny stuff happens Basically in we draw the data and update the labels. The most external labels indicates just the IDs of the teams: a number from 1 to 5. The more internal labels instead indicates the most recent values for each team. import kotlinx.interop.wasm.dom.* import kotlinx.wasm.jsinterop.* object Style { val backgroundColor = "#16103f" val teamNumberColor = "#38335b" val fontColor = "#000000" val styles = arrayOf("#ff7616", "#f72e2e", "#7a6aea", "#4bb8f6", "#ffffff") } open class Layout(val rect: DOMRect) { val lowerAxisLegend = 0.1 val fieldPartHeight = 1.0 - lowerAxisLegend val teamNumber = 0.10 val result = 0.20 val fieldPartWidth = 1.0 - teamNumber - result val teamBackground = 0.05 val legendPad = 50 val teamPad = 50 val resultPad = 40 val teamRect = 50 val rectLeft = rect.getInt("left") val rectTop = rect.getInt("top") val rectRight = rect.getInt("right") val rectBottom = rect.getInt("bottom") val rectWidth = rectRight - rectLeft val rectHeight = rectBottom - rectTop val fieldWidth: Int = (rectWidth.toFloat() * fieldPartWidth).toInt() val fieldHeight: Int = (rectHeight.toFloat() * fieldPartHeight).toInt() val teamWidth = (rectWidth.toFloat() * teamNumber).toInt() val teamOffsetX = fieldWidth val teamHeight = fieldHeight val resultWidth = (rectWidth.toFloat() * result).toInt() val resultOffsetX = fieldWidth + teamWidth val resultHeight = fieldHeight val legendWidth = fieldWidth val legendHeight = (rectWidth.toFloat() * lowerAxisLegend) val legendOffsetY = fieldHeight } class View(canvas: Canvas): Layout(canvas.getBoundingClientRect()) { val context = canvas.getContext("2d"); fun poly(x1: Int, y11: Int, y12: Int, x2: Int, y21: Int, y22: Int, style: String) = with(context) { beginPath() lineWidth = 2; // In pixels setter("strokeStyle", style) setter("fillStyle", style) moveTo(x1, fieldHeight - y11) lineTo(x1, fieldHeight - y12) lineTo(x2, fieldHeight - y22) lineTo(x2, fieldHeight - y21) lineTo(x1, fieldHeight - y11) fill() closePath() stroke() } fun showValue(index: Int, value: Int, color: String) = with(context) { val textCellHeight = teamHeight / Model.tupleSize val textBaseline = index * textCellHeight + textCellHeight / 2 // The team number rectangle fillStyle = Style.teamNumberColor fillRect(teamOffsetX + teamPad, teamHeight - textBaseline - teamRect/2, teamRect, teamRect) // The team number rectangle fillStyle = color fillRect(resultOffsetX, teamHeight - textBaseline - teamRect/2, teamRect/2, teamRect) } fun showText(index: Int, value: Int, color: String) = with(context) { val textCellHeight = teamHeight / Model.tupleSize val textBaseline = index * textCellHeight + textCellHeight / 2 // The team number in the rectangle setter("font", "16px monospace") setter("textAlign", "center") setter("textBaseline", "middle") fillStyle = Style.fontColor fillText("${index + 1}", teamOffsetX + teamPad + teamRect/2, teamHeight - textBaseline, teamWidth) // The score setter("textAlign", "right") fillStyle = Style.fontColor fillText("$value", resultOffsetX + resultWidth - resultPad, resultHeight - textBaseline, resultWidth) } fun showLegend() = with(context){ setter("font", "16px monospace") setter("textAlign", "left") setter("textBaseline", "top") fillStyle = Style.fontColor fillText("-10 sec", legendPad, legendOffsetY + legendPad, legendWidth) setter("textAlign", "right") fillText("now", legendWidth - legendPad, legendOffsetY + legendPad, legendWidth) } fun scaleX(x: Int): Int { return x * fieldWidth / (Model.backLogSize - 2) } fun scaleY(y: Float): Int { return (y * fieldHeight).toInt() } fun clean() { context.fillStyle = Style.backgroundColor context.fillRect(0, 0, rectWidth, rectHeight) } fun render() { clean() // we take one less, so that there is no jump from the last to zeroth. for (t in 0 until Model.backLogSize - 2) { val index = (Model.current + t) % (Model.backLogSize - 1) val oldTotal = Model.tuple(index).sum() val newTotal = Model.tuple(index + 1).sum() if (oldTotal == 0 || newTotal == 0) continue // so that we don't divide by zero var oldHeight = 0; var newHeight = 0; for (i in 0 until Model.tupleSize) { val style = Model.styles[i] val oldValue = Model.colors(index, i) val newValue = Model.colors(index+1, i) val x1 = scaleX(t) val x2 = scaleX(t+1) val y11 = scaleY(oldHeight.toFloat() / oldTotal.toFloat()) val y21 = scaleY(newHeight.toFloat() / newTotal.toFloat()) val y12 = scaleY((oldHeight + oldValue).toFloat() / oldTotal.toFloat()) val y22 = scaleY((newHeight + newValue).toFloat() / newTotal.toFloat()) poly(x1, y11, y12, x2, y21, y22, style); oldHeight += oldValue newHeight += newValue } } for (i in 0 until Model.tupleSize) { val value = Model.colors((Model.current + Model.backLogSize - 1) % Model.backLogSize, i) showValue(i, value, Model.styles[i]) } for (i in 0 until Model.tupleSize) { val value = Model.colors((Model.current + Model.backLogSize - 1) % Model.backLogSize, i) showText(i, value, Model.styles[i]) } showLegend() } } We have the code but now how can we use it? We are going to see that in the next paragraph. Putting Pieces Together We will need to package our web application. We will need: - A way to get the data to display - An HTML page - The wasm file with the compiled code - A JS file to launch the wasm code To keep things easy we will get the data directly from a simple JSON file. Of course in a real application you may want a data-source a bit more dynamic… This is our glorious stats.js: { "colors" : [ { "color": 1, "counter": 4 }, { "color": 2, "counter": 14 }, { "color": 3, "counter": 9 }, { "color": 4, "counter": 7 }, { "color": 5, "counter": 6 } ] } The HTML page will be actually quite simple, as it will contain just a canvas and the code to load our script: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http- <title>WASM with Kotlin</title> <style> html, body { width: 100%; height: 100%; margin: 0px; } </style> </head> <body> <canvas id="myCanvas"> </canvas> <script wasm="./stats.wasm" src="./stats.wasm.js"></script> </body> </html> Finally there are the stats.wasm and stats.wasm.js. We get them just by running `./gradlew build`. But that is not enough, we also need to put those files in the directory that we are going to serve through http. So what we do is simply copying the wasm and wasm.js files from to . Now we have all that we need, we just need to get all the pieces to the browser. How are we going to do that? Using a very simple http server. Serving Files Using the simplehttp2server During development I prefer to use a simple solution, named simplehttp2server. You are surely a smart reader, able to figure out how to install it on your platform or find a valid alternative. For example on mac you can simply run: brew tap GoogleChrome/simplehttp2server brew install simplehttp2server Once you have installed all that you have to do is to go into your web directory and run . The directory at this point should contain the html file, the wasm file, the wasm.js file, and the json file. Now you can visit and you should see the application: Ok, nothing is going on but if you open the stats.json file and change it you should see the image change. Call JavaScript Functions from WASM Well, JavaScript interoperability is improvable. Basically the wrapper generated by the compiler exposes to the WASM file some symbols. The problem is that apparently at this moment there is no proper way to add more symbols to that list. Suppose we want to add a function to show an alert once we got data. We modify our model file like this:>) { igotdata() assert(new.size == tupleSize) new.forEachIndexed { index, it -> backLog[offset(current, index)] = it } current = (current+1) % backLogSize new.forEach { if (it > maximal) maximal = it } } } @SymbolName("imported_igotdata") external public fun igotdata() Ok, but how can I expose a JS function to the Kotlin code? No, there is no proper way but there is an hack you could use : - Make the loading fail on purpose, after the loader has created some structures - Insert in those structures some extra symbols - Run the WASM file For point one we can simply remove the wasm attribute from the script tag: <script src="./stats.wasm.js"></script> Now, if you try to load the page you get an error: At this point let’s inject the symbol `imported_igotdata` and run the webassembly. <script> konan.libraries.push({"imported_igotdata":function(msg){ alert("I got the data, updating");}}) var filename = "./stats.wasm"; fetch(filename).then( function(response) { return response.arrayBuffer(); }).then(function(arraybuffer) { instantiateAndRun(arraybuffer, [filename]); }); </script> I suggest you to slow down the loop from 100ms to 1000ms before trying this code…. Call WASM Functions from JavaScript To do that we can use the WebAssembly object to compile an entire script and run them or run single functions. However this is nothing specific to Kotlin. Summary And this is it: a first example of a Kotlin application compiled to WASM. Now, this is of course very raw and primitive. There are clearly issues: - Limited standard library available - The only IDE is not free But things move fast in the Kotlin world. We have already support for multiplatform projects. That means that we can build as of today libraries that can be used on the JVM, in the JavaScript world and compiled to wasm. A free IDE is coming. The Kotlin/Native compiler is progressing at a fast pace. Things are going to be soon very interesting and we suggest you get ready and start being aware of what this new world looks like. The post Kotlin and WebAssembly appeared first on SuperKotlin.
https://kotlined.com/blog/kotlin-and-webassembly-5/
CC-MAIN-2021-04
refinedweb
2,811
66.03
connect − initiate a connection on a socket #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);). If the connection or binding succeeds, zero is returned. On error, −1 is returned, and errno is set appropriately. AF_INET see the description of /proc/sys/net/ipv4/ip_local_port_range ip(7) for information on how to increase the number of local ports.. SVr4, 4.4BSD, (the connect() function). An example of the use of connect() is shown in getaddrinfo(3). accept(2), bind(2), getsockname(2), listen(2), socket(2), path_resolution(7) This page is part of release 3.32 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://man.sourcentral.org/slack1337/2+connect
CC-MAIN-2018-47
refinedweb
127
53.17
The MoSync Purchase C++ Library provides a set of classes and methods (in the IAP namespace) for purchasing products and handling user’s transaction information from within your own application. The library is built on top of the MoSync Purchase C API which provides a comprehensive set of functions for managing purchases. For a detailed tutorial that shows how to create a cross-platform mobile application using the Purchase C++ Library and Purchase C API, see: In-App Purchase tutorial. The MoSync SDK includes a fully commented example application, InAppPurchaseExample, that makes use of the the Purchase Library and API. In-app purchase mechanisms vary from platform to platform. Their implementation is dependent not only on the device's software but also on the platform vendor's billing system. The purchase type determines how the shops handle and track purchases. Purchase types for Apple iTunes Purchase types for Google Play For a list of the platforms supported by the Purchase C++ Library, see Feature/Platform Support. Purchases are encapsulated in objects of the Purchase class. The Purchase wraps a product that can be bought along with all the details of the transaction (such as the Receipt). The main methods of the Purchase class include: Receipts are encapsulated in objects of the Receipt class: A Receipt wraps the details of a purchase. The main methods of this class include: The PurchaseManager class manages purchase-related events and dispatches them to the target products. It is a singleton class. Its main methods include: The PurchaseListener can be used to listen for a specific purchase’s events. The PurchaseListener class contains the following virtual methods: The PurchaseManagerListener can be used to listen for restored or refunded products. The class contains the following virtual methods: The Purchase C++ Library described above makes use of the MoSync Purchase C API which contains a number of lower-level C IOCTLs. For a list of the platforms supported by the Purchase C API, see Feature/Platform Support. More information on these functions can be found in the MoSync C/C++ API Reference. A complete screencast for an example application can be found here, on our YouTube MoSync Dev Channel.
http://www.mosync.com/docs/sdk/cpp/guides/libs/purchase-library-and-api/index.html
CC-MAIN-2014-10
refinedweb
362
52.8
How to convert Integer to String in Java? For enterprise java application or programming, it is a common thing that a java developer or programmer needs to convert integer to string. Using Java classes, it is very easy and straight forward to convert an integer to a string. Steps to convert Integer to String in Java: Step 1: Integer variable declaration First, define an integer variable that you need to convert. Suppose, we have a integer "123". We will define that value using a variable like myInt. So, the full expression will be: int myInt = 123; Step 2: String variable declaration After converting the integer value to string, we need to save the that value into a variable so that we could use that later. Moreover, the data type of this variable should be String type. For example, name of the String variable is myString. The total expression to define this string would be like the following: String myString; Conversion from integer to string: Using Java, you can easily convert the integer to string. To convert this, we will use toString() method which is available in Integer class. So, we will convert the integer and save it into the string variable which we declared previous step. The code for this will look like the following line: myString = Integer.toString(myInt); Printing the variable into the console: To test whether the conversion is correct or wrong, we can check this by printing that variable into the console. The following line of code is used to print the string variable: System.out.println("String output: " + myString) Sample full Java code: Below is a sample program which converts a integer to string. Using Java this code is implemented. public class ConvertingIntegerToString { public static void main(String[] args) { int myInt = 123; String myString; myString = Integer.toString(myInt); System.out.println("Integer output: " + myInt); System.out.println("String output: " + myString); } } Screenshot of the program with sample output
https://hubpages.com/technology/How-to-convert-Integer-to-String-in-Java
CC-MAIN-2017-22
refinedweb
322
55.84
In simple terms, TiVo is a system that works on digital video recorders to allow you to manipulate live television—including recording pausing, rewinding, and more. Additionally, the TiVo service gives you the ability to do such things as specify your favorite actor and it will then start looking for and recording shows for you if that actor will be on a specific show. These are just a few of the services that TiVo can do. If you have a Series 2 TiVo and you hook it into your home network, you then can display images or listen to your favorite music on your television through the TiVo system. The music is stored on your PC, so if you have multiple TiVos, you can access it from any of them on your network. Just added to the TiVo services is the ability to record shows from your TiVo/television onto your computer so that you can watch them on your computer, or take them with you on a notebook computer or DVD. Prior to this addition (called TivoToGo), you could transfer a television show from one TiVo (Series 2) to another through your network, but you could not pull copies onto your computer. To fully understand a TiVo, you have to play with one. An in-law of mine has just received their first TiVo. When she mentioned it to a friend, her friend responded that her [my in-law's] life was going to change. That is a pretty strong statement. The truth is, a TiVo does change how you watch television. I'm not here to sell you on TiVo, though. Rather, this announcement is about the fact that TiVo is working to change how you can interact with the television on an even greater level. I've talked about programming platforms and various clients. TiVo has now added the television as a viable, possible target for your applications. Yesterday, TiVo released an SDK. This allows you to start developing applications that will work with TiVo Series 2 devices. In simple terms, a TiVo is simply a Linux box with a hard drive for storing television programs. By using the SDK, you will be able to tap into this system and create applications that can work on the television using any TiVo Series 2 device that is hooked into a network. There are a few other requirements for making this work as well, but all are easily obtained: - You must be using a Series 2 TiVo. - It must be hooked into a network and have the TiVo server running (free). - If you are already running the TiVo server (needed for home media options), you may need to upgrade it to 2.0. - It must have Java 1.4 or later. - You must have the software in your TiVo updated. development is done by using standard Java and the SDK can be downloaded now from here. The only critical issue is that software in your TiVo has to be updated to the most recent version. This is an automatic update that you can get by requesting it on the TiVo site. If you have updated your Tivo for TivoToGo, you already have it. With everything in place, you can begin developing applications that will run on your PC and interact with your TiVo Series 2 to display on your television. You can use a number of the keys on the TiVo remote to interact with the developed applications. The end result is that you can use your television to run applications and the TiVo remote to interact with them. Expectations are that there will be games and applications that take advantage of single and multiple users. Additionally, you'll be able to tap into advanced program and movie guides, giving the ability to deliver a different style of application. The possibilities are open. Of course, if you haven't requested the update for TivoToGo, then you will hit a roadblock—a roadblock I consider very serious because it has implications. In the words of TiVo customer service: "Even with being on the list for the priority, it can still take three to four weeks to receive the download for the new software that will enable the TiVoToGo feature." If you request the update to your TiVo today, you will be put on a waiting list. You can ask to be put onto a priority list; however, the stated wait time for being on the priority list is up to three to four weeks. I don't know what the wait time is if you are not prioritized. In other words, download the SDK, upgrade the software on your PC, and then wait a month before you can see how it looks on your TiVo. This is a delay that the developers at TiVo will need to overcome if this is to be considered a serious platform. While I believe that this is a very cool SDK with huge potential, I have to step back and question the viability of a system that could take a month to update. With many TiVo's wired into the Internet for updates, this delay seems outrageous. I'm currently working on a basic tutorial for writing a program for TiVo. As a teaser, here is a TiVo application: public class HelloWorld extends Application { protected void init(Context context) { root.setResource(createText("default-36-bold.font", Color.white, "Hello, world!")); } } As you can see, this is straightforward Java. This is your standard "Hello World" application written for TiVo. # # # There are no comments yet. Be the first to comment!
https://www.codeguru.com/announcements/article.php/3467231/Developing-for-Television-TiVo-Announces-an-SDK.htm
CC-MAIN-2018-51
refinedweb
934
62.17
In version 2.0 of the .NET Framework, Microsoft introduced the System.Threading. SynchronizationContext class. Simply stated, a SynchronizationContext-derived object connects an application model to its threading model. The FCL defines several classes derived from SynchronizationContext, but usually you will not deal directly with these classes; in fact, many of them are not publicly exposed or documented. Here is what the SynchronizationContext class looks like (I show only the members relevant to this discussion): public class SynchronizationContext { // Gets the SynchronizationContext-derived object // associated with the calling thread public static SynchronizationContext Current { get; } // Invokes d asynchronously public virtual void Post(SendOrPostCallback d, object state); // Invokes d synchronously public virtual void Send(SendOrPostCallback d, object state); } // SendOrPostCallback is a delegate defined like this: public delegate void SendOrPostCallback(Object state); Console and NT service applications have no threading model and therefore calling SynchronizationContext.Current will return null. For GUI applications such as Windows Forms, Windows Presentation Foundation, and Silverlight, the threading model dictates that all UI components must be updated by the thread that created them. So, when a GUI thread calls SynchronizationContext.Current, a reference to an object that knows how to invoke the d delegate on the calling GUI thread is returned. For ASP.NET applications, calling SynchronizationContext.Current returns a reference to an object that knows how to associates the original client request's identity and culture with the calling thread before invoke the d delegate (which will be invoked on the same thread that calls SynchronizationContext's Post or Send methods. In fact, for an ASP.NET SynchronizationContext object, the Post and Send methods do the exact same thing: they call the d delegate synchronously. When working with the .NET Framework's Asynchronous Programming Model (APM), understanding the SynchronizationContext is extremely important as it allows the callback method to be invoked using your application's thread model. To simplify this, I wrote the following little method: private static AsyncCallback SyncContextCallback(AsyncCallback callback) { // Capture the calling thread's SynchronizationContext-derived object SynchronizationContext sc = SynchronizationContext.Current; // If there is no SC, just return what was passed in if (sc == null) return callback; // Return a delegate that, when invoked, posts to the captured SC a method that // calls the original AsyncCallback passing it the IAsyncResult argument return asyncResult => sc.Post( result => callback((IAsyncResult)result), asyncResult); } This method turns a normal AsyncCallback method into an AsyncCallback method that is invoked via the SynchronizationContext-derived object associated with the calling thread.On Sep 22 2010 5:44 AMBy jeffreyr PingBack from WOW! Thanks Jeff, this is awsome. I have been looking for a clean way to do this for a while. This is the best I have seen. This very cool method is also useful when you want to call existing code asynchronously, by doing this for ex.: Action a = SomeMethod; a.BeginInvoke(SyncContextCallback((ar) => { a.EndInvoke(ar); // Do something here (which executes on the UI thread). }), null); public void SomeMethod() { /* Long running op. here. */}; Hi Jeffrey, About a year ago I did a short research on APM. One of the result was that when async operation completes a callback is executed on one of IO threads from the .Net thread pool (you wrote in your book about these threads that they are only used to call a callback when async IO operation completes). I decided that as these IO threads are essentially used only to wait on IO completion port for async IO operation to complete it is safe to call from the callback another IO operation _synchronously_. My idea was as synchronous operation is essentially made asynchronously but it just waits for IO operation (made asynchronously by OS) on IO completion port and blocks current thread while waiting. So if we call it synchronously from IO thread we do the same as it were called asynchronously with only difference that in this case just another IO thread will be blocked waiting on IO completion port. So am I correct or it is a bad practice and I missed something when thought about that? PS. I've just read this article and remembered this idea. As i didn't found better place to ask this question I posted it here. BTW your books are brilliant! I enjoy reading them. Thanks, Mikhail Mikheev
http://www.wintellect.com/blogs/jeffreyr/integrating-your-application-s-threading-model-with-the-asynchronous-programming-model
CC-MAIN-2013-20
refinedweb
710
53.81
lua_call 0.10.0 Call Lua scripts from other Lua scripts in Redis lua_call - a Redis + Lua scripting namespace and calling library for Python This library released under the MIT license. What is lua_call? This library implements a script transformation function along with some useful utilities to allow you to call Lua scripts from other Lua scripts in Redis. There are also some Python-side wrappers to aid in calling Lua from Python, but that’s just a bonus. Generally speaking, it adds an internal calling semantic that allows you to pass KEYS and ARGV between your internal Lua scripts in a sane manner. This allows you, as a developer, to to develop your Lua scripts using better practices than copying/pasting similar code between scripts. Limitations Due to the way we handle calling conventions, you must be careful in how you use KEYS and ARGV. Because we are not using a full-on parser for the Lua language, we use a regular expression to discover uses of KEYS and ARGV to alter. More specifically, we take examples like the following: local passed_keys = KEYS local source = KEYS[1] local arg = ARGV[1] local z = redis.call('KEYS', ...) … and translate them into: local passed_keys = _KEYS local source = _KEYS[1] local arg = _ARGV[1] local z = redis.call('KEYS', ...) Note that we didn’t mangle the KEYS in redis.call(), but if you were to have the following: local string = 'this is a string with KEYS and ARGV, oops!' … we will mangle the string into: local string = 'this is a string with _KEYS and _ARGV, oops!' There are other potential corner cases where our name mangling might be incorrect, and you are advised to keep your usage of KEYS and ARGV to reading or writing to KEYS and ARGV or to the simple literal strings of ‘KEYS’ and ‘ARGV’ as in redis.call(‘KEYS’, …). Defining scripts using lua_call You have a Redis connection during script definition If you have your Redis connection available while defining your Lua scripts, you can use the following calls to automatically define and register the function wrappers in the Python module, automatically load the script into Redis, and register the function for internal calling inside Redis: # contents of example.py from redis import Redis from lua_call import function conn = Redis(...) function .return_args(""" return ARGV """, conn) function .call_return(""" CALL.return_args({}, {1, 2, 3, ARGV}) """, conn) We describe how to use these functions just past the next section. You don’t have a Redis connection during script definition If you don’t have a connection during script definition, you can omit the connection argument during definition. In this case, the scripts will not be registered, so you must later call load_scripts() to register them. The following is more or less equivalent to the ‘have a connection’ section above: # contents of example.py from redis import Redis from lua_call import function, load_scripts function .return_args(""" return ARGV """) function .call_return(""" CALL.return_args({}, {1, 2, 3, ARGV}) """) load_scripts(Redis(), __name__) Calling scripts defined with lua_call Assuming that you have defined your scripts using one of the two methods outlined above, the example module will have functions defined in the module namespace called return_args() and call_return(). These wrappers around the script take exactly 3 arguments: a Redis connection, then a list of KEYS and a list of ARGV that are passed to the called scripts. An example of their use can be seen below: >>> from redis import Redis >>> conn = Redis() >>> import example >>> example.return_args(conn, [], [1, 2, 3]) ['1', '2', '3'] >>> example.call_return(conn, [], [4, 5, 6]) [1, 2, 3, ['4', '5', '6']] Note that while KEYS and ARGV passed from outside Redis are translated into strings as part of the calling process, internal calls do not change the types of arguments passed. How it works This library takes scripts that you define, possibly including other Lua script calls, and changes the source code to allow you to actually perform those calls. Generally speaking, you can think of this as introducing a new global value in Redis by the name of CALL, which allows you to both register functions and call those functions. Now, the truth is that there is no new global value available in Redis Lua scripting, but your scripts will act as though that is the case. As an example of what actually goes on, let’s say that we start out with a Lua script defined as the below, which is from the included example.py: return CALL.return_args({}, {1, 2, 3, _ARGV}) After our transformation (and applying some source code formatting and extra comments so you can understand what is going on easier), we get the following script: -- We reference either the externally-called KEYS/ARGV or the internally -- called KEYS/ARGV in locals called _KEYS and _ARGV local _KEYS, _ARGV; if #ARGV == 0 or type(ARGV[#ARGV]) == 'string' then -- Use the standard KEYS and ARGV as passed from the external caller _KEYS = KEYS; _ARGV = ARGV; else -- Pull the KEYS and ARGV from the table appended to ARGV _KEYS = ARGV[#ARGV][1]; _ARGV = ARGV[#ARGV][2]; -- We remove the pushed reference to prevent circular references, -- which can crash Redis if you aren't careful table.remove(ARGV); end; -- push the arguments onto the ARGV table as call stack arguments table.insert(ARGV, {{}, {1, 2, 3, _ARGV}}); -- fetch the script hash from the name and call the function return _G[redis.call('HGET', ':registry', 'example.return_args')](); Generally, there is some header code prepended to your source, KEYS and ARGV references are changed to _KEYS and _ARGV, and any time you want to make a call to another script, we append your arguments to the end of the ARGV table, and pull the destination script name from a Redis-backed function registry. Early versions of this library required assigning the result of a call to a local variable before returning, but this is no longer necessary. Licensing and source code mangling Technically speaking, this library will alter the Lua script source code that you pass in order to insert the code that handles internal calls. I do not consider this purposeful alteration to result in your code being in any way derived from or related to this library. Your source code remains your source code, and this library is a utility to aid in your development and maintenance processes. - Author: Josiah Carlson - Download URL: - License: MIT - Categories - Package Index Owner: josiahcarlson - DOAP record: lua_call-0.10.0.xml
https://pypi.python.org/pypi/lua_call
CC-MAIN-2016-36
refinedweb
1,077
55.78
This feature enables seamless zero downtime re-indexing of resource data from an API user’s point of view. ElasticSearch documents are stored and indexed into an “index” (imagine that). The index is a logical namespace which points to primary and replica shards where the document is replicated. A shard is a single Apache Lucene instance. The shards are distributed amongst nodes in a cluster. API users only interact with the index and are not exposed to the internals, which ElasticSearch manages based on configuration inputs from the administrator. Certain actions can only be done at index creation time, such as changing shard counts, changing the way data is indexed, etc. In addition to changing the data, re-populating an index that has lost coherency with source service data is much easier to do from scratch rather than determining what differences there are in the data. Due to this the data and indexes should be designed so that it is possible to re-index at any time without disruption to API users. The re-indexing happens while the services are in use, still indexing new documents in ElasticSearch. In Searchlight 0.1.0, we allowed for each plugin to specify the index where the data should be stored via configuration in the searchlight-api.conf file. By default, all plugins store their data in the “searchlight” index. This was simply chosen as a starting point, because the amount of total data indexed for resource instance data is believed to be quite small in comparison to typical log based indexing for small deployments, but this may differ dramatically based on the resource type being indexed and the size of the deployment. To reiterate, all resource types in Searchlight 0.1.0 (either the plug-in or the searches) have the ElasticSearch index hard-coded into them. This hard-coded functionality prevents Searchlight from doing smart things internally with ElasticSearch. Exposing indexes directly to the users is generally not recommended by the user community or by ElasticSearch. Instead, they recommend using aliases. API users can use an alias in exactly the same way as an index, but it can be changed to point to different index(es) transparently to the user. This allows for seamless migration between indexes, allowing for all of the above use cases to be fulfilled. The concept of aliases is described in depth in the ElasticSearch guides [1]. With this blueprint, we will divorce the plug-ins and searches from knowing about physical ElasticSearch indexes. Instead we will introduce the concept of a “Resource Type Group”. A Resource Type Group is a collection of Resource Types that are treated as a single unit within ElasticSearch. All users of Searchlight will deal with Resource Type Groups, instead of low-level ElasticSearch details like an index or alias. A Resource Type Group will correspond to ElasticSearch aliases that are created and controlled by Searchlight. The plug-in configuration in the searchlight-api.conf file will no longer specify the index name. Instead the plug-in will specify the Resource Type Group it chooses to be a member of. It is important for a plug-in to know which Resource Type Group it belongs. When some operations are undertaken by one member of a Resource Type Group, it will need to be done to all members in the group. There will be more details on this later. Now that the users are removed from the internals of ElasticSearch, we can handle zero downtime re-indexing. The basic idea is to create new indexes on demand, populate them, but use ElasticSearch aliases inside of Searchlight in a way that makes the actual indexes being used transparent to both API users and Searchlight listener processes. We will not directly expose the alias to API users. We will use resource type mapping to transparently direct API requests to the correct alias. When implementing this blueprint, we may choose to still expose an “index” through the plug-in API. Exposing an “index” may allow other open-source ElasticSearch libraries (which are index-based) to still work. Currently we are not using any of these libraries, but we may not want to exclude their usage in the future. Searchlight will internally manage two aliases per Resource Type Group. Note: Having these two aliases is the key change enabling zero downtime indexing. - API alias - Listener/Sync alias The names of the aliases will be derived from the Resource Type Group name in the configuration file. Exactly how this is handled will be left to the implementation. For example, we can append “-listener” and /Sync”-search” to the Resource Group Type name for the two aliases. The API alias will point to a single “live” index and only be switched once the index is completely ready to serve data to the API users. Completely ready means that the new index is a superset of the old index. This allows for transparently switching the incoming requests to the new index without disruption to the API end user. The listener alias will point to 1…* indexes at a time. The listener simply knows that it must perform CRUD operations on the provided alias. The fact that it might be updating more than one index at a time is transparent to the listener. The benefit to this is that the listeners do not have to provide any additional management API as ElasticSearch handles this for us automatically. The algorithm for searchlight-manage index sync will be changed to the following: - Create a new index in ElasticSearch. Any mapping changes to the index are done now, before the index is used. - Add the new index to the listener(s) alias. At this point, the listener’s alias is pointing to multiple indexes. The new index is now “live” and receiving data. Any data received by the listener(s) will be sent to both indexes. - There is an issue with indexing an alias with multiple indexes [2]. The issue is that this case is not allowed! In this case we will catch the exception and write to both indexes individually in this step. For more details, refer to the “Implementation Notes” subsection below. - Bulk dump of data from each Resource Type associated with the old index to the new index in ElasticSearch. - The same issue with multiple indexes mentioned above applies here also. - - Atomically switch the aliases for the API alias to point to the new index. - - We will use the actions command with remove/add commands in the same actions API call. ElasticSearch treats this as an atomic operation. [2]:{ "actions" : [ { "remove" : { ...} }, { "add" : " {...} } ] } - Remove the old index from the listener(s) alias. - Delete the old index from ElasticSearch. We do not want the index to hang around forever. We can figure out when the index is no longer being used and then delete it (asynchronous task, a type of internal reference count, etc). If this turns out to be too unwieldy we can revisit this action. A critical aspect to all of this is that the batch indexer and all notification handlers MUST only update documents if they have the most recent data. This is being handled by a separate bug [3]. In addition, Searchlight listeners and index must start setting the TTL field in deleted documents instead of deleting them right away. This functionality is covered in the ES deletion journal blueprint [4]. We are operating on a Resource Type Group as a whole. We need to make sure that the entire Resource Type Group is re-indexed instead of just a single Resource Type within the group. For example, consider the case where a Resource Type Group consists of Glance and Nova. When Searchlight gets a command to re-index Glance, Searchlight needs to also re-index Nova. Otherwise the new index will not have the previous Nova objects in it. If Nova did not re-index, the new index will not be a superset of the old index. When the alias switches to this new index it will be incomplete. The CLI must support manual searchlight-manage commands as well as automated switchover. For example: - Delete the specified or current index / alias for a specific resource type group. - Create a new index for the specified resource type group. - Switch API and listener aliases automatically when complete (default - yes). - Delete old index automatically when complete (default - yes). - Provide a status command so that progress can be seen. * List all aliases and indexes by resource type with their status * Can be used from a GUI or a separate CLI concurrently to monitor progress. This change affects: - The plugins API which lists plugins - The API - The Listener - The bulk indexer - The CLI To further illuminate the blueprint we will turn to a series of images and save ourselves thousands of words. The images shows the state of Searchlight during sequence of operations. For this example we have three resource types: Glance, Nova and Swift. There are two Resource Type Groups. The first group, RTG1, contains Glance and Nova. The two aliases associated with RTG1 are “RTG1-sync” for the plug-in listeners and “RTG1-query” for the plug-in searches. The second group, RTG2, contains Swift. The two aliases associated with RTG2 are “RTG2-sync” for the plug-in listener and “RTG2-query” for the plug-in search. Figure 1: The initial State First Searchlight will create the ElasticSearch index “Index1” for use by RTG1. The ElasticSearch aliases “RTG1-sync” and “RTG1-query” are created and will both be associated with the index “index1”. Next Searchlight will create the ElasticSearch index “Index2” for use by RTG2. The ElasticSearch aliases “RTG2-sync” and “RTG2-query” are created and will both be associated with the index “Index2”. Glance has now created two documents “Glance ObjA” and “Glance ObjB”. Nova has created two documents “Nova ObjC” and “Nova ObjD”. These four new documents for the first Resource Type Group are now indexed. They will be indexed against alias “RTG1-sync” and end up in index “Index1”. Swift has now created two new documents “Swift ObjE” and “Swift ObjF”. These two new documents for the second Resource Type Group are now indexed. They will be indexed against alias “RTG2-sync” and end up in index “Index2”. Figure 1 shows the current state of Searchlight. A Glance search will be made against “RTG1-query”. Going to “Index1” it will return “Glance ObjA”, “Glance ObjB”, “Nova ObjC” and “Nova ObjD”. A Swift search will be made against “RTG2-query”. Going to “index2” it will return “Swift ObjE” and “Swift ObjF”. Figure 2: Explicit Glance Re-sync All of the changes from Image 1 are highlighted in red. Searchlight receives a re-index command for Glance. After the re-sync, Glance creates two new documents “Glance ObjG” and “Glance ObjH”. Nova creates one new document “Nova ObjI”. Swift creates two new documents “Swift ObjJ” and “Swift ObjK”. Searchlight will create a new ElasticSearch index “Index3”. Since Glance is re-syncing, the new index is associated with RTG1. Searchlight now associates both “Index1” and “Index3” to the alias “RTG1-sync”. Since the new index “Index3” is not a superset of the index “Index1” yet, we do not change the RTG1 search alias “RTG1-query”. It remains unchanged for now. As the Glance re-sync occurs, the previous Glance documents “Glance ObjA” and “Glance ObjB” get indexed into “Index3”. The new documents for RTG1 (“Glance ObjG”, “Glance ObjH” and “Nova ObjI”) are indexed against the alias “RTG1-sync”. These documents end up in both “Index1” and “Index3”. The new documents for RTG2 (“Swift ObjJ” and “Swift ObjK”) are indexed against the alias “RTG2-sync”. These documents end up in “Index2”. Figure 2 shows the current state of Searchlight. A Glance search will be made against “RTG1-query”. Going to “Index1” it will return “Glance ObjA”, “Glance ObjB”, “Nova ObjC”, “Nova ObjD”, “Glance ObjG”, “Glance ObjH” and “Nova ObjI”. A Swift search will be made against “RTG2-query”. Going to “index2” it will return “Swift ObjE”, “Swift ObjF”, “Swift ObjJ” and “Swift ObjK”. This diagram shows the subtle point that all resource types within a Resource Type Group need to re-synced together. If we did not re-sync Nova and updated the RTG1 search alias “RTG1-query” to be associated with the new index “Index3”, the Searchlight state is incorrect. A Glance search will now be made against “Index3” and it will return “Glance ObjA”, “Glance ObjB”, “Glance ObjG”, “Glance ObjH” and “Nova ObjI”. This is incorrect as it does not include the earlier Nova documents: “Nova ObjC” and “Nova ObjD”. This incomplete state is the reason that all resources in a Resource Type Group need to be re-synced before the Resource Type Group re-sync is to be considered completed. Figure 3: Implicit Nova Re-Sync All of the changes from Image 2 are highlighted in red. Searchlight starts an implicit Nova re-sync, since Nova is a member of RTG1. All of the aliases are still set up correctly, so they do not need to change. After the re-sync, Glance creates one new document “Glance ObjL”. Nova creates one new document “Nova ObjM”. Swift creates one new documents “Swift ObjN”. As the Nova re-sync occurs, the previous Nova documents “Nova ObjC” and “Nova ObjD” get indexed into “Index3”. The new documents for RTG1 (“Glance ObjL” and “Nova ObjM”) are indexed against the alias “RTG1-sync”. These documents end up in both “Index1” and “Index3”. The new document for RTG2 (“Swift ObjN”) is indexed against the alias “RTG2-sync”. This document ends up in “Index2”. Searchlight has not yet acknowledged the Nova re-sync as being completed. Therefore “RTG1-query” has not been updated yet. Figure 3 shows the current state of Searchlight. A Glance search will be made against “RTG1-query”. Going to “Index”. Figure 4: RTG1 Re-Sync Complete All of the changes from Image 3 are highlighted in red. All resource types within RTG1 have finished re-syncing. Searchlight will now update the RTG1 search alias “RTG1-query”. The alias “RTG1-query” will now be associated with index “Index3”. After updated the RTG1 search alias, Searchlight will update the RTG1 plug-in listener alias “RTG1-sync”. The alias “RTG1-sync” will now be associated with the index “Index3”. The alias updates need to happen in this order to handle the corner case of a new RTG1 document being indexed while the aliases are being modified. If we modified the RTG1 plug-in listener alias first a new document would be indexed to index “Index3” only. But a search will still go to index “Index1”, thus missing the newly indexed document. Figure 4 shows the current state of Searchlight. A Glance search will be made against “RTG1-query”. Going to “Index”. The internal Searchlight state is correct, coherent and ready to continue. Sometime in the future we will be able to delete Index1 completely. Upon careful review of the ES alias documentation [2], there is this warning lurking in the shadows: “It is an error to index to an alias which points to more than one index.” Yikes. Now the simple solution of adding additional indexes to an alias and having the re-indexing just work, will not work. ElasticSearch will through an “ElasticsearchIllegalArgument” exception and return a 400 (Bad Request). The plug-ins will need to be aware of this exception and react to it. Through experimentation, ElasticSearch will return this error: {"error":"ElasticsearchIllegalArgumentException[Alias [test-alias] has more than one indices associated with it [[test-2, test-1]], can't execute a single index op]","status":400} From this error message, we have the actual indexes. After extracting the names of the indexes, the plug-ins will be able to complete the task. The plug-in will now index iterating on each real index, instead of using the alias. This case applies only to the case where there are multiple indexes in an alias (i.e. the re-syncing case). When not re-syncing, the plug-in will not receive this exception. We need to be careful when parsing the error message. This is a potential hazardous area if the error message ever changes. The catching of the exception and parsing of the message should be as flexible as possible. A corner case in the rationale for triggering a re-index needs to be addressed. Sometimes an incompatible change between indexes has occurred. For example a new plug-in has been added or the documents from the service of changed in an incompatible way (different ElasticSearch mapping). In any of these cases we need to be able to handle the changes and roll them out seamlessly. An alternate usage scenario would look like the following: Queries to v1/search/plugins would change so that the index listed for each type would actually be the alias (the API user won’t know this). The searchlight-manage index sync CLI will change to support the following capabilities: - Re-index the current index without migrating the alias (no change from 0.1.0). - Delete the specified or current index for a specific type. - - Create a new index for specified resource types. - - Specified name or autogenerated name using a post-fix numbering pattern. - Contact and stop all listeners from processing incoming notifications for specified types. - Switch alias automatically when complete (default - no ?). - Delete old index automatically when complete (default - no?). - Contact and start all listeners to process incoming notification for specified types. - Switch alias on demand to new index(es). All of the above must account for 1 … * indexes for a single alias. All listener processes must now support a management API for them to stop notification processing for specified resource types. Without this ability, there will remain a race condition for populating a new index. For example, if it takes N seconds to populate all Nova server instances, there will be a delay in time from when the original request for data to Nova was sent and when any updates to the data happened. Therefore, notification should be disabled while a new index is being populated and then turned back on. This alternate explores a way to avoid the “multiple indexes in a single alias while indexing” exception as described in the “Implementation Notes” subsection. The idea is that instead of having two indexes in the Sync alias and one index in the search alias, we invert the index usage in the aliases. Now we consider adding multiple indexes to the search alias while leaving a single index in the sync alias. When we start a re-sync, we create a new index. We update the sync alias to point to this new index, replacing the old index. Since there is only a single index in the sync alias, we will not get the ElasticsearchIllegalArgument exception. We also add the new index to search alias. At this point, the search alias contains just the new index while the search alias contains both the old and new index. When a search occurs it will find old documents as well as any new documents. The main issue with this alternative is that the search will find a lot of duplicates while the re-sync is occurring. All of the documents in the old index will eventually be added to the new index. In order to be usable, we would need to figure out a way to filter out these duplicates. The initial investigation into filtering ideas led to solutions that were deemed to fragile and defect prone. Hence the inclusion of this idea at the bottom of the alternate proposals. Optimizations: Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.
http://specs.openstack.org/openstack/searchlight-specs/specs/mitaka/zero-downtime-reindexing.html
CC-MAIN-2018-51
refinedweb
3,293
65.12
UK High Altitude Society There are two peripheral libraries which can be used. Firstly is the official ST libraries, or alternately libopencm3. There are more examples available for the ST libraries, however libopencm3 is nicer to use, but still in development. STM32 Intro (Jon) slides here: stm32_intro_ukhas14.pdf Ideally you should be able to apt-get install the tools, however the version in the repo is broken slightly and doesnt have the 'nano' version of newlib (printf etc) export PATH=/usr/local/gcc-arm-none-eabi-4_8-2014q2/bin:$PATH to your ~/.bashrc (assuming using bash). $ source ~/.bashrc $ sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded $ sudo apt-get update $ sudo apt-get install gcc-arm-none-eabi $ arm-none-eabi-gcc –version cdinto the root of the repo $ git submodule update –initto fetch libopencm3. cdto the libopencm3 directory and run $ maketo build. We've not got things set up for the F1 (or other) series yet, give us a shout if this is what you're after and we can help. Open up Makefile in firmware/src/. Adjust the last line for either the F0 or F4 as appropriate include ../common/Makefile.f0.includeOR include ../common/Makefile.f4.include Now open up common/stm32f0-discovery.ld or common/stm32f4-discovery. Adjust the RAM and ROM lengths as appropriate for your particular device. If you want to change the name of this file to satisfy your OCD, do so and then make the relevant change in firmware/common/Makefile.fx.include (where x=0 or 4 as appropriate). st-utiland st-flashbinaries A libopencm3 LED blink example is provided in firmware/src/main.c. cd to this directory and build the firmware with $ make - this should produce the main.elf file. If you're having issues then use $ make V=1 for more verbose build output. $ st-flash erase $ make bin $ st-flash write main.bin 0x8000000 On Linux, st-flash needs root privileges ( sudo ./st-flash …) to access the USB system until you set up udev rules In theory you should be able to follow the linux instructions. You will need to have make installed, as well as python. This guide will get a windows IDE based toolchain up and running. There is the option of either using ST or openlibcm3 libraries (see above). This guide uses 'coIDE,' however there are several available. This has the advantage that the ST libraries are 'built in', and so you just need to click on the ones you want and they are copied into the project. libopencm3 can still be used, but it requires a few more tweeks These are the drivers and downloading program for ST-Link, which is found on the ST development boards The STM32s also have a UART booloader, the tool to download is here: (you dont need this if you intend to use the SWD interface on the development boards) (skip to the next step if you want to use libopencm3) This example will now get an LED flashing. After project creation the 'repository' window should be showing, which has a selection of libraries that can be copied to the project. (if not, go view→repository) With the repository showing, click 'GPIO'. A whole load of files should have been copied into the project. Also click 'C library' (for printf/sprintf etc). Open main.c, and copy in the sample code below Firstly add the libopencm3 files to the project directory. This can be fetched from the libopencm3 repository and compiled as per above instructions, or run git submodule add .\firmware\libopencm3 if you want to add it to an existing repository. Since it is unlikely for all the tools (make, python and others) to be set up correctly. As a result, a precompiled version is available here. Unzip the contents into a separate libopencm3 folder along side your project The final file needed is part of the linker script. Copy this file (f4) or this file (f0) along side your project. Note that this file needs editing depending on how much flash/RAM the target has Now set up the IDE with these files: To run the program: coIDE defaults to STLink to download programs, however if you are having issues, check 'Download' settings in the project configuration #include "stm32f0xx.h" #include "stm32f0xx_gpio.h" #include "stm32f0xx_rcc.h" //include further headers as more peripherals are used int main(void) { //turn on GPIOC //IMPORTANT: every peripheral must be turned on before use RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE); //init structure for GPIO GPIO_InitTypeDef GPIO_InitS; GPIO_InitS.GPIO_Pin = GPIO_Pin_9; //the pin we are configuring GPIO_InitS.GPIO_Mode = GPIO_Mode_OUT; //set to output mode GPIO_InitS.GPIO_OType = GPIO_OType_PP; //set to push/pull GPIO_InitS.GPIO_PuPd = GPIO_PuPd_NOPULL; //no pullup resistors GPIO_InitS.GPIO_Speed = GPIO_Speed_50MHz; //set to max speed GPIO_Init(GPIOC, &GPIO_InitS); //write this config to GPIOC while(1) //flash forever { GPIO_SetBits(GPIOC, GPIO_Pin_9); //set pin on int32_t i = 4800000; while(i) i--; //delay a bit GPIO_ResetBits(GPIOC, GPIO_Pin_9); //set pin off i = 4800000; while(i) i--; //delay a bit } } #include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #define LED_PORT GPIOC #define LED_PIN GPIO9 int main(void) { // Set clock to 48MHz (max) rcc_clock_setup_in_hsi_out_48mhz(); // IMPORTANT: every peripheral must be clocked before use rcc_periph_clock_enable(RCC_GPIOC); // Configure GPIO C.9 as an output gpio_mode_setup(LED_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LED_PIN); // Flash the pin forever while(1) { gpio_set(LED_PORT, LED_PIN); int32_t i = 4800000; while(i) i--; gpio_clear(LED_PORT, LED_PIN); i = 4800000; while(i) i--; } } while(1) //flash forever { GPIOC->BSRR |= (1<<9); int32_t i = 4800000; while(i) i--; GPIOC->BRR |= (1<<9); i = 4800000; while(i) i--; }
https://ukhas.org.uk/guides:stm32toolchain
CC-MAIN-2021-43
refinedweb
924
55.44
.NET is a popular software framework developed by Microsoft. We just released a course on the freeCodeCamp.org YouTube channel that will teach you how to create a REST API end-to-end from scratch using the latest .NET 5 innovations and Visual Studio Code. The course uses the C# programming language. Julio Casal developed this course. He is a Senior Software Engineer at Microsoft and he is also an excellent teacher. Here are all the sections covered in this comprehensive course: Getting Started - Introduction - Creating the project - Exploring the generated project files - Trusting the self-signed certificate - Exploring the default Swagger UI page - Configuring Visual Studio Code settings Entity, Repository, Controller GET - Introduction - Adding an entity - Adding an in-memory repository - Creating the controller - Implementing GET all items - Implementing GET single item - Returning a 404 NotFound status code Dependency Injection, DTOSs - Introduction - What is dependency injection? - Extracting the repository interface - Injecting the repository into the controller - Registering the repository as a singleton - Adding a Data Transfer Object DTO - Creating the AsDto extension method POST, PUT, DELETE - Introduction - Implementing POST - Adding validations via data annotations - Implementing PUT - Implementing DELETE Persisting Entities with MongoDB - Introduction - Using Postman - Creating a MongoDB repository - Using the MongoDB.Driver NuGet package - Implementing MongoDB Create - Running the MongoDB Docker container - Configuring MongoDB connection settings - Registering the MongoClient singleton - Testing the MongoDB integration - Exploring the created database in VS Code - Implementing MongoDB Get, Update and Tasks, Async and Await - Introduction - Using the Async suffix - Using tasks in the repository - Using async and await - Returning completed tasks - Using tasks in the controller - Testing async methods in Postman Secrets and Health Checks - Introduction - Enabling authentication in MongoDB - Using the .NET Secret Manager - Using the MongoDB credentials in the service - Introduction to Health Checks - Adding an endpoint for health checks - Adding a MongoDB health check - Adding checks for readiness and liveness - Customizing the health check response - Exploring other health check NuGet packages Docker - Introduction - What is Docker? - Removing https redirection - Generating a Dockerfile in VS Code - Building the Docker image - Adding a Docker network - Running the containers in the Docker network - Running the REST API in Docker - Pushing the container image to Docker Hub - Exploring the image in Docker Hub - Pulling the image back to the local box Kubernetes - Introduction - What is Kubernetes? - Enabling a Kubernetes cluster in Docker Desktop - Installing the Kubernetes extension for VS Code - Declaring the REST API Kuberentes deployment - Creating a secret in Kubernetes - Declaring health probes - Declaring the REST API Kubernetes service - Creating the REST API resources in Kubernetes - Declaring the MongoDB Kubernetes StatefulSet - Declaring the MongoDB Kubernetes service - Creating the MongoDB resources in Kubernetes - Testing the REST API hosted in Kubernetes - Exploring the Kubernetes self-healing capability - Scaling Kubernetes pods - Adding logs via ILogger - Getting a new image version into Kubernetes - Load balancing requests across pods Unit Testing and TDD - Introduction - What is unit testing? - What is test driven development? - Restructuring files and directories - Creating the xUnit test project - Building multiple projects in VS Code - Adding NuGet packages for unit testing - Testing GetItemAsync unexisting item - Using the AAA pattern - Stubbing dependencies via Moq - Running tests in VS Code - Using the .NET Core Test Explorer extension - Testing GetItemAsync existing item - Using FluentAssertions - Testing GetItemsAsync - Testing CreateItemAsync - Testing UpdateItemAsync - Testing DeleteItemAsync - Refactoring and catching regressions - Using TDD to test a yet to be created method - Going back to green by fixing the failing test - Testing the new controller method in Postman Watch the course below or on the freeCodeCamp.org YouTube channel (6-hour watch). Video Transcript (auto-translated) You are about to learn how to use .NET 5 to create a Rest API. The creator of this course is a Senior Software Engineer at Microsoft and he is also an excellent teacher. REST API allows your app or system to expose its functionality to multiple types of clients both inside and outside of your network, including clients across the internet. This is what you would use if you wanted to write a program to collect data from say, Twitter, Yahoo, finance, or even NASA. If you're looking into building your own REST API, and you're considering the dotnet platform for it, please stay with me, as I show you how to do this end to end using the latest innovations provided by dotnet. Five, I hope you enjoy it. In the first part of this tutorial, you're going to learn the scenario to be used across a tutorial, how to create a dotnet five Web API project from scratch, how to use Visual Studio code for building and debugging the project, we're going to work on how to draw the development certificate installed by dotnet. Five, and that's going to be needed for HTTPS access and how to use swagger UI to interact with the API. To follow the tutorial, you're going to need a few things, including the dotnet, five SDK, Visual Studio code and some basic understanding of the C sharp C sharp language. Now let's talk about this scenario that we're going to be using as a domain for this tutorial. So let's imagine that we have some sort of a catalog system. And we have a bunch of items available in it. So in this sense, like I am, video, video gamer, so I like to think of these items as items that I will use within a video game. So items like potions, swords, shields and stuff like that. Right. So that's a system that we have in place, it has a catalog. And of course, we're going to have users that are going to be a would like to banish this catalog via their, their browser, right? They have a browser, they want to manage these catalog items, somehow. So these are they would they would like to do is well, how are we going to create items in the catalog? A How can we retrieve the list of items currently available in this catalog? hunka. We update properties of the items. And how can we delete items in this catalog. So as it is today, we do have the catalog available. But we lack we don't have a way to expose this catalog to the internet so that people can use go ahead and manage it from the browser. So that's where we're going to introduce our REST API for this catalog. And during this tutorial, we're going to see how to build this REST API from scratch using dotnet. Five. So here we are in business to recode. And the first thing we're going to do is open a brand new terminal. And this terminal, we're just going to switch to the directory, where we're going to create our project and create a project, we're going to be using the dotnet CLR. So to do that, we're just going to say that, that new and the type of product that we want that we want to create for our REST API, that's going to be Web API. And the name of the project is going to be catalog, hit Enter. And that creates your race all the files, face it on the web API template. So now I'm going to open that folder that got generated, catalog. And a, as you open a as usual, as you open a dotnet project in Visual Studio code, it will prompt you to add a few additional files for building and debugging the project. So I'm going to say Jess, and those files get d rated under Ws code. So the left side, you can actually see all the generated files. And let's take a quick look at each of these files as a quick lack of love around. So the first part we're going to look at is the ACS proc file. This file is used is this is called the project file. And this is used to declare how we're going to build this project. In this case, we're saying that we're going to be using the dotnet web SDK to build the project, which includes a bunch of tools and tasks to specifically designed for web kind of projects. The next interesting thing will be the target framework, a monitor or target framework, which in our case is net five. The target framework defines the API's or face or what kind of API's are going to be available to your project. In this case that five is perfectly good for us. And the next thing is going to be a bunch of nougat packages that we're not going to be diving into right now. But those are just dependencies that we already acquired on this project. Close that and the next we are going to take a look at this program. See His pronunciation is what we call the entry point of the application. And what this will do is just pretty much race or stand up the host. That I mean, the process is going to become the host of our problem. And it also declares a bunch of defaults. And it also sets up what we call the startup startup class for our project. So let's actually go to a startup and see what's going on there. Really, the main things and startup are that we have this property called configuration that we receive as part of the startup constructor. This is you can use anytime you need to read some configuration information from multiple sources, like from a environment variables or files, different kinds of files, or a bunch of other places, a configuration that you don't want to hard code is your service. The next interesting method is configure services. And this is the place where you would register all the services that you're going to be using across your application. And we'll talk about this later on in this video. And the last interesting piece is the Configure method. This is where we configure what we call the a pipeline that a request pipeline on ASP. net. And so this just defines a bunch of typical middlewares, which are additional components that will execute before your, before your, your controller or your your code actually executes. So each of the each of these can execute as a request comes into, into the ASP. NET process. And from there all the way into when your code executes. But we're not going to be exploring this part in this video. A couple of other things are so we have a weather forecast. So this is a model that gets out generated for this sample application here just have a few very simple properties here. And alongside this a this model, there's a controller. Now the controller in ASP. NET is just pretty much the class that handles the route. Yeah, pretty much the routes that a your service exposes, right, but we're not going to be using these in this video. So let's not dive too much into that. A few other files a upsetted. json, this is where you can declare configuration, that's going to be that you don't want to use hardcoat into your, into your, your program your your source code. So And right now, it just has some configuration for logging and the wholesaler allowed in the app. There's also a variant of appsettings JSON, which is absurd in development, Jason. So development, I mean, the fact that is that says a does say upsetting start developing that JSON means that we're running in development environment, these settings will take precedence on top of the opposite is Jason. So you could have a bunch of these appsettings files for each of your environment like production, test integration, all of these environments. And I'll be talking about environments may be a good time to take a look at the files era that VS code, which are a task Jason and logic a lot Jason does, Jason is just a file that declares the tasks with these key concepts and pieces to your code, you can declare tasks and a task is can be a bunch of things. And in our case, the most interesting does is the fact that we want to use run the dotnet build command. So dotnet build, which is going to be used for building our code. And in terms of launch the JSON, this is the file that controls what is going to be launched or executed when we do like an f5. Or when we start debugging the code in this case is already pointing to the right DLL for start to start debugging. Lastly, we also have launch settings. So Jason are really the only interesting part here that they're like to take a look at is the application URL. Here we are defining the URLs, URLs Imperial, for our application, in which case in this case, we're saying we're going to be serving our server in localhost 5004, the HTTPS version will be serving in which is going to be the default version is going to be 5001. We also declaring the actual a, a spinet core environment environment variable. And we're setting it as development. And so also, in business to the code. This is not the actual one that's been harder the one that will is going to be harder eating lunch, Jason. As you see over here. This is the one that takes precedent if it was to recode. So so that's good. Well want to do now is actually to test this this project just to make sure that everything is running as expected. So what I'm going to do is I'm going to switch to the debug hub. Hear me expand this a little bit. And so what I would do is just click and start working. Let's see what happens. Right. So a browser pops up. And then if you're getting these page here, a, what it means is pretty normal, it means that we don't have the self signed certificate that goes without net, it has not been trusted. Right? So there's a very simple way to go around decision and to properly trust the survey that comes with dotnet. So let me actually just close this, and stop. And let's switch back to the terminal. The actually let me open up a new terminal here. Yeah, there it is. So in order to trust a certificate that comes bundled with the dotnet SDK, what you have to do is just type dotnet, def cert, https trust. When you run this, you're going to get this pop up, asking you to confirm that you actually want to trust that cert, I'm going to say yes. And then that we should do it. So I'm going to run it again. Let's see what we get. Alright, so yeah, so we still are not getting pretty much anything here. But we are not seeing any trust issue anymore. Now if what we want to see something meaningful here, although it doesn't matter too much for us at this point, what you can do is just go to swagger. And then you're going to get this this nice UI. So this is what we call swagger are also an open API specification. So this is a component that is bundled now with dotnet, five, so you don't have to do anything to make it available. As you saw, we did nothing. So it's just there. In the slash swagger URL. What this does is allows you to easily describe all the operations, all the actions, all the routes that are available in your API, and allows you to also interact with them easily. So for example, if I just go to the get route, and I click a trade out, click Execute, it will go ahead and run it. And we can see already some results for that route. And then one thing that I like to do as I work on these projects, is to really not open the browser every single time that I run the project. So let's actually switch a little bit the behavior of VS code so that we just keep this window open. And then anytime we just hit f5, or hit Run, it will not open more windows. So to do that, I'm going to stop here. And we can go to launch the JSON and close this. The only thing that you have to do is just remove this server Ready Action section here. And that's pretty much it. If I run again, and by the way, you can do this by just pressing f5, which I'll do right now, five. That starts to host, as you can see, but we did not he did not open any more windows, which is fine. Because we have the browser ready to call right there. Then the last thing that I like to do in terms of a practice set up is to simplify how we build our project in pieces to record. So for that, let me minimize this and go back to business to recode. Stop this, close that out I'm going to do is to go to data Jason. And the only thing that I'm going to do is to add this little section here under the build task, which is just the what we call the group, which is going to build and it says is default true. What this does is that allows us to more easily build a project. So now I can go to let me just save this saved. I can go to terminal room built tasks and immediately builds. Without that, we're able to just have a pop up yet another menu to do the build. I can also now do Ctrl Shift B and it will do the same thing. So yes, that just speeds up our situation. In the second part of the net five REST API tutorial, we introduced the foundations of our API, which includes the core entity used to represent the items in your catalog, the repository class responsible for all items, storage related operations, and the controller that will handle all the requests sent to a REST API. Here you will learn how to model an entity via C sharp record types. How to implement an in memory repository. Sources and how to implement a controller with get route to retrieve resources. Alright, so now that we are comfortable with the initial setup of our project, it is time to start setting up the the entities and a repository that's going to be used to a store and retrieve the items that are going to use it across a service. So the first thing we're going to do is well, let's actually just close these and the terminal. And let's get rid of a few of these classes that really make no sense for our project. So I'll just delete weather forecast here. And I'll delete the weather forecast controller. So we can start cleaner than that. So let's introduce our entity, the item entity. So for that, let's add a folder here called entities. So people will say domain, as a lot of people may see models, in our case, entities should be good enough. Let's create a file here, let's call it item. That's Yes. Let's follow the right namespace here. So the next page should be catalog as he's wearing the ntds folder, let's say entities. And then what you would usually do at this point is declare a class, right, so you would say public class and let's say it. However, since a dotnet, five and a C sharp nine, there's a new option here for you, which is what we call the record types. So record types are pretty much a pretty much classes. But they have better support for immutable data, immutable data models, right, which means that once you get a one instance of this object, it is not possible to really modify it. And that's pretty convenient, especially for objects that you receive over the wire. So all of these are coming from, from the web, usually use one to take them and do something with them, but you don't want to modify them. Right. Also, record types have this thing called with expression of who you're going to see later on in this tutorial. And then also a provide ability to compare based on a value. So validated equality is what they call, which this means that when you compare a two instances of these a of an item, in this case, those instances will be equal, only if all of the properties of that instance are the same, as opposed to just the identity of the object itself, which will be the case of classes. So record types are pretty handy, I think are a great option for the for the objects that we're going to be using here, over here. So let's switch class for record. There, it is time to introduce the properties for this record. So let's add just a few properties here. So let's see. So let's use a good for our ID. And let me import that system, your system namespace was missing there. And then before adding more properties, let me actually make a small change here. So instead of using Get set, let's switch to it. So why you seen it. This is another addition in the in C sharp nine in dotnet. Five, which it's a great fit for, for a property initializers. That where we want to only allow a setting a value during initialization, right. So this means that, for instance, in the past, you could say you could say, Get set. What this means is that after you create the object, you can just modify in this case, the ID a time. So that's not really desirable, we want an immutable property. So for immutable, we will have to set privates, right. So yeah, so this makes it immutable. But now it is pretty challenging to construct any set of these objects. Now we have to introduce a constructor. And then our customers don't have a really nicer way to go through our objects. So to get into a good middle ground there, they introduced the the init accessor here. So this means that you can use a creator creation expression to construct this item object, as you will do with a with a set. But after the creation, you can no longer modify these property. So it's a very nice a balance between the two words in there. I will see how this plays out later on. So at this point, let's just define our properties. So let's see. Let's add Of course, name. Name. It's great to be studying name Oh, Also in it, let's add, let's add a price for our item. Price, also in it. And finally, let's add a time offset. This is great. So this is going to be the date and time where the item got graded in the system. Let's also not forget to change this to it. Now it is time to introduce our repository, which is the class that is going to be in charge of storing the items in the system. To keep things simple For now, we will only use an in memory repository. And a few episodes later in the tutorial, we will bring in a proper database. So let's create a new folder here called depositories. And here, we will add a new file. Let's call it hidden man itemtype was 30. The writing space here not forget that it's going to be catalog that people see 30s. Right. And now, let's create a class. So holy class, I'll just grab the name from the main file. Right? We're going to do here, like I said, this is in memory. So we're just going to define a very simple list of items that are going to be the initializers that we're going to be working with. So let's declare a lease here. So let's see write rate and make it read only because it should not change. I mean, the instance of the lease should not change after we construct this repository. object. It's good to be a list of item we used to fight him. And I think, yep, so these the item items. And yes, we need to import the couple of namespaces their collection generic for the least. And that other entities for the item. And we want to say this is new. And we want to declare the list. Now these one another addition in C sharp nine. As you see here in the past, you may have needed to say okay, so this is new list of item, right? But that's a bit redundant. Since we already know clearly this is a list of item. So why, why so much ceremony, so let's just remove this. And that's all you need to do at this point. So nice addition, C sharp nine. So let's add a few items here. So let's say new item. And let's, let's do the initialization here. So let's just do random go it. You go it for the ID. Again, let's import the museum a space. And so for the name. And so like I mentioned in the introduction, I like to play with these ideas in terms of video game items. So the first item that I'm going to choose here is abortion. Super classic in these video games. And let's say the price for that one is going to be just nine. And for created date. Well, I'll just say they offset it etc. Now. So that means right now in terms of UTC, so not the local time, just the UTC time. And do assess we need these one, let's add a couple more. So same a good. I mean, get a new GUI for each of these ones. But let's call this one. It's going to be a idles word, resort. And let's say it's going to be more expensive. Make it 20. And then for the last one, let's say we're going to do rose shoot. Got to be a bit cheaper, let's say. All right. Oh, there is we have our initial list of items ready to go. Now in this repository, we're going to have to deal with a bunch of things, right. So how do we get an item? How do we get a collection of items? How do we create an item update, delete all these things. So to get in simple, let's start with a get. So we're going to do to get metals here. The first one is going to be get items for getting items if we're going to do, we're just going to return an ienumerable of item. items. Right? So a nominal is pretty much the very basic item, it is a basic interface that you can use to return a collection of items. And then yeah, that's always got to be as simple as say, well, as yours return, whatever we have in items right now, it is that sort of get items method. And the next one is going to be similar. But this guy is going to return just one item, it's going to be named get item. But this is going to need to know the ID of the item to return. Right? Start. And then. So in order to retrieve the correct item, what we're going to do is you say Okay, so let's return from the items collection. And I'm going to say where these requires important yet another namespace sit in that link importing now. And so we're going to say, okay, so from that list, where the item ID equals the ID that we got in the parameter. And that's going to return a collection. But we don't want the collection, which is one, the one item that that he should find all the folder where the file is going to be? No. So if it finds the item, it will return it. If it doesn't find it, it will return null. All right, so that makes up our repository. And so the next thing to bring in is controller. So like I said, the controller is going to be a the class that receives a request that has been sent by the client and handles it properly. So let's add our controller class then. So new file under the controllers, folder, and scenes, the reasons we are dealing with here is a items. So the convention will be to just name it. Items controller. That's Yes. Right. And again, security right namespace catalog, in this case is going to be controllers, controllers. Alright. So this controller is going to be all the class items controller. And then the interesting thing about controller classes is that you always want to inherit from controller base that gives you and this also important namespace here. So that will effectively turn this into a controller class, right? So let's always inherit from controller base. That's the first thing. The next thing is to mark this class as an API controller. Right there. Yeah, API controller. So this brings in a bunch of additional default behaviors for your controller class, that just makes our life easier. So yeah, don't forget to add API controller layer. And yeah, and by the way, there's tons of documentation on each of these a attributes, or the next thing is to declare the route. So the route defines a, to which a HTTP route, this controller is going to be responding. And, by default, what you would put here is just the name of the controller. So if you do this, this will mean that whatever the name of the controller is, that's going to be the route. Right? And so in this case, for instance, let's say for a get, it will do get slash items, right? That's going to be part of the URL that we'll be using. So yeah, I mean, you can do it either that way. Or you can explicitly declare a route that you want to use, like, I could say, two items, which is perfectly valid. And in fact, let's stick with that. And let's move forward. Now, here in this controller, of course, for any action, or any operation we're going to do, we're going to be needing that repository that we worked on a moment ago. So let's bring in an instance of that. We're going to declare private read only. Again, because it's not going to be modified after construction. I suppose seat 3030. Right. And Yep, for any space we have ready. Now, before moving forward. Let me just tell you that we'll be making a few not so ideal choices as we move forward. Just to explain that A bunch of concepts, right? So the fact that I'm introducing explicit dependency into i ng meme it suppository. It's, it's not ideal, but I just want to do to keep things simple and then improve as we move forward. Right? So those just don't take this as a final word on how you should do this. Now, we're going to construct these in the in the constructor of this controller. So let's add a high def controller as the constructor. Okay, and then let's say yeah, so double storey equals new name. It was, right. So boom, we have a suppository right there, ready to be used? So let's define our route state to find a route. So let's see. How do we find a route to retrieve all the items? On this storage? let's declare a method called Hi enumerable. Item? Sorry, item, get items. Okay, so these are methods that's going to return an ienumerable of items just like the repository. Let's import the right namespaces. Are we missing here? Okay. But then also, in order for, for this method to actually become a route and react to some HTTP verb, you have to declare it the right, the right attribute in this case, HTTP GET is what we what we want to declare for this. So by doing this, it means that when somebody goes to perform a get against slash items, this is a method that's going to be reacting to that, right? I do see how a few cases we pretty much have the same route, but it is the verb that makes a distinction into which method is going to be invoked. Then what do we do in this HTTP GET? So fairly straightforward, we're going to say, Okay, so we have items is going to be a depository. You remember, we created these get items method. So we just invoke it, we have the items, and then we return the items. And that's all it is. Okay, so with that, we should be able to test this out and see how that goes. So I'm going to hit f5 here. Alright, going to go back to swagger. And I'm going to use refresh the page that we get open from the previous video. As you can see, everything got refresh. Now there's no more weather controller. Now we have an item's controller. And we have our first route here we use a get for items. We not only that, we also have a schema that describes a an item, how it will be laid out. If we click on items. And let's see, try it out. Let's see what we get. And right here, as you can see, swagger will show the the router boot executed, like we said, it's a get on slash items. This this is here, this is our host and the port. So against localhost 5001 items. And here's the result. So we have our three items that we declared as static. Well, the initial value for our items collection, right? Or the potion, the sword and the shield, right? This is working great. Stop this and add our second route, which is a route to return one specific item. So this is going to be public item, get item and then we receive good, right? And then are we missing any space? Again, let's see. Yes, focusing in a space. That's where it is. And then just like before, we just say, well, var item equals repository dot get item. Okay, so here's the other method that we added to the repository, we just pass the ID, and we return that item. Now, again, we need to mark a top like that right bear here. So it is going to be an HTTP GET. But in this case, there's a little additional detail, which is the template. So we have to provide a template where we specify how we're going to treat another piece of the route. Like in this case, the route is not going to be just get slash items. It's going to be good slash items. And the the idea of the item, right, which is is that piece of the big plate, I was just going to put it like that. So would you request the items is slash rF cific item ID then this This piece is going to get executed. Right? So yeah, let's see how that goes. I'll do f5 again. Okay, this is running back to swagger. Got to just refresh the page. And as you can see, now we have our second route available. Like I said, this is slash items slash ID. So, in order to execute that, let's Well, let's actually execute the first one items to get a list of all of our items that we know about. And let's grab the first one. so dearly, we should be able to get that item via the the other route. So gateway ad, so let's try it out our basic item here, so these how in open API swagger, you can introduce values, right? And now execute that, see what happens. So here's the executed route. So you can see slash items and the slash the actual ID. And then interestingly, we are getting 204. Right? So this means that something didn't go quite as suspect. What I'll do is I'll go back to Visual Studio code, and I'll put a breakpoint over here, see what we're getting. So go back to swagger, UI, and execute. Here, we got a breakpoint. And, right, we're getting No, that's what's happening. So the item has not been found. So why could why would that be? Well, let's see. Here's our items. And here's our get item. I made that. And so, yeah, so really, what was happening here is that anytime we make a request to this to our controller to our, to our service, we are actually creating, as you can see, over here, a new instance of the in main items are positivity. Right? So that means that he's created, a brand new list is created with a random set of new codes here. And of course, when we try to use our previous use it good, it will not find it, because now we have a brand new list. So I'm going to do a five, yesterday go and this is a good actually a good thing, because you have to realize that we need to deal with that situation properly in in the controller. So in this get item method, we should be a not just returning an All right, so how do we handle this? So let's stop it. So I think that we probably want to do is to return the proper status code HTTP status code in the case that we can find the ID. So let's say so if item is no all right, so let's return it something different. So let's return not far. So that's the way to actually ask a dotnet to create the proper status code for not found so we don't have to actually figure out so I set a status code. And then yeah, if it is found, they will just go ahead and return the item. Now we do have a problem here. Because now a in one branch, we're trying to return this type, or not found result in these other graduates right to return just an item. So what is it going? I mean, it's not like in it, right? We expecting to always return an item. How do we deal with this is a by the use of the action result type. So if we do action result, that actually allows us to return more than one type from this method. So as you see, there's no more errors, because now this is saying, Okay, if if if you want to return not found return not found, or if you want to return the type that is in the a direct tie right here, you're also able to do that, right? Or we're going to also say something like, Okay, if you wanted to, that's probably fine. But now in this case, we can handle both cases. So let's run this again, and see what we get used to get the proper status code for each of these actions to be properly restful. So let's refresh this. Let's again, let's get one of these items are going to try it out. Execute. So good. Yeah, can you just get one of these we know it's no good to find it. But get that good. And then open up here, try it out with ad and execute. So this time, we do get a 404, which is the correct status code word for not found, as you can see here, in this third part of the dotnet five REST API tutorial We learn about the dependency injection technique, and how to leverage it to properly inject a repository instance to the items controller. We also introduce the concept of data transfer objects, and how to use them to establish a clear contract with our API consumers. Today, you will learn what is dependency injection, how to register and inject dependencies in dotnet. Five, how to implement data transfer objects, also known as dtos, and how to map entities to details. In a previous video, we were able to actually create our entities, repositories and even our controller to be able to get items and our specific item. However, we find an issue where we try to retrieve an item, we can retrieve it, because as we found and just go back to the code, anytime we receive a request, in our items controller, we are creating a new instance of depository. And that's bringing a bunch of new items in such a way that we are never able to find, right. So how can we go around it? I mean, how can we actually fix this the right way? So for these, there's a pretty important concept that we need to learn here, and which is called dependency injection. So let's talk about that. So what is dependency injection? Let's think about our class, right, so we have a class, which wants to make use of some other class, where we have this kind of relationship, we say that this other class is a dependency of our class, right. And, in more concrete terms, in our case, we have the itis controller, which is constructor is a creating a new instance of the repository ready in meme items repository. Now, what we really want to do in terms of dependency injection is flip things a little bit. And instead of have a test controller construct that instance, and I'll just open up my highlighter here, we will receive the repository in the constructor, and then just take that, that, that reference into the class. So at this point, we are injecting the repository dependency into the IDS controller class. Now this is also brings in something very important, which is the dependency inversion principle, in which again, so we have a class, and we have some dependency, let's call it dependency a. And well, this class depends on dependency a, but what we want to do is just not take that kind of dependency, and instead, have our our class depend on an abstraction, which is, in this case, in C sharp, it is an interface, right? So the class no longer depends on dependency, it just depends on some interface that dependency a will implement. Right? So we have inverted the dependency by having a class only depend on an interface and dependency a implement that interface. At the same way, I mean, as we do that, we could bring in a dependency or any other dependencies that also implement interface. But in this case, you can imagine, now the repository that I just control receive is just an interface. So class in this case, has no idea of which explicit dependency it is working with, could be a B or any other dependency, as long as they implement the contract, which in this case, is the interface. And this instruction class is very happy to work with it. Okay, so that's, that is the dependency inversion principle. And well, the thing is, okay, so why why do we want to do this? Well, really common reasons. And yeah, like I said, like he says, right, so by having our codependence dependent upon abstractions, we're decoupling implementations from each other. So it gives us much more freedom in terms of moving around these dependencies, without ever having to touch our class. And this makes the coal cleaner, easier to purify, and much easier to reuse. But I'm very wary, so much easier to test. But then, if we're going to do this, how are we going to construct these dependencies, right, because now we're just receiving them in the constructor. So if we have all these dependencies, dependency ABC, how are we go the constructor constructor. So because our class was to receive them, right? They were going to inject them there. So comes into play this thing called a service container, which in terms of a dotnet five is an AI service provider. So what happens is that a during a application application startup, we're going to register, each of these dependencies are going to be registered into the service container. And then eventually, when the class gets instantiated, the service, a service provider separate container is going to take care of resolving any of the dependencies needed by this class, like it has a map of all the dependencies are needed by each of our classes. So resolve the dependencies, construct them, if needed. Only the first time, of course, depending Well, actually, depending on the application lifecycle that has been set up for those dependencies for the class. So if needed constructors, otherwise, it will reuse it. And then it rejects the dependencies. And this is, in fact, what's going to help us with little problem that we have right now in the inner project where we want to be constructed and constructing I mean, we don't want to get a split dependency on the regulatory, or we don't want to construction, explicit construction of warnings as every time we created the controller, we just want to receive an East as if it's available, a lot of constructed getting constructed first time and get it all sorted by the service container. Let's see now how we can use dependency injection to our advantage. So what I'm going to do is I'm going to get back to the code. So let's stop debugging close terminal. And so let's fix the situation where we have this explicit dependency on email it depository. So firstly, we're going to need is some interfaces so that I just controller does not really a operate on concrete instances of the depository. So let's go to a main idea posit Ori, and we're going to do is just right click on the class and actually in the light bulb, and let's extract interface. So that's going to create a interface for us and makes it makes it possible to implement that interface. Now, we probably want to take the interface out into its own file. So let's do that. A new file, let's actually call it a I items depository, should be a better name for this. Okay. And so thanks, space catalog, dipole stories. And here's where we're going to bring in our interface, I'm going to use cut and paste here. It is a report a couple of nice spaces, let's see, for the entities. For CS for good. Collections generic, that should do it. Alright, so we have our interface. And here's the repository. repository implements interface. So now that we have the interface, let's go back to our controller. And let's switch this into I mean, this type into i a items of repository of policy items. For seat gaudy. Make sure this is off. Yeah, we have to do the right naming here for that game. And now we've got the receive it here. So I demonstrate depository. This is a boss story. And then just to not confuse things, let's say this, that repository equals depository. Alright, so yeah, so now we got the pennsy injection working here. And no longer This class has any idea of which repository is going to use behind the scenes. Now, the only thing we have to do here is to what's going on here, actually, I was just fixing that in our laboratory. The other thing is that we have to do the registration, right. So to do the hyperinflation of our depository, or we're going to do is go to start up, configure services. So this is the place where you register all the services that are going to use it across your service. And the service that we need now is our history. So let's do services that add Singleton. Now there's a bunch of ways to add a URI. To register your services here, I'm going to be using a singleton so and a singleton is nothing, nothing else, other than just having one copy of the instance of a type across the entire lifetime of our service. So only one will be created. And it will be reused wherever whenever it is needed. So that's going to help us resolve the problem that we have today. And so to add the singleton fares, we specify the interface. So I added repository, which we may need to add. Yes, we namespace. And then so that's the interface. And then the concrete instance is in main items repository right? That's it. So that's how you register your dependency. And so at this point, we should be ready to be ready to go. So I'll do a five. And now I'll switch to swagger. So we have the same API as before, I'll refresh anyways. And then let's try an exercise now. So let's see, I'll try out our items, endpoint. So I'll get one of our items. And I should be able to find it now. So see, items, Id try it out. I'll put it here and there, let's try to find it execute. You have a breakpoint here. Let's see. Yes, this time, we can resolve no more, no, remove that breakpoint, run back to swagger. And then here it is, we got our response code 200, for the request of that item, and here's all the body that is crucial. So as expected, now we only have one copy of repository hanging around, which is injected into the controller, and that allows us to actually find the data we're looking for. Now, there's one more thing to notice here that we should fix right away. And which is the fact that these these routes that we have enabled right now are enabling a or are exposing our item entity directly to the outside. And we have to understand that as we build REST API, we're also establishing a contract with any of the clients that we're going to be using, which is a contract that we should not be breaking easily. And the problem that we have right now is that since we're exposing item, which is the item that we're using for dealing with persistence, we have versatility. Anytime we want to add feel, I mean, anytime we want to modify or remove any of the fields that were that we're using in our inner storage, right now, in the versatility, we can potentially break our clients, right, break that contract, which is really no goal for us to build these REST services. So how can we avoid exposing these item contract there? So let's, let's take a look, let's go back to the project. Let's actually find that entity. So we have item here. And as we said, we are returning it both in get items and get the item. So what we're going to do now is introduce what we call a DTO or a data transfer object. So data transfer object is nothing else other than the the actual contract that's going to be enabled between the client and our service. And to do that, we're going to do introduce a new folder here. Let's call it videos. And let's add a new file for our item dt. All right. All right in the deal. So again, namespace catalog, in this case is going to be videos. And the identity is going to be fairly similar to our item, actually. So let's want to just copy the item. And so going to add missing spaces. here and there. Yep. And, yeah, I mean, in this case, it happens to be that the item that we want to return in our methods is pretty much the same as the item that we will be storing in a repository or retrieve the depository. So we use, okay, seems a bit redundant right now. But the benefits become evident as you move forward as you start modifying your database. You don't have to be touching this contract, or you can be very careful with the contract, or supposed to be breaking our clients anytime. So this gives you a lot of flexibility as you evolve your data store. So now that we have, actually let's rename this to item DTO. Sorry for that. Okay, I think the deal. And now that we have that, it is time to start using it right, so let's go back to iTunes controller. And so at this time, what we'll need to do is to convert the iTunes or we're getting started with good ideas, right, we have to convert these in from item into identities. One way to do this would be to just do a simple projection with link. So we would do a select and then maybe missing the link a space here to add it. I'm going to say okay, so I tend to project into a new item DTO and I may need to add any space here. There it is. So here we're going to bringing the properties, right, so I'm going to say alright, so Id is equals item.id. name equals item name, same thing. Price. Okay, so now we have a our items collection is a collection of items, we do think we're missing parentheses here. And we return those items, no longer item, there has to be item B to setting up the contract. Okay, so, yeah, so that should do it, we have to inform the item, do it and do. And as you may guess, we have to do pretty much the same thing over here, right? This point, it will be a bit redundant, right? So why will want to do this transformation twice with exactly the same properties. So one way that we can overcome this is by adding an extension method. So let me show you what I mean by that. So I'm going to add a new file here, we're going to call it extensions. Games. So good luck. And then what extension does addition metal does is it just will extend the definition of a one a type by adding a sum a method that can be executed on that type. So in this case, we're going to add a class only static class or for extension methods, you have to use a static class, there's a way to go, extensions. And then we're going to declare one method here. public static is going to return item DTO. And we're going to call it as DTO. What is going to it's going to operate on the current item does, that's what this method means. So again, let's add some namespaces here. So this method receives an item right, by by using this here, it means the current item can have a method called as DTO, that returns its identity or version. So at this point, we can probably take advantage of what we did here. So let's see, this is what we used to create activity Oh. So we can say well return new identity or out of the item that we received. Ladies, we have an efficient method ready to be used. So now we will go to adjust controller, what we can do is instead of all of this, we can say so item is projected into it, and that as the deal. That's all it is. Let's collapse this a bit. With that, we can also use the same method over here. So when we get the item, we will say as you do, of course, we need to change this into our do contract. And then the rest. Actually, I will do this. So let's just get the item first. Check if it is no, if it's not, then we do the CTO. Okay, so now that we have done that, let's see how that goes. So I'll do a five again. Okay, back to swagger. And I'm going to refresh this. And let's see if this still works. So items, I'm going to try it out. Execute. And yeah, just before we can get the list of items. But this time, if you scroll down, you will see the disclaimers. The contract we're exposing to our consumers is no longer an item but it is item to do with the properties posted right here. In these four parts of the dotnet five REST API tutorial, we introduce additional controller actions for creating, updating and deleting items. We will also learn how to validate the incoming dtos to prevent invalid data from landing in the service. Today, you will learn how to create resources with post how to validate the values of DTO properties, how to update resources with good and how to delete resources we delete. It is time now to introduce the rest of our, our routes, right so route for both to create an item, route for update, delete, or update the item and the route for Delete to be able to delete a date. So let's start with post. Right. And before doing anything else, what we're going to have to do is to update our repository to be able to have that create that route for creating an item right So let's do that. And I'm going to start again, by going to the interface, that's the first thing to do. And so let's declare void, create item, item item. Okay, so this new method just returns nothing. And it only just received the item that needs to be created into the depository. Now let's switch back to the concrete in main, it depositories. And I'm going to say, implement interface. So that brings in a new method right there. And CNC turning memory depositories, this is as straightforward as just saying items that add item. That's all it is. And then now we want to expose these into the controller, right, we start to add a route the controller. But before doing that, we got to realize that so the client is going to be sending these, these items. And we will have to establish another contract for receiving that, that item, it cannot be identity or because we don't need as many properties as in identity or for the creation of an item. So let's see what I mean by that. So I'm going to go to our details folder, I'm going to create a new file, let's call it create identity Oh, and add the space catalog that videos. And then. Okay, just like before, we're going to be using record for this pretty convenient for the tiers. And so now I've looked back at it to, let's see, so what will make sense to be sent by the client as we create an item. So normally, the ID is auto generated in the server side, right? So we don't need to be passing in that ID, we do need a name and a price. And likely the created date is going to also be generated on this service. So we're only going to include in these two lists. So we have name and price. And that will be for our create item DTO. And now let's see how we can use it in the controller. So back to the controller. Let's see how we declare these a post route. So it's going to be public action result. Because again, we could return more than one thing in this method, things could happen. And they call the convention for a post or a create method is to create the item and return the item that got created. So if we're going to do that, we're going to we should be fine to return the identity. Now that the conventions here are going to vary. So some people will create their own response object here, it doesn't have to get into to it happens to me that it works fine for us in this case. So that's okay. So it's going to be called right in grade eight MBT Oh, that's going to be our input contract. Item BPO. Okay, and then let's qualify these with the right verb. So each HTTP POST, and then just for the communication will say so yeah. So this is going to be invoked when somebody does a post into the items route with the correct body, of course. So how do we create an item? So very straightforward, we're going to say, well, item, item equals new, we will have to find the type. So thanks for sharp nine. And then yeah, so let's just say ID equals, here's what we actually generate the ID for the item. So it's going to be good, that new good. So the name is identical to that name, same for the price. Price, and then the created date, as as you would expect a time offset that UTC now, that's the item. And now we have to build we'll take advantage of the repository method we just created. Create item, and then it goes there. And then once the item has been created, a convention here is to Yeah, I mean to return the items that were created and also a to return a header that specifies where you can go ahead and get information about that graded item. So to do that, what we can do is use Created add action, you can also use create route, that's another way to do it. gradient action will work fine for us. Because what we can do here is say, Okay, so what's the action that we want? What's the action that reflects the route to get information about the item. And that's going to be our get item action right here. So what we can do here is say, well, there's going to be the name of get item. And then when you specify the ID, that's going to pass it to that order route. So for that, let's create just a simple anonymous type here. With ID equals ID and ID. So that's a generated ID. And then finally, the actual object that's going to be returned, which is a thing. And again, let's take advantage of our extension method as DTO. So we take the identical created, and then we just converted yesterday to. And yeah, that's it. Let's do f5. See if this works. So back to swagger. Let's refresh this. So now we have our post route over here, as you can see, and also our grade identity is showing up as a new contract that we're exposing torque lights. So let's go to post. Try it out. And as you can see, now we only need to provide a name and a price. Let's see for the name. But let's see, let's bring in something like another type of support, I guess, for let's see, a de neumes sort to be a bit expensive, let's say 35. And yeah, so let's start let's execute, see what we get. So as you can see, here's the request URL the same as the get. But in this case, it is a post, we have guarding 201, meaning a created art route. So he got created a new sort. And as you can see here, we have a location here that specifies Where is that we can find that item. So if we actually take this a these code here, we go to our collapses and go to our get route. Go to try it out. We're going to paste that here. Execute. As you can see, now this is the route that was provided in the location here for post. And it actually is able to find a developer a new source we just created. And in fact, his use case, get the full list of all the items. Try it out, execute. So now we don't have your three we have four items, including the deadliness. But then let's also try one more thing. What happens if I try to create something without a name? Does that make sense? Well, let's try it out. There's the V that that was accepted. And now we have an item with a no value, which is totally unacceptable. And and again, in fact, we use code to the get route and we say, execute, we can see we have an item with no, which is pretty bad. How can we protect ourselves against that situation. So there's this thing called a data annotations, which is something we can add to our DTO in this case, to prevent that situation. So back into create identity, oh, what we can do is just request that this field is required. And I'm going to add the data annotations namespace in there. So it name has to be provided, and price has to be provided. For price, don't just add, let's do one more thing, let's say there's going to be a range of possible values for price because we should probably not accept a negative value or even zero here. So let's say that we're only going to set values from let's say, from one to 1000, that should be a valid range for us. So just by doing this, we are protecting the values are going to be coming into the controller. So I'm going to do a five again. And let's see how that goes. So back in swagger, I'm going to be collapsing this route. So back in post, I'll just try to do the same thing again. Try to execute this. And this time. Now we have a 400. So bad request error. And clearly it says here the Name field is required. So now data validations are coming into place. And so we must provide a name. Let's actually play with the price here. Let's say I try a negative number. Right see what happens. If you have price must be between one and 1000. Right. So data notations for valuations pretty useful for relating dot r or D do Now it's time to implement our update route. So let's go back to source code, close terminal. And just like before, let's go back to our a repository, I identify the interface and add the relevant method. So let's say this is going to be a void. Again, update item. And this is going to receive the item to get updated. Very similar to create item. Now, back to the concrete implementation. I'm going to say, again, implement interface that brings in the method data item. So how would we update this item. So since it is an in memory list, really, the only thing that we have to do is use find the relevant item and update it with the incoming item, right. So to do that, let's do this is find the index of the relevant item. So I'm going to say items, find index. And then so this is the existing item. So you're going to find the existing item where existing item ID matches item.id. Okay, so that's just finding the index of the of the ID that we're looking for. And we've found it, we can do items, index equals item. That's all it is. So we will update the item in the right location. So it's time to go back to the controller, well almost like to go back to the controller, because, as you may realize, at this point, we do need some video to receive the input for the update route. And even when that disables, you're going to be pretty much the same as with great identity, oh, these are good practice to actually have a another a video for this case, because you don't know right now is the same thing. But eventually, it could be that an update means something different than accurate. So let's use to update identity Oh, that's a copy of great identity, oh, pretty much has the same properties is the only thing that you can verify the name and the price. And required and the range, right. So now let's go back to the controller, right this controller, let's create out of the drought. So this is going to be again, public action result. In this case, a convention for output is to actually not return anything. So use what we call no content. So it's going to be no type here other than action result, it's going to be called update item, we receive two things, the first thing is the good of the idea of the item. And then they are new update item DTO. Let's call it item DTO. And then, let's not forget to add the correct verb here is an HTTP put. And just like we did before, the route is going to be just for documentation, when you to put into slash items, and then slash that's the piece that we're missing actually here, we need to also specify here the template which is in this case is the ID. So that means that when when we do a put, we have to certify the ad in such a way like these, right, so put items slash the ID, and they will hit this method here. So let's see. So first thing, so how we will do an update, first thing to do is a Find the Item. So existing item, it will use a repository for that we already have a method for this, which is get item passing the ID. And then it will be great to verify if this ID if these items actually exist. So if an existing item is no, then well, we couldn't find it. So we will just return not found. And at the end of story for that that branch. And then if we find it if we found it, well, we're going to do is just proceeded to do the we're going to create a new item, which is the updated item in our system. So in this case, we're going to say is item updated item equals it essentially our existing item. But with a couple of differences. Like we need to use a the name of the provided identity. Oh, and the price of that also provided identity. Oh So, now here, I just use one 190 of a record types that I mentioned when I was talking about record type, which is the width expression here. So what's happening here is that we're saying, Okay, so we're taking this existing item here, are we creating a copy of it with the following two properties modified for new values. So that's a very nice addition into records, and allows me to use what is really an immutable type. But still, I can go ahead and modify a some properties on initialization. So if the item is just a copy of existing item with a bunch of properties, like nice addition, in record types, where we have this updated item, we can go ahead and say, okay, so repository that updated the method that we just created, and send the bladed item. And like I said, the convention is to return no content, so nothing to report just returned. Let's try this out. f5. And back to swogger refresh. So here it is, our put our port route. And before doing a port, let's actually get a one of our a items. So try it out, execute. So let's say we're going to modify our potion here. Okay, so the potion, I'm going to collapse these up and put, so for put, we have to provide an ID, and updated values here. So this is a potion, let's actually rename it to, let's say super potion. Let's bump the price to I don't know, let's say - So execute. And then just as expected, we get 204, which is no content. And you can see the route that was executed here. And then if this succeeded, we should be able to get a updated version there. So I just get the full list of all the items that we have. Now let's see what happens. And there is no longer potion super potion with updated price. Also, notice down here that we do have a this update identity are available now here, the new contract. So we'll update really, the last thing to add is our delete route. So let's go back to controller. So back to the project. Just before, back to the repository interface. Let's do void. The title, we already already know we need for the reading item is just to know the idea of it. So back to the repository. let's implement the interface for delete item. And actually, the item is going to be very similar to update item, first thing that we have to do is find the item, I mean the index of the item. And now we can just say items that we move at. Look at that index. That's all it is. Sorry, we have to say it here. We had the opposite already. And now we can look forward to the controller. In this case, we're not going to need another DPO. Because the only thing that's needed here is to use a simple ID. So let's use implement the controller action. So public action result. Delete item, just like with update, we're going to return no content. So action result delete item, good ID. And let's add the verb. So this is going to be an HTTP delete. Again, documentation. So these are going to haunt or delete slash items. And then slash, let's not forget our template, which is the ID slash items ID. And to perform the deletion, similar, certainly with similar to update. So let's try to find the item first. And we'll just copy that base there. So not found if we can't find it. And then we go ahead and to repository, that delete item and it just like we did before, return, no content and that's all it is so f5 and by swogger refresh again. And now you can see we have our delete action available. So let's come to the name of one of our items and see if we can delete it to execute this. So let's try to delete that potion, copy, collapse, expand, try out, put ad and execute. So here's the route. We got 204 is expected, no content. So if I tried to get the items again, let's see what happens. All you have to, so no more potion habido here. And yeah, so that will be at the end of our routes. In this episode of The dotnet five REST API tutorial, we will see how to start our entities in a persistent store. Specifically in a MongoDB database, we will implement a simple MongoDB repository that can replace our existing emancipatory with minimal changes to our service. Today, you will learn how to implement a simple MongoDB repository, how to run MongoDB as a Docker container, and how to use postman to interact with the REST API. Starting with this episode, you will need a couple of other things to follow the video step by step Docker, which we will use to run a local MongoDB instance. And postman, which we'll use to interact with the rest API's from Iran. Now let's think about the scenario as it is right now. We have our user who is trying to manage his items via the browser. And he will do that by reaching out to our REST API. And more specifically, by reaching out to the IRS controller, which is where or all of our routes let at this point. Now, I just controller will interact with the inmate item depository to manage these items. And the items are actually stored inside the main depository as a simple items collection right. Now, what happens if the REST API for any reason stops, either eat stops or is restarted, and it could happen, either explicitly or unintentionally. But it is a really common scenario that a service would need to be restarted. If this happens, of course, our items collection is going to go away, because it's just a collection in memory, right? This is all desired, we need to figure out a way to keep these items alive beyond the lifetime of the REST API. So what are these, we have a few options. And I can think of first very basic option will be to using files. So you can think of, well, I'll have one file for each of the items in the repository. But really, the most common option these days would be to use a database. And in terms of databases, we have 1000s of options. But you can categorize them into relational and no SQL databases. In this tutorial, we will go for a no SQL database. And the reason for this is well, because of the benefits that it offers, beyond the fact that no SQL databases are one of the most popular options these days, there's the fact that you won't need a schema or SQL to interact with the database. I mean, you don't have to learn SQL yet another language here, you can just stick to your object oriented programming. And in our case, today, she's C sharp API's. And you also have low latency, high performance and these because there's no need for strong consistency as it as it would be in a relational database. And also, these are highly scalable. In our case, we'll go specifically for MongoDB, which is it is a no SQL database, and specifically is a document storage type of database. So it stores a the entities as documents, specifically as JSON documents inside the database. So this is we're going to use for this tutorial. So you can think that now we will have this database living outside of our race API. And now, when a controller receives a request, it will actually hand it over to a new repository called a MongoDB. I just have visited it, that's what we're going to create here. And even if our services stopped and restarted, the database will not be restarted at all, our data will be saved in there. And that way, we can keep our items beyond the lifetime of the REST API. Before we start implementing our MongoDB repository, I wanted to show you one more tool that you will probably find useful as you interact with your API's and they want to so is postman and you can get it in the postman downloads page. If you had no done already? And why would you use postman for. So if you remember, so far we've been using this page, the swagger UI for interacting with all of our API's. However, the problem here is that eventually you may not want to be opening, you know, web pages do interact with each of your API's. And these API's may not even be in your host, they may be somewhere. So what else were you there may not be a swagger UI. So you do need a way to interact with them. Plus, you may need some additional capabilities that are just not available in this page. So that's where postman can help you. So in this case, let me open a postman right here. So how we can interact with your APIs in postman. So it's as simple as clicking the plus sign here. And the first thing that you have to do is pick a verb that you're going to use. In our case, let's just try I get that you're going to read the request URL, all of those URLs are going to start with your host. And so in our case, let's see what's your host, let's do an f5 in VS code. And as you may recall, our host Ace and is one of the last lines here for the HTTPS endpoint is going to be localhost 5001. I'm going to copy this back to postman, paste that. And then if you remember, our route, going back to VS code, now, our route is a starts over route, start with items right, right here. So that will be the route that we want to use in postman. So just type here, items. And that should be enough to perform I get. So I'm going to just going to see click Send. And then if you get this problem here, this issue that says SSL error, unable to verify the first certificate, this is because of the SSL verification that postman is performing. But this such verification will just not work with the self self signed certificate that comes with dotnet five. So in this case, what you want to do is just disable SSL verification, and that should be fine. So you can just click here. And that will run the request. Again, as you can see, it ran the request. And we have the resource over here. Same results that we had in swagger UI before. But now, we are interacting more directly more directly with that API, the same way that we need to get you can do post put and a bunch of other verbs here. We will do so as we move forward with this with this episode of the tutorial. So now let's go back to VS code. And I'm going to stop the host here and close terminal. And I'm going to close it with controller. So the first thing that we want to do is to implement a new repository to be able to interact with a MongoDB database. For that, I'm going to create a new file. We're going to call it Mongo DB. Items repository. Right. Thanks space. Got a look. depositories game. So it's going to be called for league class MongoDB. depository. And just what are your sweet as with our email it suppository, we are going to implement items repository. We may need to import a namespace here, I will implement the interface. And just by doing that we have VS code has scaffolded all the methods that need to be implemented to comply with these interface. Now in order to interact with MongoDB, we're going to need a what is called a MongoDB. client. So the client is is a component provided by the creators of the owners of MongoDB that you can use to interface will be kind of the adapter that used to interact with MongoDB. So we'll need to inject that a as we as we everything else, we need to inject that dependency into our repository so that we can interact with it. So the first thing I'm going to introduce here is our constructor. So let's see. folic MongoDB is capacitor. And here is where we need to receive an instance of our MongoDB client. Where do we get this MongoDB client from? So to do that, we'll have to add a nougat package. Plug the nougat package what I'm going to do is open up a new terminal and here I'm just going to die dotnet package MongoDB that driver, enter, that's going to go to noget, grabs the MongoDB nougat package. And if you go to catalog CS Pro, you're going to see that now we have, we have the dependency right here. Oh back to the repository, we are able to start doing the injection. So let's see, we're going to receive here in the constructor is what we call an eye, Mongo client, to listen port import the correct namespace here MongoDB driver, and we will call it Mongo client. And now what is it that we're going to store? We're going what we want to store here is not really the client, but what we call a collection. So the collection is the way that MongoDB associates all these entities together. So I'm going to declare a variable here. I wrote it with only because we only modified in constructors is read only variable, I Mongo collection. And that you have to specify the type that that of the items, the type of the entities or documents, actually in this collection, our type is going to be our item entity. And his colleague, items collection. However, before we can get a collection, we need a couple of other details, which is the database name, and the collection name. So usually, like all of your document, yeah, all of your documents are going to be a grouped into collections. And you can have one or more collections in a database. So the first thing we have to add here is the name of our database. So let's just add a constant here is call it database name. And probably a good database name here would be use catalog. And now let's add a collection name. So private string, collection name. collection is going to be called items. Now that we have these available, this go back to constructor, and we actually close the terminal for now. And what we can do is the following. So first, let's get let's get an instance, let's create a reference to the database. So I'm going to say I Mongo database database equals Mongo client that get database. So database name. So that will get us a reference to that database. Now we need a reference to the collection. So items collection, is the variable that we say that we declared before equals database that get collection, and then the type of the item and then the name of the collection. And then the good thing about this is that both database and the collection will be created the first time that they are needed. So it doesn't matter which API we use to interact with the database and collection MongoDB. Or I guess the driver will detect if we don't have them, and they will be created automatically for us to we don't have to worry about it. So we have a few a few methods to implement. So to get started, we'll go for the Create item method. And we'll start implementing one by one and exercising each each one as we move forward in this video. To implement create item, what you want to do is just make use of that items collection. So you can say, items collection that insert one, and then you just pass the reference to the item. So in this case, it will be just item. So at this point, you may be wondering, where is this database is MongoDB database that we're going to interact with? Because Yeah, I mean, we have the code here ready to create an item, but we don't have a database. So there's a couple of ways to get a MongoDB database into your box. So you can either install the database via the MongoDB installer, or you can run the database as part of a Docker container. We're actually going to go for the second one. And the first concept to understand on that side is a Docker image. And I mean, we're not going to go deep into Docker concepts here where we're actually going to talk about that in a future video. But for now, you can think of our Docker image as a standalone package of software. That includes really everything needed to run an application. This application in our case is MongoDB. So everything is packaged in this Docker image. Then, when we run or when we execute this Docker image, it becomes what we call a Docker container. So is a running instance of a Docker image. That Docker container is going to run in the Docker engine. So how do you get this Docker engine into your box. So you just go to the Docker download page, which I can show you now, right here, did you go to this page, you pick your platform, and then you can go ahead and download and install Docker in your box. Then you have a Docker engine. And you're able to run any of the Docker images available publicly, like MongoDB, or perhaps some private Docker images that you may be storing in your own Container Registry. In this case, we're going to go for the A MongoDB, a public Docker image, let's see how we can acquire it, we can run it. So first thing we're going to do is go to terminal, say new terminal, we're going to type the following Docker run, then we're going to use the dash d dash dash RM modifier This is so that we don't have to attach to the process. So we just let it go. And RM is so that if the image is actually sorry, the container is destroyed after we close the process. So then, we're going to give it a name, Mongo so that we can easily recognize which image is this. And then we're going to open a port, that port is going to be 27, zero 1727, zero 17. So this syntax here means that we want to open, let's say, we're going to open kind of a window or a view into the Docker container. MongoDB usually listens in Port 27, zero 17. So what we have to do is we have to open some local ports as in the local machine, we have to open some port that can be mapped into the MongoDB port inside the Docker container. So this is the way that you would do it, you could assign actually any other port externally on the left side. But on the right side, you have to point to that to the MongoDB port. Finally, we're going to specify a volume. And the purpose of this is so that you don't lose the data that has been stored in MongoDB. When you stop the Docker container, okay, if you don't do this, then you will lose all that data as you start getting the content. So let's declare this volume MongoDB data is going to be the name that is going to be mapped into data dB. Here, slash data slash dp is the usual location where MongoDB is going to store the data inside the container. And we're just saying where we're going to map this location called MongoDB data from our local machine into the slash data slash dv directory inside the Docker container. And finally, we have to specify the a the name of the image, in this case Mongo, then I'm going to hit enter, perhaps I can expand this terminal a bit. So the very first time that you run a Docker image is going to pull it down from in this case from Docker Hub, into the machine. So that may take a while depending on your internet connection. But as you can see, there's there's multiple lines here. Each of them represents what we call layers. So each of them has some piece of this Docker image, including all the dependencies. So like I said, this is just the first time next time is going to be blazing fast on as long as you have those people's lives already in your box. So now we have the Docker image both into the box, and even Docker container running. If I actually do docker ps, I can see that I have the Docker image up and running and listening in this port 27, zero 70. I'm going to close the terminal. And so what we need to do now is to be able to point to that to that Docker image. So to do that, we need to write a little bit of configuration. So I'm going to open up settings Jason. So the basic two pieces of information that we're going to need in order to talk to the database are the host and the port. So for that, I want to introduce a new, a couple of new settings here. And let's call these MongoDB settings. Like I said, we're going to need a host and we're going to need a port. So, in the case of a MongoDB instance that's running in your in your machine, you can refer for the host you can just call it localhost. And as we said, the port that we opened in the Docker container was 27, zero 70. Those are the details that we need to talk to them to the to MongoDB. Now in order to read these settings into our service, I mean there's a bunch of ways to do it. But I think the best way is to declare a class that represents the settings so that we can easily interact with the multiple settings from our C sharp code. To do that, we're going to introduce a folder here, let's call it settings. ukoliko, call it configuration options. There's a bunch of ways, I'll go for settings. So let's add a file here, let's call it sorry, Mongo DB settings. And, again, namespace, got a look that settings in this case, this declared a class. Let's call it MongoDB. settings. And here, we're going to declare those settings that we saw in app settings, Jason this, this declared them as properties. So our first property is going to be prop string cost. And the next one public int port, so this is an integer. And then, let's actually take advantage of this class here, to calculate the connection string that's going to be needed in order to talk to MongoDB. So what we can do here is actually a read only property. So let's see. Let's let's do this string, let's call it connection string. Okay, we're going to remove the set, we don't need to any sailors in there, this gate, we're going to open up. So that becomes a read only property here, we can just return the calculated connection string. So we need to do a little bit of string interpolation here. So what I can say that they connect normally, a MongoDB connection string looks like this. So MongoDB, lashes lash, and then here comes a host, and then comes abort. So those are going to get from the properties, host and port, the properties that we declared over there. So with these, we have an easy way to grab the connection string, as long as we have populated host and port. Now that we have this, it is time to perform the registration of that a MongoDB, a client, a Mongo client, that we injected into the MongoDB, it was 30. So this client here has to be registered somewhere, right? And as of right now, what we know is that we do that stuff in startup. So just open up startup. And here, let's go to configure services. That's what you register all your all your services, we're going to do this services at Singleton because we only want one copy of the Mongo, the IMO client for the entire service. I'm Mongo client. We made it important namespace here. Yep. And then here, instead of just declaring the type of the explicit type of the dependency to inject, as we did over here, in this other thing, you don't, what we're going to do is actually construct explicitly that type. So that it is injected with the additional configuration we do this week, because we have to specify a connection string that that a client is going to need. So to do that we're going to do is say, Okay, so we're going to say service service provider, we're going to receive that service provider. And then we open up braces, going to add column there. And then over here, we can do things like First, let's actually grab the A, the the settings. So an instance of those settings that we have populated in app settings. Jason, let's grab them via our MongoDB settings class. How do we do that? So back in startup, it's two bar settings. You can use your configuration property, the one that we have over here that has been populated by the runtime, you can use that one to say get section. And then so now you need to get a one of the sections in the opposite is the case and we name it MongoDB settings, which is the same name as our MongoDB settings, settings class. Therefore, what we can say is just name off MongoDB settings sorry, Let me type this properly DB settings. And then we need to import that namespace. Alright, so that will get us a section. And then let's actually turn that an object which is returned as I configuration section, let's turn it into a proper MongoDB settings like this. So now we have a setting subject. And now we can actually construct our Mongo client instance with return new Mongo client. And then we will do settings that connection string, the property that we calculated in that class. So we that we should be ready to register and inject the client into the repository. Now that we did that, it is time to actually flip our service to start using our new MongoDB depository. So that we can do in this line, you remember, we previously registered the email it was it already. So switching to this other depository is as easy as you're saying here. Mongo DB items repository. That's all it is. And then one more thing that we're going to do here just to make our lives a bit easier, is to tell the MongoDB, a client, the driver, how to serialize a couple of types in this case is going to be a the codes and the date time offsets. If you remember our entity item, it has both agreed on a date time offset. And I think our MongoDB is that if you don't tell it, how exactly we want to reflect this, these types in the database, they may end up with a representation that's not very friendly, at least not for our learning purposes. So what I'm going to do is say, let's say these, so I'm going to do these on serializer. See if I can get the right namespace, register serializer. Today, we're going to say new COVID serializer. And it's going to be be some type. Let's collapse this coordinate space, that string that tells delsey that anytime it sees a good in any of our entities, it should actually serialize them as a string in the database, we're going to do something very similar with our date, time, date time offsets. So just copy that line. And I'm going to say, date time offset to your laser based on type string. And we'll see how these properties how the data actually looks like in the database in a moment. But for now, we should be ready to start testing this out. So I'm going to hit f5 here. And I'm switching again to postman. Here we're going to start logging in again. Because we have not implemented that we can start with a post. So to do a post, just, I just opened a new tab, and I'm going to switch the verb to post. We need the request URL. So we can grab that from our previous proper use right here. Should be that same URL localhost 5001 items. But what we're going to do, we're going to need in this case is a body, right, so the body the payload that we're going to send to our API. So we'll switch to row here. And then we're going to switch here to Jason. Let me minimize this a bit. So here, we will just a type, the JSON that represents the entity that we want to create that JSON is going to be composed of a name, if you remember, it's just going to be a name and a price. So trying to pick a name and a price. So for our first item in their database. Let's say we go for a great x, and price is going to be let's say 22. So that's all we need for a post. And then we're going to hit sent. And as you can see, the item got created 201 created. And we can see the response that we got from the API. We got an ID, how to generate it in MongoDB and a created date created via our controller. We can also check out the heaters that we received here. And as soon as we returned a created at action. You can see how the location heater has been populated as With the proper URL to retrieve the details about that item, but then also how does this item actually looks like in the database if you're curious. So how can we tell that. So let's go back to VS code. And let's stop this and close terminal, what we can do is install a MongoDB extension for Visual Studio code. So I'm going to open extensions hop over here. And I'm going to type MongoDB, in this case, is the first entry over there. So just click Install. And with that, we have a way to talk to our MongoDB instance, I'm going to close this one. And if you see, there's a new item on the left side MongoDB when you click it, and then there's a connection to already establish or defined there for localhost. 27, zero 17. This may fail the first time you try to connect. So if it does fail, what you can do is just not going to do it, I'm going to remove this connection, or I'm going to add it again. Add connection, localhost 27, zero 17 is the default, and close the STS and that, and then we're not, we're not using authentication at this point. So let's say no. And then hit Connect. And you're going to see on the left side that you have a connection to your local instance of MongoDB going to collapse these and these. As you can see, there's a few databases here. And some of them are really default databases for MongoDB. The one that we cared about what those are closest, now that we care about is the catalog database that I'm going to open. As you can see, we already have both the catalog database and the items a collection over there. We disband these. And you can see that we have one document for us open up that and these good here should match the good of the item created. So let's see FCO 27, open up postman is right here. Sorry, the body of the response, FC 27. So that's the item back to VS code. And if you click over there, you can see the actual data that's stored in there. So as you can see, this is suspected as as of our document database, it is storing the data as Jason directly into the database, we have an ID, the name, price and degraded date. If we had not done these two lines here, these reducers realize it lines here, the data you would see either for ID and for created date would be in pretty much in a different format, that will not be very human friendly. But you may want to play with that decision a little bit depending on on your requirements. I'm going to close this. And I think it's time to implement a tournament winning auto route. Where are other methods in the depository, let's actually go for the get items route. First, how to implement get items, the only thing you have to do is this. But let's say return scope to our collection, I just collection, we're going to say find. And here, since we want all the elements in that collection, we're going to just say new visa document. Oops, there will be some document, I'm going to import namespace. And then that will find all the documents. And then you're going to say to list. So that will give us a list of all the items in the in the collection. So we found on respected a way to request all the items. But this is just one of the ways to do it. There's a few other ways. But yeah, this will get all the items in there. So with that, we can try to get items. So I'm going to do a five again. Back to postman. And happens do we already have the gate for is open here. So it should be as easy as running these again. So just going to click Send. And there it is. We're getting our collection of items. And see if you only have one right now, why not create a few other ones just to have a small list here, as we had before. So I'm back into the post page, the post tab, and I'm going to add a couple of other items. So let's say How about an antidote as this let's make it 15. So he'd sent three if he created and then one more let's add. Call this worked for the golden sward is going to be more pricey say 40. It sent created and then if we go back to get it sent. Now we have those three items available. As you can see Okay, now what if we have to get just one item. So that's what we, for that we need to implement our get item, or our get item method here. But before we can implement this, there's one thing that we're going to need is what MongoDB calls as a filter definition builder. And that's a way that you can kind of filter the items that you want to return as you find them in the collection. Since this is a pretty common object that we're going to use across multiple methods here, I'm going to actually just declare it up here as its own local variable. Sorry, class variable. So I'm going to say, private read only filter defini shim builder, then we have to specify the type in this case is going to be item. Let's call it filter builder. And then we're going to use the builders object MongoDB. of type item, again, that filter, so that we have a reference to this filter object that you will to see how we use it now. Forget it. So but to get item, we're going to do this. So first of all, to build this a filter. So we're going to say, bar filter equals filter builder that equals So where the item item that ID. So the ID of the item has to match the ID that we have received as a parameter. That's the filter. And then we just have to do similar to before items collection, find, we passed a filter. And then we don't want all the items, we just want the one item that they should find. So we're going to say, single or default. That's all it is. With that, I'm going to say five again. And back to postman. So this time, I'm going to open up another tab, I'm going to paste the route forget. But now I have to specify one of the items. So from our previous exercise, let's say that we want to look information about the last insert. So I'm going to copy this ad. And I'm going to paste it in the route item slash the item ID, and I'm going to hit send. And here is we were able to query for one specific item, as opposed to all the items back to VS code is time to implement our update method update item. So similarly to suit ticket item, we need to introduce a filter so that we can tell which item to update. Here. Now, we have to really find these slightly, because we don't want to have so many variables named item. So to avoid confusion. So the item the existing item is going to be named existing item. Existing item that Id should match the item that we got that ID, which is the item to update. And then what we do when we find it is items collection, replace one filter item. So that we'll go ahead and replace that item into the MongoDB database. Let's look at five and try it out. Five, back the postman. And then what are we going to copy the gate route and open another tab here and use our put. So basic there. And then we have to switch, switch to body row. I'm going to be again, Jason. Then we bring this down. And we have to put the body here. So if we use if we do this, we're going to be updating our golden sword. Right? And so I'm going to get the body of our athlete. Yeah, I mean the the format of this a put request, I'm going to grab it from post. And so let's see what can we say about this call this word? Let's call it actually. But in insert. Let's say that the price is actually much more pricey. Let's say it's 35. So this should turn into a platinum. So with this change. So let's see we're going to the output, click Send. We get a tool for no content as expected, and then the item should have been modified. So if you go now, back to Or get route for that item, I'm going to run it. And then as you can see, he has changed noticeably newsworthiness art price 75, we get all the items, hit send, and we see that we have the readiness sword as the last item is great. So finally, it is time to implement our delete method to back to VS code. Let's see delete. And yeah, the filter is going to be again, very similar to our get item filter. So just copy that here. In this case, it's as simple as saying items collection that delete one, here's the filter. And that will do each. So I'll hit f5. Once again, back to postman. And then again, I'll copy the router and use input open a new tab, switch from gate to delete. Basic route, we don't need a body because this is a delete. And I'll hit send. We got our tool for no content as expected. And if you go to the get route once again and hit send. Now we don't have that bloodiness. You see there's only two items. The other one has disappeared. If you wanted to delete yet another one, let's say the great x call to delete - There it sent no content back to get get all the items and there is no great x. So yeah, looks like it worked. And then I'll just go back to VS code studies and close that what I want you to realize is that we did not have to really touch that our items controller at all. The only thing that we need really here, besides adding a few configuration and you know, registering the MongoDB client, the only thing that we did is use create this new identity depository that was plugged in into the service. And that is able to by itself do all the logic of interacting with interacting with MongoDB, the rest of the service has not changed at all. And that's a great the great benefit that we get from dependency injection and in this case, the repository pattern. In this episode of The dotnet five REST API tutorial, we will talk about the synchronous programming model in dotnet. Five, why you should care about it, and how to implement it in your REST API by using tasks async and await. Today you will learn what is a synchronous grabbing model and how to use tasks async and await to add the synchronous programming to your REST API. To understand the concept of a synchronous programming, you can think of common scenario which is say preparing a breakfast. So when you prepare breakfast, you're going to do a bunch of tasks. So for instance, you're going to prepare your pan you're going to heat it in order to after that, you will go ahead and freezer max. And that will be followed by perhaps toasting some bread. And after that when the bread is toasted, you may want to add some peanut butter or use butter or jelly which you prefer. And finally, perhaps you also want to prepare a glass of juice. So a bunch of tasks that in this case you have executed sequentially. If done in this way, it could take let's say 30 minutes to complete. But is that the way that you will usually do this? What about something like this is that so you go ahead and you hit the pan. But instead of waiting for the pan to be heated up, go ahead and immediately start tossing the bread. Right, you don't have to wait for the retest to complete. And not only that, after pulling the bread to toast, you could also start preparing your class of use. That's totally something that you can do at that point. And then yes, eventually, the pound would be heated and you can go ahead and fry your eggs. And also while that's happening, you can if the the bread has been toasted, you can go ahead and put a peanut butter jelly what you're going to put in in that bread. So things are happening, a bunch of things are happening kind of in parallel. And as opposed to sequentially. With this kind of sequence of events, you can reduce significantly the time it takes to prepare your breakfast, let's say all the way back to 15 minutes. These two models is what we call the first one is what we call the synchronous programming model. I mean making an analogy to our programming models that will be synchronous and then the other world will be asynchronous. So in a synchronous manner model, you are not waiting for every single task to complete before starting another one. So you started when you can, you will go back to the previous task when it's time to do so. So then thinking back to our current scenario, we do have a database, a MongoDB database. And then we do have a repository class that's interacting with that database. Now interacting with the database is an expensive operation, because you have to perform input output, right, you have to go over the wire and talk to that database, that database may take time to give you back results, depending on where it is, depending on how much load it has at that point in time. So it may take time, so you don't want to be waiting for that database to finish the work to where you're going to do is instead of doing a synchronous call to database, you're going to do an a synchronous call to the database. So you start the work. And then you let it finish work and work. While that's finishing, you just go ahead and do something else, if you have to do something else. And the same way, we will have our controller talking to the repository. But now we're going to turn it into an async call. So the controller will talk to the opposite, it will not wait for it to finish doing whatever work it has to do with the database, it will just keep going doing anything else that you can do. And then eventually it goes back to that task to complete the work. And the same way, whoever calls, our controller should also be able to call it in an asynchronous way, so that they don't have to wait for our controller to finish whichever work is performing in order to continue doing some other work. So this is what we call basically async all the way. So all your calls a chain a is is when doing in an asynchronous way. And that provides a lot of performance and efficiency to the execution of your code. In order to to reuse the asynchronous programming model to our REST API, we will need to introduce a few changes to our depositories and our controllers. Let's start by making the necessary changes to our items depository interface. So let's open up the depositories items capacity. And here, there are two things that we need to do. First one's going to be make sure that each of these items return dusk, as opposed to item or ienumerable or void. And the other one is to rename each of these methods to have an async suffix. Because that's a convention when you create an API or interfacing says in this case, and you have if you have an synchros better, you should be fixing it with async that tells the consumer that the method is Nic Nic method. And we will actually start by doing that, because we're going to take advantage of the refactoring capabilities of VS code. So that this renamed habits across the board as opposed to having to go to each of the files and make the changes. So let me show you what I mean. So I'll just right click on Get item. And I'll do rename symbol. And then we'll do is just type the new name here. It is amazing. I'll hit Enter. And as you can see, not only the name, change it here in the interface. Also if you see it, I just controller has been modified. And if we see here, where we're calling the repository, get itis async is a new name that it is using already. Without us doing anything else he may might have suppository is also now it has been renamed the method to get item async. And the same for MongoDB. depository, get item async. So that factoring actually goes all the way. So we're going to do the same thing for all of the methods. And then to make things even faster, instead of a right click, and we're going to do is use heat f2 we use a shortcut for this. So you do f2 and then just type pacing. And I'm going to copy this suffix here, enter F to base a seeing enter F to a Singh enter F to async. So with that all of our a or four methods have haven't changed. Now, like I said, the only thing that we have to do is make sure that each of these methods return task. And this is because a that is a way to signal that this is not going to be a synchronous method anymore, but it's going to be an asynchronous method. So what you do is you do task of item in this case. And let me import the namespace system three tasks. And so like I said, this, this is saying that when you get an item from this method, you're not going to get the item right away, it's not a synchronous method anymore, you're going to get a task that represents an asynchronous operation that eventually is going to return an item whenever a we have finished retrieving that item from the from the from the database in this case. So that turns the metal internet synchromed we're gonna do the same thing for the other methods here. So task of ienumerable of item and then for the void cases, we just turn into desk And that is it for this interface, the interface is ready to operate as an a synchronous interface. Next, we're going to go to our list open up this a little bit MongoDB items have auditory. Okay, so let's see. Let's go one by one. So the first one in this list is great items async. So I'm going to turn again Boyd into task. And then I'm going to import a way to import the namespace, right namespace. And at this point, what we have to do is start invoking the a synchronous version of the methods that in this case, MongoDB is item collection offers. And this is a common a pattern, like in this case, I'm actually going to open up the IntelliSense here, and you're going to see that for insert one, there's an alternative insert one async method. And for in this case, for insert, many there's insert many AZ met, this is going to be a common situation for many of these libraries that have to a reach out to some external service. Since those operations can be expensive. And they represent input output operations, you want to offer the capability of executing the operation in an asynchronous way, as opposed to an asynchronous way. Where you do a C synchronous operation, like we had before just insert one, you're actually doing a blocking call, where you're just you're making it so that this method just stops there, nothing else can happen until the call comes back into the method, right, in this case from the database. And that's exactly what you don't want to do. So just turn turn into using the asynchronous method. And you will not have to wait I mean, the code will not have to wait for that call to finish. And and that will make your entire application way more efficient. So that is one piece of whatever we have to do here to make that a synchronous call. However, we still have a little problem here. And the fact is that we're missing one thing, which is the async await keywords. So by doing async, here, just next to task and then await here, when we made the call, we're kind of adding a little bit of a syntactic sugar around the whole method to tell a dotnet five, the compiler that this is going to be an asynchronous call. And that it please help us to not have to write even more code to tell it that how we're going to go to go around this asynchronous call. So a sink and a weight, it really helps us a lot in terms of defining that the methods are going to turn into async. So that we don't have to write even more code to deal with task and how to break it. And that will be it for grade item async. So now let's keep going with the other methods. Or let's go with delete imazing. So same way, we'll do async task. And in this case, we're going to do a here's the line where we call database. In this case, the lid one will do a weight is collection, delete one async. Yep, and that's it for delete. Next one, get item async. In this case, we're going to do async task of item, because we had to return that item, but it as part of a task. And then we're going to do return await, I just collection find foot by filter single or default async. Next one get is async will do async task of ienumerable of item and then return await. And then here to list async. I think this is the last one update is async. Once again async task. And then we just await here, we say we base one async. And that's all you have to do. Like I said, By doing this, you're making sure that every time that you talk to the database, you're not making a blocking call anymore, you're actually letting a framework, I mean, giving back resources, I mean, giving back the chance to the framework to keep doing work while we wait for the database operation to complete. And like I said that, that gives a lot of more efficiency and performance back to Europe. Now Now we did this, as you can see, we still have the problem with a with a meme is a possibility, which is, this is the original repository we're using in the first videos. So we could choose to just delete really this repository at this point because we're not going to be using it anymore. But as a learning exercise, we can actually turn this guy also into an async a class, I guess, even when we're not going to be calling anything external, right, so in this case, we're just dealing with a with an email list of items. So there's not really that much of a need for async stuff here, but we need to We need to handle the interface that were implemented. So let me show you how we can do this. Let's start with a get is hazing. So same thing we did before, this has to be async task of ienumerable item. And then we have the important space. What we do here, we say return await. But in this case, since we don't have anything to call noising, close by to to call, but we have to say, say, Hey, I just want to do tasks that from result. And we're going to pass items. What this means is that we want to create a task that has already completed. And we want to introduce the value of these items collection into that task. So it's kind of the equivalent to saying, hey, go ahead and execute this, execute this is this other method and wait for it to complete and then return the results, right. But since we don't have anything to call, you say, hey, just return a complete task with the items in it. And that's, that's always, so that's how you can handle this situation where you don't have something else to call. Let's see what we can do about get item async. So we'll do a scene async, task vitam. And in this case, we're going to use capture in the case of a dynamic thing we're going to capture ID equals items where we capture the item that was found, we do something similar, as before, await does that from result. Item. Yep, same thing, we return result, complete task with the item that we that we found. For create item async. Again, we're going to do async task. And in this case, we don't have really anything to return. So the only thing that we have to return here is some some sort of a task, right? So we're going to say is a weight task that in this case, we can do a completed task. So this means just create some task that has already completed and return it without returning anything inside it, because there's nothing to return. Now let's move to update a item async. So async task. And then once again, copy this await task, that completed task. Finally, we'll do the Delete. So async task and await task that completed task. Yep. So it's as simple as that. Now, just to let you know, it is not necessarily it is not necessary to use async and await in every single case, you could go around and avoid a avoid this combination. In some cases, however, I would consider that to be a bit of an advanced concept that I will not like to dive into that right now just because it has some pitfalls that you have to be aware of. And it is not trivial to know them beforehand. So for now, I would recommend you to stick to async await anytime you have to run an asynchronous INVOKANA synchronous operation and define your own method as an asynchronous operation. And now let's go to our itis controller and do the final set of modifications that we need to introduce here. So let's start with a get items. Right so same thing. Let's turn this guy I mean this is a sink all the way right so we have to turn everything async now async task of ienumerable identity all these forget items. So again, importantly space. Let's not forget that this method now should be suffixed with async because it is an asynchronous method. Now here what we have to do is again do and await and await for the get a get is async call. But it's it's a bit more problematic here because the weight is separated from the from the actual method, and we're trying to chain a select right away, that's that's not going to work, we have to wrap this into into these parentheses to tell it that first go ahead and do this. And when that's completed, then go ahead and do the Select right so that is just to comply with the with the syntax that the compiler is expecting from us. I'm actually going to put this in this in a second line to look at it better. And just before we go ahead to get is async await for it and when that's done, we select the items that we got. We turn them sto and then we just return them back to the caller. When we learn to get item, we're going to do now a sync task of actually sold it to and it should be get item async. And here when we call get item async we used to await That will do it. When we don't do the next one post, we will do async task. grade item pacing. And then here is where we create the items. So we will do a weight, create animation. And then remember that now the method is actually named the get item async here, so we have to do the proper rename. Next one update item. So let's say async task. Action result update item, a sink. And let's see, here's what we call it. So we will say await get item async. And over here, we also have to await for the call to update item async. And finally, let's go to our delete item method. It's going to be again async. task, action result list item async. And then await and then over here, wait suppository, delete item async. So now our controller is all async and is calling methods that are all async. And the depositor is also calling methods are always in. So we're doing async all the way basically. So let's see how this goes. So I'm just going to do f5 now. And I'm going to open postman. Let's see, let's start trying out the API's. First one here, the first one that we had is a the items. So let's try to get the full list of items. So I'll hit send. And as you see, we do have the antidote from the previous video still hanging around, that's working just fine. Now let's try to create a brand new item, right, so how would we call it let's say this is going to be high potion. So a potion that provides increasing strength to the player. And so the price is going to be, let's say 30. And I'm going to hit send. Let's see if that works. So we do have an issue here, we're getting a 500 internal server error, and no route matches the supplied values. So this here is actually unexpected situation. This is because of a breaking change in ASP. NET Core three. And let me let me show you why this happens. Let me go back to items controller, I'll use a stop this, close that. And if you remember, what we just did a in grid item async method is that we updated or created an action call here, to use a name of get items get async as opposed to get item because we just rename it that method over here, get item async. It was get it before. And now the breaking change that interested in ASP. NET Core three zero is that at runtime, the framework is going to actually remove the async suffix from from the mid range at runtime, this actually looks like just get it as opposed to get Iam async. Given that when we try to do the greatest add action call here, it is not able to find the route that represented by that action. And so that breaks things. So there's a couple of ways to fix this. And what I'm going to do is to actually tell a dotnet that I don't want that behavior, I just want to keep using the async suffix. So to do that, what we can do is just go to startup startup, what you want to do is find your call to our controllers. And there, you just have to specify a one option, which is options. Let's see options, open curly braces, and then you want to do options that suppress a theme suffix in actual names equals false with that, that that will not remove the async suffix anymore from any method at runtime. So let's see how that goes. like five, back to postman. And now the one thing that you want to keep in mind is that the creation actually succeeded. It just happens to be that we were not able to be a we were not able to create to invoke the created our action a call, right. So just to confirm that if you go back to get a return to do a get here, you will see that we do have the high potion created. So it is there. But we will not we were not able to complete the creation. I mean, we were able to call the Create action successfully. So let's actually create something else here to not confuse these with a high portion. So let's call this one mega potion, or mega potion is going to be more expensive. Like let's say 45 So now I'm going to do sent. And this time, they actually it was actually created successfully. No issues there. Now let's use the A this item to actually try the get route. So just to get a for that item, let's see if that works. That works just fine. And now let's try our put our put route for that item. As so let's see, we're going to use the same name, perhaps make a potion. But let's put another price. Let's see what price we have. Here we have 45, let's say it's even more expensive 50 for the mega potion. So I'll hit send. And that should have updated the mega potion. So let's go back to the gate, make sure that the price changes. So hit send again. And as you can see, price is now 50. And let's see, let's actually not delete that makeup in we're going to try to delete route. But let's delete something else. Let's say we want to delete this high portion. Actually, he's kind of our favorite experiment. So I'll copy that ID. So I'll try to delete that. Anil he'd sent two or four new content back to the target route. Let's see what we get. And as you can see, Hypatia is gone. So we only have the antidote and the mega portion. You want to configure that things are actually getting read into the database. It's as easy as going back to VS code, and close. And I'll open up again, our MongoDB extension here, catalog items. And we do have let me refresh this. We do have two documents, one for the antidote. And whilst they make a push, and yeah, now you have fully a synchronous REST API, which is going to give you great performance and great efficiency. And from here on. In this episode of The dotnet five REST API tutorial, we will talk about secret management and health checks. We will see how to securely store secrets during development that your REST API can use easily as with any other piece of configuration. We will also learn about health checks and how they are a great way to report the health of our API. Today, you will learn how to store and use secrets via the dotnet secrets manager and how to use health checks to report the health of the race API and its dependencies. So let's talk about secret management. As you know, at this point, we do have a REST API that is able to talk to a database or MongoDB database. And in order to be able to talk to it, we have defined a configuration service where we have specified details like host and port. So to be able to connect to that MongoDB database. The configuration source that we've been using so far is our app settings, that JSON file right there, we have host localhost and Port 27, zero 17. But now we are going to enable authentication to the MongoDB database. So you're going to need a username and a password in order to be able to connect to it. We have to tell our REST API how to how to use this information. So for the user, we're going to add our user another user is setting in top settings JSON for are going to call it just MongoDB admin for the username. And then we also have to specify a password. So should we just specify the password directly in the app settings JSON file? Well, the answer is no. You don't want to add any sort of secrets into app settings JSON or into any of the files that you have that are part of your service. Right. So that's a basic, good practice in terms of security, never introduce secrets in there. If we cannot do this, then how are we going to pass that information into the service. So it tends to be that app service JSON is just one of the possible set of configuration services that can feed into your REST API. There are other options like you could use a command line arguments, you could use environment variables, or you could even use a bunch of other cloud searches, searches coming from the cloud that can provide configuration information into your REST API. In our case, we're going to use one that's called the secret manager. This is just one more configuration source that's built in into dotnet. And that is already pre configured for you, for any new brand new web API are in that secret barrier. We can securely store our password, let's say pass in this case. And without having to put that password within our REST API. So it's not going to be in any of the files that compose our REST API. It will be in some placing our machine securely stored, but yet, they are REST API is not going to have any trouble reading that. That password because just as as anything else, it is coming just as a new piece of information. majorly from our configuration service. And the rest the REST API can easy to consume. We are now going to enable authenticated access to our Mongo database. There are a couple of ways to do this. But to keep things simple and safe, this is just a development database for learning purposes, we will delete the volume where Mongo container currently storing all the data. This allows us to start a new container with a brand new Docker volume with authentication will be enabled. So the first thing that you may want to do is verify if you're running the container already or not. So we're going to do is open a new terminal. And I'm just going to do docker ps, that will tell you if you have the container running already. And you are indeed, in this case, I am. So what if the first thing that I have to do is to stop this container. So I'm going to do Docker stop Mongo that stops the container. And now what I want to know is, which is the volumes that I have available here. So Docker volume, LS, that will give us the one volume that we care about right now MongoDB data. And now what I'm going to do is just delete it. So Docker volume, RM MongoDB data. So now the volume is gone, we are free to restart the container with a brand new volume. So what I'm going to do now is just a grab the initial set of a, the initial command to run the container, just as we did before. And then as you can see, the same volume is here, there's going to be a new one, since we deleted it already. And what I'd like to do is just add a couple of environment variables that represent the username and password that are going to be used at a within the database. So if I just do dash E, and this is the file, the name of the variable, in this case is going to be Mongo in it. dB. Root username. And here we specify the name for our user, you could use any name here, I'm going to, I'm going to use Mongo admin. So that goes for username, and now the password for the password, you have to use Mongo ini dB, root, password, equals, and then you got to pick a password. So I'll pick something here, not super strong, but still something like these. And finally, the name of the of the Docker image that we want to use in this case is Mongo. So with this, it's a hit Enter. And now we do have docker ps, we do have a database that has authentication enabled with a user of Mongo admin and a password of pass bout, we're one. So at this point, our database requests authentication, but our service does not know about it yet. So what happens if we try to query date at this point, what I'm going to do is just hit f5, the service. Okay, and then go into postman. And I'll just try to query for a few items and see what happens. So these are items query it sent. And yes, command find failed command phi requires authentication, right? So just good. authentication is working. It's just that our service does not know the correct credentials to talk to the database. So how can we make a how can we make this service a aware of the user and password needs to use. So let's go back to VS code. Let's stop and close this. And what I'm going to do is, first I'm going to declare a a configuration setting for the user. So I'm opening up series Jason. And in this section where we have MongoDB settings, I'm just going to add a one more section here. For for user, let's call it user. And we know that the user we specify for the database is Mongo. Now, we also need a password. And of course, I could specify a password right here. But that it's not a good idea. You should never specify a secret or confidential information in your app settings JSON file, that's a security kind of a security hole. So you should not do that. Instead, we're going to take advantage of the dotnet secret manager to store the password security as still we should be able to pull that secret into the service into the REST API without any trouble. So to do that, again, I'm going to open a terminal. And here's what I'm going to do. First, let's initialize the secret memory for our project. And that we can do via dotnet user secrets a bit And if you take a quick peek into catalog CEUs blog, you're going to see that there's a new entity there. User secrets ID. So this represents a identifier of this secret configuration for this project. From here on, we can start actually adding secrets to the for this project, and do a secret what you can do is.net user secrets set. And here you have specify the name of the secret. Now for the name where we want to do is follow the convention of the settings, the settings property that we have defined already, and yours a add to it in the in, in the in the format accepted by the net. So in the in our case, that means is specifying MongoDB settings, and then we do colon, and then we specified the actual a property that will represent the password, this case is going to be use password. And after that, we specified the actual value, in this case for the password, and we know that the password is pass bound word one, or one. Okay. So just like I did here, what I'm saying is, is that the, the, the name of the secret is going to start with MongoDB settings, which matches a MongoDB series right here. And password is one of the properties that is going to follow the other properties that we already have in the MongoDB settings class, and the actual values passed out word one, hit Enter. And the secret has been add. What we need now is a way to read both username, the user and the password into a our service. To do that, we're going to go into our settings, settings class MongoDB settings. Absolutely, let's close this. Let's add a couple of new properties here. So let's add string, user. And string password. So these are the two properties that will be populated at runtime by dotnet. into into our app. Now, the other one that we want to define is a modified connection string because now it is not going to be enough to provide us whole support. We have specify user and password. And the way that you do that for a MongoDB connection string is by saying user colon password. And then we'll say at host column port. So that's the same text that MongoDB is expecting from us. So just by doing that, let's try equating again and see what happens. So I'll do a five. And I'll go to postman now. So let's see if we can query for information sent. And yes, we don't get anything because remember, these are brand new database because we modified the volume, but we are getting a 200. Okay, oh, things seem to be a running just fine. And just to be completely sure, what we're going to do is do a post. And we'll switch into the post tab here and see if we can actually recreate this mega portion with price 45. And not just that, let me actually put a breakpoint over here. And to see how these values look at runtime. And Cynthia Singleton, I'll have to stop and restart our, our service. So let's hit f5 again. So the first time that the connection is needed, we should hit this breakpoint. So go to postman. And I'll do send here. And I suspected we have a breakpoint here. So as you can see, the user has been read from our app settings JSON file, and the password has been read from the secrets manager. So password is not at all reading, updating JSON is just coming from secrets manager. And really that that that magic that takes that does running here is being driven by program CS when we do create default builder, that piece takes care of injecting the secrets barrier as one more configuration serves to our service. So you don't have to do anything special for that to happen. So if this happened, and we just let it keep going. Go back to postman. And in fact, yeah, the mega portion has been created. If we create it for them. We'll see that it is right there. So moving on to the next topic. Let's now start talking about health checks and how to enable them. So But first, let's learn about health checks. So as we know, we do have a REST API at this point that is talking to a MongoDB database. However, it is not uncommon to face issues as time goes by, right? So a REST API could go down for a variety of reasons. Or it could be a good intention, right? We may be redeploying these REST API to our, to our server to our cloud service or to our server wherever it is going. So even if temporarily, that REST API could go down. And there will also be issues on the other side with talking to our database, right? So for any reason, that database, we may lose connection to the database, either temporarily or for a long time. Or something could be going on, and we're really talking to that database, right? So communication issues could happen. So with this, we may start getting equations like, is our REST API alive? So is it alive? Ganga, we actually talk to this REST API. Right. So you may start wondering this, or you may start wondering, Well, can we reach a database? So is it there? Is that connection in a good state? So but really, what you're asking here is the broader question, is it healthy? So is our race API healthy? Is it ready to receive quiz? Is it ready to do the job the right way? And to answer that question, the right way to do it is to enable what we call health check endpoint. So so you don't have to guess. So we will have, you will have a natural endpoint that you can call is part of our universal API. And you can call to it and it should be able to tell you if the service is healthy or not. Right. And, of course, there will be a person or people interested in that information. So us as, as a developer, as an engineer, that increases service may want to query for that help endpoint as either services healthy. But really the most important case, the most useful and original a scenario is when you have an orchestrator system, that will be in charge of knowing when your service is ready to receive requests. So we will talk more about this in a few episodes in the future. But having a health check endpoint is a key piece of any REST API that you have think about right away. Now that we learned about health checks, let's see how we can enable them for our REST API. So the first thing that we have to do is to add the services for health checks and that we can do within startups. Yes. Before that, let's stop debugging and close terminal and open up startup CS. And I'm going to head into the Configure services method. In this method, we're going to go all the way down. And we're going to add just one line here. Services dot add health checks in now, so that's the services and now we need to add the middleware for it. And that we have to do inside the US endpoints method inside Configure. So here, we're going to say, endpoints that map health checks. And then here, you get to pick the route that you want to use for your health endpoint. So in my case, I'm going to go for health. But feel free to choose something else, like you could do something like hc, or you could do health See, it's really up to you, what do you want to use, I'll go for those held. And now I'm going to do a five. And let's try it out. So that should give us a very basic health check endpoint for service. So back to postman. And the way that you query for this health check is really very similar to what we do for the iTunes route. So we just have to open up in a new tab in postman for the get burb. And I'll go for my localhost colon 5001. And then you just add the URL to route our case is held. I'll hit send. And here's you get a result, he says healthy. So with that, you have a way to almost like being your service to see if it's in a healthy state. So this means that yet the services is up and running, and everything should be fine. However, this is actually not super useful, because even if the service is up and running, it means nothing if the database is down, right, if the service is down, or if we cannot reach it. Our service is not really that much healthy. So how can we tell if we have any dependent service like a database in a not in a healthy state? And how what how can we take advantage of health checks for this? So let me show you what we can do. Going back here, stop that close these are going to do is add a nougat package. That's called ASP. NET Core healthchecks MongoDB. That will allow us to add health check is specifically designed to verify if MongoDB is running properly. So I'm just going to open a new terminal here. And I'm going to say dotnet, add package, ASP. NET Core health checks MongoDB. So this is an an open source project, it's not part of ASP. NET Core or dotnet. Five, but it is a very handy project. And with these with this package, the let me show you what we can do. Close the terminal again. And then. So here, what we want to do is add some options to this call to add a health checks. But before we can do that, we need to pull out our MongoDB settings in such a way that we can reduce them later on. So to do that, I'm just going to grab this, this line here, outside and into, let's say here, and we will call these MongoDB settings. So now those MongoDB settings can be used over here for our MongoDB client Singleton. But also for our purpose right now, after saying a uthealth checks, we're going to say that at MongoDB. And here we will use MongoDB settings, that connection string to specify the connection string that needs to be used to connect to the MongoDB database, right or health check is going to be based on can we reach this database or not. We will also add a couple of things here, like a name used to define this specific health check. And we will just say MongoDB. And one more thing is a timeout. This is because we don't want this healthcheck to take a long while to tell us if the database is is just down. Right. So in this case, we'll say timespan from seconds, let's give it three seconds. If after three seconds, we cannot connect to the database. But we'll consider that this has failed write the check has failed. So now that we did that, let's try it out. So I'll do f5. And let me actually remove this breakpoint. And back into postman. So here, yeah, I'm going to say hello again sent. And it is healthy. And I suspected because our database is up and running. But if I go back into VS code into our terminal, and I use a stop our MongoDB container. So let's see Docker stop Mongo that will is Docker container, which is equivalent to just stopping completely our database, right and the entire database services going down. So let's see what happens as I go back to postman. And I tried to check her health will take like two seconds. And then yes, right here. So now health check is reporting as unhealthy. Which is great, because now anytime a database is down, we can easily tell that that as part of the health check that we're using right here. Now there's one more thing that we can use to improve the scenario. And is the fact that we may want to have more than one endpoint to verify not just the fact that the services is up or not, but also if it is ready to receive requests or not. And the typical pattern here is specify both a ready endpoint and a live endpoint. So our ready endpoint is going to tell us if we are ready to well, if a service is ready to receive every incoming request, right, which in our case really means so is the database up and running Ready to go? Can we use it? While the live endpoint is just going to tell us if our service a justice service is up or not? Is it alive or not. So to do this is these two endpoints, let's actually go back to VS code. I'll stop this again. And back to startup. First thing that we have to do is going back to our health check configuration, we have to assign an attack to our health check to let me show you what I mean. So actually put these things down a bit so that we can do the easier. So I'm going to open up a One more line here. And I'll say tax. So I'll create a little array here. And here, I'll say ready. So here I am attaching a tag that I'm calling ready. That will help me a group, every single health check for which I want to apply are ready endpoint. So the endpoint that specifies if I'm ready to start receiving requests, how do we use this. So now let's go back to our map health check section. And I'll add a line here. So now we know we need to specify in our two endpoints, one for ready and one for life. So let's go for the raven first. So instead of just having held here, I'm going to say okay, slash ready, it's going to be our ready, ready endpoint. And now has specify health check. Health Check options, see for museum a space right there. Okay, open up this. So at this point, we have to specify what we call the predicate for the predicate is the way that you can filter out which health checks you want to include in these in this endpoint. So remember that right now, we only have one really, our that one has been tagged with ready. That's one form of MongoDB. So in the case of the radium point, we want to include that MongoDB endpoint. So to do that, what you do is is this, you say check. And then we'll say check tags contains. And then the tag name ready that you have already endpoint that will, will will only include those a health checks that have been tagged with ready. And then we have to define another endpoint. So I'm going to actually copy, copy these, these one is going to be just live. Really, for the live case, we don't have to do much, we actually don't want to, we don't want to include any health check, we just want to say a kind of the response over pink rice. In this case, we're saying just false. By doing that, we are excluding every single health check, including the Bongo DB one, and so that it would just come back to us as long as as long as the REST API is alive as the service is alive. So that's the way that you can do the life. So ready, we'll make sure that the database is ready to serve requests, life is just going to make sure that our site, our service is up and running. So with this, let's run again. So I'll do f5. And I'm back into postman. And this time, so let's, let's see. So I'll query for, let's see, health, life. see what we get. So he says healthy, is expected because the service is up and running. Now I'll try ready. see what we get. So after about three seconds, we do get unhealthy. And this is because our database Docker container is still still down, right? as we did before. If I go back here, and I go back to my terminal, let's say this one, and actually restarted the Docker container. For Docker, Ron, Yep, sure, do it. That starts a container again, go back to postman. And he'll sent and I get held up because the database server and the database are they're up and running. And usually that's good enough. So that's what you want to do to enable your your health checks. But if you happen to want a little bit of more information about the health check that you have configured, you can actually customize the message that you're getting here. This gives us the basic thing healthy, but you can get more if you want to answer Let me show you how to do that. So back in VS code, open close, we're going to look for our map health checks function. The red one in particular is interesting. And what we can do is take advantage of what's called the response writer. This is post writer you can use to specify how to render the message that you're getting as you're collecting the results of the health checks. So I'm going to say async context. Sorry for that context report. Let's do this and then open curly braces, and then here I'm going to collect the result of the of the checkout. So for that, I'm going to say sold equals, I'm going to use the JSON serializer. The one that comes with dotnet, I'm going to serialize. Now we're going to create an anonymous type here. So I'll just say new. And then we have to give it a shape. So this is the shape of what we're going to return back into postman, to the collar. So the first thing that I want to show is a status started, we can get from report dot status, just to string. And then we want to get the array of checks, which should include our MongoDB check. So in this case, I'm going to say report entries, select. And I'll say, so I project each entry into a new anonymous type. And in this type, I want to show first the name, which is going to come out of entry that key, then I'll get the status of this very specific check, which is going to come from entry value status to string. And then there could be an exception coming from the database. So let's actually capture that too. Oops, sorry. exception, is going to be empty that value that exception, but we may or may not have an exception, depending on the status of this check. So we're going to say is that if the exception is not No, we will get an entry value, exception message. But if we don't have any exception, if it is no, we will just say not. Finally, one last detail could be interesting is the duration that will tell us how long it took to do this health check. And three value, duration to string. game, so to taste. And now one more thing that we can do here is to format that output. So I'm going to say, context, that response that content type equals media type names. And using something that application that Jason, that will let us render as a nice JSON string, back in postman. And finally, I'll actually write this information out. So await context response. Right? Right async result using one new spacer. And that should do it. So now we have customized how that message should be rendered. So I'm going to do a five once again. And back into postman. So let's see what happens when I tried my radio endpoint now, sort of hit send. And now as you can see, the result is a bit nicer. So we do have a status of Lt. And then we can see the array of objects. In this case, we have MongoDB, with a healthy state nociception and a duration in there. And if we wanted to get the sample with an actual exception to this, you can just stop your local Docker container again. stalker stop Mongo container stopped. I'll try again back in postman sent. And after three seconds, we should get Yeah. So now, as you can see, here, the entire health check is unhealthy. The specifically MongoDB is unhealthy. And yeah, the operation has been canceled. So that's what we're getting from, from dry dock to MongoDB. Now one last thing that I wanted to show you is that there's actually a bunch of health checks already available for you. And so just like we did a MongoDB one, let me stop and close this. If you remember, we did this here, we did the MongoDB. One, just like this, there's a bunch of other ones already available for you to try out, depending on the service that you're using. Let me point you to this page here, which is a page for the open source project that I mentioned that has these health checks. So over here in this GitHub project, you're going to see that so this will tell you everything about how to use these health checks. But I wanted to show you that there's already health checks built in for a bunch of providers, right, so SQL Server, MySQL, a bunch of things Cosmos TV, send sendgrid, a few Azure services, Amazon services, Google stuff, here's the one that we use MongoDB. And so yeah, so there's A bunch of providers already available. And there's even an here's a nougat package that you can use. And there's even support for let me show you the support for for a UI. I don't usually use this one. But if you wanted to show a very nice UI with all your health checks, with a breakdown for for each of the checks, you can actually enable these, these health check UI. Sorry. And yeah, and that will just stand up another endpoint in your in your service that you can go to, and get all these nice UI rendered. So that's something that you may want to try it out. I usually find there's some old ways that I quantify the help of my services, as we're going to see as we move forward with these videos. But this is another option that you can try. In this episode of The dotnet five REST API tutorial, we will start our path towards getting our API deployed to our production environment. We will learn about the relational challenges involved in getting the API beats deployed outside of our developer box, how Docker can help us address these challenges, and how to turn our existing API into a Docker container. Today, you will learn the challenges of deployment, how Docker works, and why you should use it, how to turn the REST API into a Docker image, and how to run your REST API as a Docker container. So the way that things are at this point, you know that we do have a REST API up and running in our local box. And there's also a MongoDB database running next to it as a Docker container. But now we need to figure out how we're going to share this REST API with the world, right, either how to share the REST API with people inside of our local intranet, or how to share the REST API with the world perhaps in the public Internet. And that place where we're going to share things is what we're going to call the production environment. The production environment could be anything from some server running in your in your building, or your house. Or it could also be some server running software in the internet, right. But for all cases, this is the production environment, this is a place where people will be able to access the a REST API without having to get access to your local box, your developer box. And one of the first things to think about when we want to pick this, this server for production is the operating system. So we will need to figure out when to find the right server with the correct version of the operating system that our REST API is able to support. So in the case of for REST API is not really that much of a big deal, because that five is cross platform. So what we have built so far is to be able to run in really in a bunch of operating systems. But still, we need to sell install operating systems. So if we say that we're going to be running this on on Linux, then we would need to go ahead and make sure that we have Linux available the correct distribution and version of Linux available in that production environment. Then, we also know that we do need the dotnet five runtime to be able to run a REST API, the REST API is built on dotnet five, therefore, we do need the dotnet, five run time, and all the corresponding files of it, they need to be placed in the right place in that production box. On top of that, our app may have a bunch of dependencies, like the MongoDB driver that we've been using to talk to one MongoDB. So like that, it may have a bunch of dependencies that they also need to be placed into the production box. So that finally, our REST API can be placed alongside all of these other components, and it can run happily. So it is at that point that we can, we can continue that we have all the files and sorry for the REST API to be running in production. But then also, we have to consider that we also have database requirements, right. So we have a database that we need to play somewhere in this production environment. And it will have its own requirements in terms of operating system, and dependencies that MongoDB may have the MongoDB and Gene, all these things that we need to run the database in production. So that by itself presents another set of requirements. So as we think about all of these, these things that we need to that we need to happen to get our production up and running. So we need to think about a few challenges right. So the first thing is going to be preparing a box. So what you really want is to make sure that whatever box we use for production has everything that we that we have had so far in our developer box, right. And then but you also have to think about so are we going to pick a physical machine Are we going to pick a virtual machine or virtual machine is really just average the latest version of operating system running on top of some other physical machine. So any regardless if office same physical machine virtual machine, we need to figure out well, where are we going to get this machine from? Where are we going to host it? Who is going to be taking care of this machine? A bunch of questions just regarding this this machine. But also way to figure out okay, so is it going to be Linux? Or windows? Who's going to put the right version of the always in there? Who's going to make sure that he has the right set of patches? And who's going to maintain these? Really, somebody has to take care of these things? But also, how are we going to take the files to the production machine, right? So we have all these files in their box? And somehow they need to land in production? How are we going to do this? If we're going to be using perhaps some FTP protocol, to be able to talk to an insanely fast to production machine? Are we going to put the files in some USB or pendrive? And then just copy them using it into the production machine? Are we going to send the files to some person from operations, B, perhaps some email and then the person will place the files in there? How do you make this happen? The first thing to get there? So one way or another? What happens? I mean, in this case, we're thinking of placing, let's say that the database server just next to the REST API, if we're going to do that, how are we going to make sure that all the dependencies of the database and the dependencies of the REST API have the right versions, even when we only were placing everything in the same machine? Right. So there could be version mismatch between the things that are needed in the MongoDB database? And the detail needed in the REST API? Right, starting from the previous system? How do we make sure that all the dependencies are the right version for both of them? And if they're, if they cannot be, we have to figure out okay, so perhaps we need to split his REST API into one machine and the database server into another machine, which could not be that uncommon. But we have to think about all these things. Also, what if we eventually decide to move to a new version of dotnet? Right, so let's say that net six is out. We have to we want to move to the next six. What does that mean? Do we have to bring in a brand new set of servers, physical rooftile, that are already enabled for dotnet? Six? Do we want to just update the version of dotnet in this existing server, and then somehow make sure that the app does not break by making that change? How are we going to make that happen? Also, how do we start recipient the machine because it is not just about copying the files in there, right? So somehow, we need to start the dotnet app into the server, somebody has to do it right. So we have to bring in some sort of automation, sort of a scripting, something needs to happen in that machine, to be able to start with API and not just started but started fast. And we want to make sure that as soon as we put the beats in there, the application starts quickly so that it can start serving our users. And finally, what if one instance of the app is not enough? So what if we start having so many users and us having one web server for a REST API is not enough? And now we need to bring in yet another? Let's say VM virtual machine for a recipe and then another one, and then another one? So who's going to take care of provisioning all these VMs? For us? What about the database? What if we alternate multiple copies of the database server to be able to handle the load? So how is all this going to happen? So do we need to think about all these challenges? Do we need to deal with all of this? Or is there a better way? So luckily, here's where Docker can help us. So now, let's go back to our local box. So yeah, so we have our local box has REST API and the and the database currently, and we need to get to production. But now, instead of starting to worry about how to copy all the things into production, or how to make sure that production has the right things already in place, we can start using this thing called a Docker file. So a local file is kind of a template of all the things that are needed by your a, in this case, a REST API to get it deployed into production. So in the Docker file, you will declare things like the operating system that we're going to need. So you're going to say, I run in this specific version on this specific distribution of Linux, let's say, What is his version of Windows. So he is already declared in that file. And so you're saying as long as that version is available in the production machine, I am, I am going to run just fine. And not only that, you can say, Well, I actually need the version five zero of the dotnet, or ASP. NET Core runtime available in there. And by doing this, as long as I have all the dependencies of the dotnet core runtime, I am able to run my my REST API, right, so you can declare the runtime that you're going to be running on. You can also declare or you can prepare all the dependencies that are needed for your app. Right, let the ongole be driver and any other DLL or any other dependencies that need to be present in there, you can specify how to place the files that you want to put in that in that production environment, you can say how we're exactly what to put them. And you can also tell it exactly how to get started or how to start that REST API. So that scraping that is needed to say how to start it, it can also be said in this Docker file. So just by using the Docker file, you get, you get, you're already handling a lot of the challenges that we were talking before, because this Docker file is clearly declaring exactly how the how the environment needs to be built for the REST API to run properly. And so but then, it is not not enough to use have this Docker file. So now that you have Docker file, what you're going to do is use this thing called the Docker engine to actually prepare what we call a Docker image. So what happens here is that the Docker engine, which is just a process running in your in your box, the Docker engine is going to take that Docker file, and it's going to tag it and and build what we call a Docker image. Tagging is is really just kind of a synonym for creating a version for your image. So you're going to set a version on that image, and then you're going to build it. So building a Docker image means reading that Docker file line by line, or executing all those instructions to prepare the environment where a REST API is going to run. And that goes all the way back to ensuring that all the exact dependencies are in place, put the files in the right location and starting the app. Right. So all of that is encapsulated in that Docker image. But then, once you have the Docker image, it is not enough to just have it running in your machine, right? what you really want is to make it available in production. So how do you take it from your box into production. So enter the Container Registry, the Container Registry is a place that could be anywhere going from some server in your again, in your internet, to somewhere in the cloud, it is the place where you can place your Docker image, you can push your Docker image so that it eventually becomes available for a your production environment. So this Container Registry, I mean, you don't necessarily have to be the one that pushes the Docker images in there. There may be some some other images already available in the registry. So for instance, in the case of MongoDB, there, we've been using an instance, the Docker image of MongoDB. Since a few episodes back, we did not actually create that image Damon was already there. And that image is actually available in a specific Container Registry called Docker Hub. So Docker Hub is a public registry, where many vendors place their Docker images for public consumption. But just like there's a Docker Hub, there's also other container, private cul de registries like a Azure Container Registry, or Google a registry. Amazon ECR, I think is the name. There's also these days, GitHub have a registry. So there's a bunch of versions of these available. But all of them are able to operate with your Docker images in the really the same way. So what you have Porsche Docker image into the Container Registry, then you're able to have your production box in the physical box, virtual machine, whatever it is, it is able to pull your Docker image into it. And by pulling it and executing that image, it turns into what we call a Docker container. So the Docker container becomes kind of living version, our executable or running version of your Docker image, but a Docker container. So the Docker container just has it has all the files and all the dependencies that have been declared in the Docker file, and executes the REST API the way that you have declared it in the Docker file, and just like what well, just like how we stand up Docker container for the REST API, we can stand out the Docker container for our MongoDB Docker image. And then, of course, these containers can talk to each other on all of these magic, I mean, it only works just because you also have the Docker engine of the same Docker engine that you have in your box, you will have it available in a production environment. So here, as long as you have the Docker engine available in whichever machine, you want to go ahead and run your Docker image, then your Docker image is guaranteed to be able to run as a Docker container in that environment don't need that you need is a Docker engine. And that brings a lot of benefits along the way. The other thing is that you not only just can just run one instance of your Docker container, you can actually run multiple instances of your local container. So as you need to scale up more and more, perhaps because you have too many users, then you can use to start spinning up more and more copies of that Docker image into Docker containers in production, without having to incur into a lot of hassles to be able to provision more and more environments. So, lots of benefits about Docker really here, started with efficient use a resource usage. So as opposed to the case of having to stand up new virtual machines or new physical servers, you don't have to really enter into a lot of new resources. spinning up a new Docker image does not take a lot of RAM does not take a lot of this space, because there's a lot of caching happening in there by by this thing called layers in in Docker. So a lot of caching, memory is going to is going to only going to increase in terms of what, what exactly is needed by for your, for your, for your image for your service, free REST API. And so you can really fit much more instances of your REST API, in this case, also have your database, many more instances in the same production box. As you could before, just feed one instance of your REST API, or your or your MongoDB container, or a MongoDB database, in the same production box, right, you can fit much more. By using containers, there's also faster start, because because Docker, the Docker engine is able to cache all these, these layers are only the very first time that it needs to pull down the Docker image, it will do that with all the layers apart from their own, it will be able to just pull only the layers that have changed. And so that allows it to really start very fast. So you don't have to also you don't have to boot up an entire operating system, just to put a your your app, right. So the operating system is already in place, you just need to start your app. And Docker is able to do that very, very fast. There's also isolation if each of these containers is running in a in a completely isolated way. So it doesn't matter what's going on in the actual production host machine, or what's happening in any other containers running in the box. Each of the containers are running in isolation. And so from their point of view, they are the only thing happening at that point in time in that environment. So that that gives you a lot of benefits from that side. And then also you can you can think of these containers have been able to run anywhere. And because like I said, as long as there's a Docker engine running in your production machine, you're guaranteed to be able to run your Docker container in there. So lots of portability. And finally, scalability, like I mentioned, in the same in the same space, where before, you will be able to run just one instance of your REST API, like in the case of virtual machine. Now you can actually run multiple instances of your local container with using much, much, much less amount of resources in there. So you can really scale significantly by using Docker containers. Let's see now what we need to do to containerize or Docker eyes our REST API. To create the Docker image for a REST API, the first thing we need to do is create the corresponding Docker file. However, before doing that, and to keep things simple, we will update our REST API so that it no longer performs HTTPS redirection, and allows the use of the HTTP address only. The use of HTTPS from here on is a topic out of the scope of this tutorial. So what does this mean? If you remember, we do have two URLs configured for a REST API. And those are configured in our lunch settings file on their properties. And you said Lisa, Jason, application URL, we do have HTTPS localhost 5001 and HTTP localhost 5000. And the way that things are configured right now, if anybody tries to access HTTP localhost 5000, they will get redirected into HTTPS localhost 5001. You want to test this, what you can do is just launch the app. So I'll do f5 here. And I'll open postman. And normally we would go to HTTPS localhost 5001. But I'll change this into HTTP localhost 5000. And in this case, I'll actually open the postman console down here to see what's happening behind the scenes. And I'll do sent to query for items. The query succeeded. But then if you see there are two calls in here, the first one for HTTP localhost 5000 slash items. It returned 307 code, which means a redirect. And then that was followed by a call to HTTPS localhost 5001 slash items. So that's a the redirect that has been configured right now is what we want to change for the Docker case, at least. So how do we change this? Going back to VS code, and I'll just stop the app and close this for now. This is configured in startup.cs. In under the Configure method, we have this line here, up that use HTTPS redirection So he turns to me that when you run inside the Docker file, well, sorry, inside the Docker container, the ASP net environment switches from development into production. And this is what we can use to put a conditional on this on this line. So we can say is, if, and that is development, then we will allow the HTTPS redirection, but otherwise, we will not allow. That's the only change that we're going to make here. We will see how this works. Actually, when we have the Docker container ready to go. This point, I'll just close this. And now we actually want to generate or actually to create this Docker file. So there's two ways to create a Docker file, either you can create it manually, or you can generate it. For this tutorial, we will have to speed things up, we will generate. So you need a Docker file. Well, I would recommend if you're a business to recode, is to use a Docker extension for Visual Studio code. And that you can find if you go to the extensions hub, you can just type Docker here. And then you will go ahead and install the extension. And now close this. And now what you can do is just say, view command palette, and then you can type Docker Docker files to workspace is the first option there. Now you get to pick the platform of the Docker image we're going to create in our case will be dotnet. ASP. NET Core, then you got to pick the operating system of the container, in our case is going to be Linux, just because it's the most popular option most of the time. And then you get to pick the port that you're going to release in in in within that container. In our case, it's going to be Port 80. And finally, if you want to generate a Docker compose file, we will not use this in this tutorial to hit No. And now if you go to our explorer here, you're going to see there's a couple of new files, we have the Docker file and the Docker ignore file. So let's start by looking at the Docker file. In the Docker file, each line that you can see here represents a one set of instructions that are going to be applied as the Docker image or Docker image is going to be built. And each of these lines will also generate what we call a layer that represents the changes that are happening from one line to the next line. And that's what helps a lot in terms of a caching of steps as we do subsequent builds of this Docker image. So the first time we will build it, it will take time. And this was a good time. So silicon times is going to be much faster. Now let's go one by line by line here to understand what's going on. So the first thing that's happening is we're saying that we will be building out our image base it on the dotnet ASP net image, specifically version five, zero, right. So that's, that's the way that you that you start by saying, Where do you want to go from by specifying dotnet. asp. net, you're guaranteed to be building a your image based on working ASP net environment, in this case, a five zero environment that has all the dependencies that are needed to run an ASP. NET app. And not just that the ASP net image has a has a at the same time has been built based on the correct always based on wait where you're running your image on in our case, since we're going to be running it in a Linux machine. That will include all the dependencies to run an ASP NET Core app, or the net five app in Linux. Now, we're also saying this is five zero as base. This means that this is going to be a our first stage of the building the container. This is a good segue into the concept of multistage builds, which is what's enabled here. This means that there will be more than one stage on the build process. And in each stage, you can specify a different set of instructions that may have nothing to do with the instructions executed in some other stage. So for instance, here we're saying, so this is the first stage and we'll call it a base. And in this stage, we'll go from a dotnet. asp. net, which is the runtime image for ASP. NET five work there is going to be slash app means everything that happens after this will happen in the in the app directory. And then that we expose a port 80 this line actually means does not mean much is just a kind of a documentation field. The way that you expose a port is a bit different actually. But it is a there's a convention to specify the port that they are policing in. Now that temporarily finishes that first stage and in the next nine In line five, we are going into our next stage that we're calling built. And the interesting part about this stage is that it comes from a another base image, if you notice this is coming from dotnet, SDK to dotnet. SDK five series are supposed to dotnet. asp. net. So SDK is the image that has all the build tools, and all the libraries, everything that's needed to build and dotnet five app, which is not the saying that you need to just run other than five AP, right. So this, whatever is coming in this ACP image is potentially much bigger. There's a much, much more files, compilers and stuff in there that are needed for building the container, but not needed for just running. So that means that your final image that's going to go actually from the base image is potentially going to be much smaller than the image that we're going to use to build your container. So we start with this stage, in this case, it worked there is going to be a slash src. So that's where we're going to place any files from here on. And that's exactly what we're doing. Then in the next line, we're saying, Okay, so let's copy the catalog, that CS profile, the one that defines our project into the root of the current location. And they will run a dotnet restore, on that break. So that brings in all the nougat packages that are needed, then we say, OK, so we have restored all the packages, now copy every other a file that's needed a folder up. So that includes all the files that you can see on the left side, except for a few sections, but most of the files are included here. And we'll talk about that in a moment. And then there's this line here, that's actually not that much needed. Because as you can see, it's pretty much the same as the as line six. So we will actually delete this in a moment. And then we go into the actual build process, where we say, hey, go ahead and perform a dotnet built on catalog that says Prague, we're modifying a Korean configuration to not be the bug anymore, we want to release version of the app to optimize it for the production environment. And the results of that build should go into the slash app slash build directory. So currently, that finishes our build stage. So it's this section here. And then we're switching to yet another stage that we're calling it publish. In the bullish stage, what we saying is, actually, we're going to go from the build stage. So notice, now we're going from build is the stage that we just created. And we will go from there and name it as bullish, and just execute the dotnet publish command. with similar set of parameters and the previous one, just changing the output directory. So that then polish, what it does is it creates a new folder, in this case called Polish with all the files are needed in the right shape, to just execute the app. Now at this point, I'd like to point out that I find a few of these lines are a little bit redundant. So we could simplify things a little bit here. So I don't think we need to separate both a build and abolish stage. So I'm going to make a couple of changes here. So I'm going to actually remove these a warfare source line, because we already have these in line six. So I'm going to remove that. And I'm going to also remove dotnet build just because dotnet Polish also performs dotnet build for us. So there's no need for two separate lines. And I'm actually going to completely remove the Polish stage because their build stage should be good enough for what we did here. So now we just have one stage called built. One second stage called built, that will end up by running duct and polish. And all the files that we need should end up being in Polish. Now in 912, we go back to our initial basic stage, build stage, and we're going to be calling it as final. Right. So now we're pretty much finishing what's what's going on here. So we switch again to the app directory. And then we're saying what we're saying is, okay, so now let's copy from the foolish build stage, we net, which in our case is no longer there, we actually opted for built. So I'm going to actually copy this and change it into build. So from the build stage, go ahead and copy whatever is in the app slash Polish directory, the one that will replace all the files, copy all of that into recording directory, which will be slash app. And finally, we'll define the entry point for our app. So this is how we define how to start our REST API. And in our case, that will be just by hitting the we're executing the dotnet command with the catalog that dll file. That's all that's needed to start our, our REST API. With this Docker file, we're pretty much ready to build our image. But before doing that, what I wanted to do is just show you about the dot Docker ignore file. So this Docker ignore file, what it does is, it defines a series of files and directories that you want to exclude from the Docker image. So there may be a one or more files that you don't want to include in the Docker image, because it makes no sense to close. For instance, the stuff that we have on there that VS code is really only useful for development purposes. But it means he has, it makes no sense to include that into the Docker image. So for instance, this line here specifies Hey, use, go ahead and exclude everything under slash that VS code. And the same thing for a bunch of other files and directories. So a good file to not forget to keep in mind, otherwise, your image will end up being bigger than it is. So with that, we should be ready to start building the array image. So what I'm going to do is just open a new terminal. And to build the image, what you do is use a Docker is Eli. So what we're going to say is Docker build, then you, you have to specify attack, I mean the name for the image and attack for it. So that you do be the dash D, qualifier. And then we will give it a name, the name will be catalog, and then you give it a tag, which in our case, let's say is going to be v one. And finally you specify the directory from which you're going to execute the command. In our case, that's going to be the current directory, which is specified by the.so. I'll hit Enter. And that's going to go ahead and build the image. So first thing we need to do is go ahead and download any of them base images. In our case, that will be the dotnet ASP net image, the runtime image will go ahead and do that. And then for the second layer for the second build stage needs to pull in the dotnet SDK, a five zero SDK, a five zero image, which may take a little bit more because it's speaker, and then it proceeds to perform the actual build process within the the image. So Docker restore, and they are to publish, and then all the other steps that ended up creating that image. So at this point, we have an image ready. And like I said, each of the lines going back to a local file, each of the lines here represents one layer that maps to each of the steps that you see here. So he says step, a bunch of steps here. So step one of 13, to 13, three of 13. Each of these will correspond to each of the lines that you can see on the Docker file. So these are the layers that will be cached from here on, so that you don't have to do them again. So in our case, if we don't have it, if you don't make any change, if you've tried to do Docker build dash D, the same command again, I hit Enter, really mostly nothing happens because everything is cached. So only if you make some changes, then those some of these layers may need to be executed again. Now, one thing to remember is that this is not the only container that we need for our REST API. We also have the MongoDB container, which is the one that handles that access for us our database server, right and which is the one that has our database. So we need to make sure that our new container for the REST API is able to talk to the MongoDB container. And the way to do that, at least in the local box, is by setting up what we call a Docker network. And having both containers join that that Docker network. So how do we deal with this network to create a network, the only thing that you have to do is just say, Docker, network, create, add use, give it a name. So we will say that five tutorial and that crazy network if you want to see the the existing networks, you can do Docker network LS. And you will see we have the our net 530 network already created. So now when we run our containers, we should take advantage of that network. So what I'm going to do is first make sure that I'm not running the MongoDB container yet. So I'll do docker ps, the MongoDB container is running right now. So I'm going to stop it Docker stop Mongo to that stopped, and I'm going to run once again, the same command that we've been using so far to run our container. let me paste that here. Same command. But I'm going to add one modify here that says network equals and the network name that you use was defined in this case, net five tutorial. So that makes a disk container a joint that did work. So I'll say Mongo, the name of the Docker image, so hit enter. And then the MongoDB container is running in that network. After doing that, we're ready to actually start running our a catalog container, which by the way, if used to Docker images, you should be able to see our created image. As you can see, we do have catalog be one, ready to be executed, as well as the Docker images for the dotnet. SDK, and the dotnet, ASP net, runtime, and Mako. So to run our Docker image, we're going to do something very similar to what we did with MongoDB. So we'll start by saying, Docker run. And then instead of doing dash D, for the dash, we'll do dash ID for interactive, that allows us to keep our terminal connected to the Docker run process, just to see whatever whichever logs are coming out of that container. And then we will do the RM so that whenever we stopped the container, it actually it gets deleted, so we don't keep hanging around. And now we specify the port, similar as we did with MongoDB. Now we have to specify which is the port that's going to be mapped from our local machine into the container. In our case, let's pick ADHD, it doesn't have to be it, you can use any other body port. And that is mapped to the internal port in the Docker image. Now, for ASP net, and that five images. The base image itself, it's been a runtime image defines or overwrite the port where the app executes, at least for HTTP. So that port is 80. So regardless of the fact that we've been using Port 5000, for local development, when we base our Docker image in the ASP NET Core runtime image, the port is overrated into 80. So you will have to specify 80. And if you don't want to use 80, there are ways to specify the port that you want to use in your degree in your Docker file. But in our case, the Port 80 will be just fine. Now we have to remember that in order for our app to connect to MongoDB, we have to specify a series of settings, right. So if you remember when we go to app settings that Jason, we have this MongoDB Settings section, where we specify host, port and user. And not only that, it will remember going back to Settings MongoDB settings, we specify host port user and also password which is coming from secret manager. So in this case, since we are trying to talk to Mongo to MongoDB. From within the container, we can no longer use just localhost to reach out to it. They remember that each of these, each of the apps running inside of the container, both arrest API and MongoDB are running in an isolated way. And they can no longer resolve things by localhost. So for our REST API to talk to the MongoDB container, it has to do it via the name of the container of MongoDB. In our case, remember that we gave it the name of Mongo. So we have to override the host name. To talk to Mongo, we don't have to touch it update the JSON file for this, what we can do is just take advantage of the configuration system of 35 to be able to override the settings. So this one going to be setting section can be totally overridden by environment variables. And that's what we're going to do now. So as long as we follow the convention, we should be able to make that happen. So I'm going to say dash E, that's the way that you define an environment variable in in Docker, I'm going to say, I'm going to use MongoDB settings. So just copy that. And then we'll say colon host. And that host is going to be Mongo, the name of the Mongo container. So that's how you can override this localhost as specified here. Now the same way that we did that, we need to specify a password because the password that we've been using so far is stored in the secret manager. And the secret manager is only being used for development, a development purposes is only available in development environment, it is not available in production, and the Docker image, the Docker container is really going to be running in a production environment. So how do we feed that password, same thing that we did a, just now we'll say MongoDB settings. Let's not forget to also add dash in MongoDB, settings, password, and then we specify the password as bound word one. And that's it. And then let's not forget that we need to join also this container into the same network as the previous container. They won't go on the inner so that's going to be network med five tutorial, make sure this is exactly the same network that you used before. And finally the name of the container and the name of the image and the deck. So that will be catalog. Be one and I think I may have a couple of mistakes. Here. So the first thing might be, let's see, yeah, so it should be dash dash RM as opposed to a dash RM. And the next one would be Yeah. So this one should be equals supposed to column. And then I'll hit enter. So that has started our Docker container. And as you can see, our hosting environment has now changed from development to production. So production is the environment that will be reflected when you run the Docker image as opposed to development anymore. Now let's see if things are working properly, we should be able to reach out to our REST API at Port 8080. So let's open up postman. And now let's just switch from Port 5000, to Port 8080. And let's see what happens send. And through to be told, the API keeps working. But now as you can see, we're hitting a port 8080. So things are happening within the Docker container. Also, notice how we did not get a redirect anymore. So instead of getting at 307, like we did before, we got 200 right away. So there's no more redirect happening in there, we're just going to be at the HTTP endpoint. Now to keep things interesting, let's actually post one more item here via our post tab over here. And I'll do the same thing. I'll switch from HTTPS to http. And then I'll do Port 8080. The 80. And so let's say let's say that we bring in back that antidote for you. So sometime in the past, and then I'll do price 15. an hour heat sent. And as you can see, I'll just close the console. Now, the audio has been created. Now really, the interesting part about Docker and Docker images, is not just being able to create them, right, but also to be able to share them so that they can be used by either other persons or some other systems. So how could we share this Docker image that we have in our box now with some somebody else, right, so use for the sake of this tutorial, we'll do something very simple to see how this can happen, we're going to take advantage of a service called Docker Hub, which you can find Let me open up the browser here. You can find at hub that docker.com. So this is the place that the creators of Docker offer, so that people can publicly share their Docker images. So creating an account here is totally free. So feel free to try it out. So you'd have to come up with some Docker ID, I mean, some kind of a username and a password. And then you can have your own account in Docker Hub. So how can I get my image Polish into Docker Hub. So let's go back to Visual Studio code. And I'll stop my Docker container now, by doing Ctrl. C. And the first thing that I'm going to do is actually logging in into Docker Hub. So once you have an account in there, you should be able to do a simple Docker login to be able to start pushing image in there are a way to do is just say, Docker login. So this is going to ask me for my user username, my case is, will you see it will ask for my password. And now I'm logged in. So now in order to get our currently existing image into Docker Hub, we just need to do a little bit of retagging to tell it where we want to place this image. So let's leave our images that once again, local images. So here's the mission catalog b1. So we want we want to do is just retag these in in this way. So let's do Docker tag, catalog be one that's the Korean, the green tag, catalog, big one. And then our target tag is going to be starting with our username, my username, in this case, for you see, and then slash the name of the of the image in Docker Hub, when you get to Docker Hub is going to be called a repository. And so that was during August is going to be catalog. It doesn't have to be you can choose. But I'd like to give it just the same as we had before. So you can typically see a slash catalog be one, hit Enter. And like I said, this is just a tag. So if I do Docker images again, we're going to find it now you have catalog B one, and who you see slash catalog B one. But if you notice the image ID and you look closely, you'll see that the ID that both of these images have is pretty much the same So it's really you can think of the stacks as just pointers into one of the images. But with this retag, we are able to now actually push the image into Docker Hub. So what I'm going to do now is just say, Docker push our new newly written image, catalog b1, hit Enter. And this starts the process to upload, not just our REST API dogri mesh, but all the layers that are composing these REST API needs to go into Docker Hub. So remember that our Docker images Docker base is the ASP NET Core runtime image. And that one, in turn is vetted in some distribution of Linux in this case. So all of those things need to go into Docker Hub, so that anybody else got in the future, just pull that image and start using. So these may take a while because it's an upload, upload task. Alright, so the image finish uploading. And now if I go back to Docker Hub, where I'm going to do is actually sign in with my account here. And as you can see, I do have my image just uploaded a few seconds ago, who you see slash catalog. And here's the one fact that we have right now. So that would be one. So let's see that let's play the role of somebody that does not have this image in their system right now, and that they want to use it. In that case, what they can do is either do a Docker pull, or just run the image. So let me show you what I mean. So the image is now available in Docker Hub. So I go back to VS code. And what I'm going to do is just completely remove the image that we have currently in our system. So let's do Docker images, once again, and we're going to do is just remove these two images, so that it gets completely out of the system. And to do that, I'll do Docker Rmi, will you see slash catalog v one, and Docker Rmi, catalog, v one. So now there should be no catalog image anymore. In my system, z only, I only have these three images right now. So now, the only thing that I'm going to do is use to Docker log out to simulate somebody that actually has no access to my Docker Docker registry. But since the image is public, they should be able to pull it. So in order to pull the image, you can either do the local Docker pool operation, so local pool, or you can run it right away. So we can run it in the same way that we run it before. So let me show you is going to be pretty much the same command line, I'm going to actually copy paste here. But now instead of you're saying catalog b1, what we can say is polisi, slash, catalog, b1. So just keep in mind, so I am at this point, I am somebody that has never, that has never had access to the catalog, REST API service, I have no access to the Docker file or anything about how to build this image, I just want to run it for the very first time. So I do this command line and hit enter. It says yeah, I cannot find this image locally. So we'll go ahead and actually pull it from Docker Hub, and then run it. And as you can see, it is already running. If I go back to postman, and I try to query for items again. I get my items from this Docker image. So that's how you can publish or push your Docker image into what we call a Container Registry, in this case, Docker Hub, and then it is pulled back, potentially in some other machine. That's how you can share it. So we may end up using some other form of Docker registry in future videos. But for now, I just wanted to show you how you can do the sharing of Docker images across systems. In this episode of The dotnet five REST API tutorial, we continue our path towards deploying the REST API to a production environment by using Kubernetes. We will talk about the implications of running containers outside of the dead box with no downtime and how Kubernetes is a perfect fit for these and the many other challenges of running distributed systems resiliently. Today you will learn why a container orchestrator is needed. What is Kubernetes and which are its basic components. How grenades enables resilient distributed systems, how to stand up a basic units closer in your box, how to deploy your REST API and one of the to coordinate this, and how to scale a Kubernetes deployment. So if you remember from the previous video, we talked about these orange box, which so far we've been talking about it is the production environment, right? In this case, let's just call it an old Indian, this is the, this is the either the physical, or the virtual machine, where we're going to be running our Docker engine, right? These things to this Docker engine, that were able to run a bunch of containers in this dog, this could be either our API containers, or also our MongoDB container or many other containers, right, that we want to run in this node. However, a few interesting questions start arising as we move forward with this approach, right? For instance, who takes care of pulling and running containers. So I mean, can imagine that without any forter sort of automation, somebody will have to come to this box, and actually start doing Docker run for each of the containers that we want to run in this box? Right? So that's an interesting question. So either some information somebody saw somebody has to take care of this, how to run the containers, right? So who knows? Or where do you see the reading? All these different environment, variables, secrets, and different common arguments that we have to fit into Docker run, to be able to run the containers exactly the right way, for each of the cases? And what if, what if we don't have enough container instances? Right? So what if we need more, so something or somebody has to start spinning up more and more instances, as as needed, both for a recipe containers or for any other containers that we want, we may have in this box? Right? And then also, we may win, we may not be able to fit, just I mean, we can only fit so many containers in a box, right? So at some point, we may need to introduce get way more nodes, right? And then somebody has to decide if the containers are going to be created are going to go into in this case to node node two, node three and two, node n. Right? So who decides this distance here? So do we have a person that is looking at the different stats for each of these nodes, and just decides to do Docker run in each of these indices machines? How does that work? Also, a are the containers healthy? So what happens if one of these containers crashes? What do we do? Who is on point to make sure that we bring back this failed container so that we keep having as many as we wanted? To start with? Also, where do we store all the secrets? For the restore to database files for MongoDB? database? Where do you put all these? How do we enable containers to talk to each other? Right? Because we know that our REST API containers need to talk to our MongoDB container. But how do we enable that communication in so far, we've been using these Docker network, right to make them communicate. But as we have more boxes, more containers, how to make sure that they can all talk to each other. And one more thing, how do we read this container from the outside, right? Because all of these containers are running in the box. But all of them are running with some port a opened locally. But then what if somebody comes from the outside? What will be that public IP that somebody from the outside will use to talk to these containers? And if they talk to them? Which of all the instances would serve the request? Because we have so many instances in there who decides which is the right instance, for the request that's coming in? So all of these questions? How can we solve all these challenges? Well, this is exactly the reason why we want to introduce an orchestrator tool like Kubernetes. So enter Kubernetes so as we describe what goons can do, let's they think again about this These dots, right? So we have, let's say we have these three nodes. And we need to start placing containers in them. And we have to do a bunch of things to get these containers up and running in the right way. So instead of having to have an individual person, or some sort of a script that needs to run, to be able to allocate, and to make sure that everything is going properly in across these nodes, we're going to be introducing this component called Well, I've got a series of components that we call the control plane in Kubernetes. So the control plane has several components that take care of all the the it's kind of the brain of coronaries. So he decides how to schedule the container into the different nodes, he decides what to do if one of these, one of these containers is destroyed, how to bring back one, one more how to let them communicate to each other, and a bunch of decisions, right. So for instance, when we want to get one new container deployed to one of these nodes, or we can do is via the control plane, we can create a deployment, what this deployment is going to do deployments, by the way, one of the resources inside grenades. And so what is flaming can do is go ahead, find the image that we need in the Container Registry, and then allocate what we call a port for that, for the container that will be will pulling in now the ports are really the smallest deployable unit of computing that you can create, and manage inside Kubernetes. Right. So the pod, it has a similarity to what we call, if you think a pot of wealth, right that I guess that's the symbol for Docker. But it's a group of one or more containers that are sharing, storage and network resources. And it The report also declares how to run the containers inside them, right. So you will always be working more with bought that with containers, you can read with the containers directly, you will only work with bots. So for instance, in this part, we will have, let's say one container, which is a very common case to use have one container per pod. But you don't have to have one, you can start standing up your deployment object, you can start standing up more than one container for let's say this is for catalog race API. But in this first note, we don't have to just have this catalog API, right. So we could have some other port for some other service that in this case has not one but two containers inside of it. More than that, we will have also a port for our Mongo for a Mongo container, right that we need to also pull in, that has access also to these database database needs to get a granted access to some storage to be able to store the database files. But then the thing is that the this catalog posts don't have to be using node one, right? So when we run out of space, we may want to take advantage of other nodes like no two here, right. So again, the control plane will take care of deciding where to put these these ports across the entire set of nodes that we have here. So in this case, we have seen three, but you can think that this can be an entire form of dozens and dozens of nodes, and then control plane will decide which is the node that is the perfect fit for the ports that need to be allocated. Right, if Lemmon declares that it needs three ports. So this may be Was it the one way that the polls are distributed? If deployment says no, I need four pots that we may want to deploy get another pot pot for into node three because notaries use free at this point, right? Same way with some other pod. He may want to be allocated somewhere else. There's no space in node one. So let's just put it in no tree. Let's see, just because no tree has so much memory available, right? The other thing is that what three, let's say for three wants to talk to utterly all of our catalog boards, we want to talk to the database, right? So how do they do that? So there's this object called the service in coordinates. And the service allows us to reach the other components that are available. So what else in the cluster? So in this case, I'm saying, well, I want to reach out to the Mongo service via that Mongo service, I am actually able to reach to the database. In a similar way, if we have an external client that wants to talk to our catalog, a REST API, how can I reach it? So again, we stand up a catalog service, which can reach in our case for now ingesting the localhost, but eventually it could be a public IP. And then this client can reach to the to this service and be at that service. It can reach not just one but all of the pods that are running behind the Behind the surface, right, so it's a way to route to those to those bots. So all of these is what we call a meet all of these components is what we call The Goonies cluster, right? The suit of all these components. And now, what I'm what I'm showing here is really just just the tip of the iceberg in terms of all the possible resources. And, and the series of configurations and the capabilities that can be a use within coordinates. Really it there's a lot that can be done with coronaries and but here, we'll just explore just a few of them to understand how it works. And so in terms of benefits of using Kubernetes, one of the main things about this is the ability to turn desired state into active state. So like I said, we create a deployment object where we say, hey, I want three copies of the catalog service. So that is a solid state. So Kubernetes via the control plane, we'll have to figure out how to make those four, four instances of the catalog container available as support somewhere in the series of nodes that we have available. If you have three nodes to find space in those two nodes, if you just had one node, so figured out how to allocate that in that one node, or we could have hundreds of nodes, right. So decided to stay in the Draco state is a key feature of Kubernetes. Then, like I said, select nodes to run the bots. So it the control Bay has knowledge of the stats of features installed. So depending on the amount of CPU, or the amount of RAM available in each of the nodes, it is able to allocate the port in the right place. It also allows for self healing. And so if he detects that one of the ports, let's say port three is just easiest to destroy for any reason, it should be able to automatically bring back another part. So let's say that a note to the entire note just goes down, right? If that happens, then a control plane will know that it is able to I mean, that is missing one note, sorry, one port, and then it needs to allocate that boat somewhere else, either node one or node three in this case. So this is the self healing capability of Kubernetes. That's super handy. It also is able to store configuration secrets. So he has a it has a place to store all the configuration that you need for your for the services, and also to store to safely store sensitive information and like secrets, so somewhere in there so that they cannot be compromised. Like I said, he provides service discovery and load balancing. So when the client calls and talked to the catalog service, it is able to be directed to the right at one of these nodes following following some algorithm to load balance across them. It also ensures no downtime. Because whenever it it, let's say that we want to deploy a new version of our catalog, Docker image right across all of these spots, it will not just destroy all the pods at once and bring back a bunch of pods with a new image, it actually those will will slowly roll out the new version of the of the image as as new ports as it starts destroying the older port. So only when it configures that new, the new instances of the ports are available, he will start getting rid of the older ones. So that way it keeps I mean, it makes sure that there's no downtime for clients. He can also auto scale. So it can be configured to say hey, if there's so much CPU being used across the across all of our nodes just spin up even a more pots in any order available nodes to satisfy the demand. So, within this tutorial, we will be doing scaling exercise manually, but corneas can be also configured be configured to do the scaling automatically for you. It also disabled to on demand automatic storage, so you can easily declare that you want so much storage for your port, and granary will I mean without having you don't have to know exactly where that storage is going to be. You'd have to say hey, coordinates, I need storage and grenades will be in charge to figure out where to find the storage and make it available for the port. And finally, it provides a what we call gradual rollout and rollback use, just like I said, it will gradually start bringing in new ports as needed. And also if there's some issues with some ports, it is able to roll them back to a healthy version. So now that we know what Kubernetes is, let's see how to get our catalog REST API and the MongoDB database deployed into a local Kubernetes cluster. To get started with Kubernetes The first thing that we're going to need is a Kubernetes cluster. locally. If you're already using Docker in your box, you already have it An easy way to send up a simple local velocity for development purposes. Let me show you how. If you go to your Windows taskbar, you should be able to find this Docker icon. You can right click this I can select Settings. And this opens Docker settings in your box, maximize this. And here, what you're looking for is the q&a section on the left side, and then enable coordinators over here, so I'll just click on it, and then click Apply, restart and then click Install. Now this is going to take a while if this is the first time that you're enabling coronaries, because this is going to set up a local cluster simple with just one node. But still it is a local cluster, and that Docker needs to download a bunch of Docker images for all the components of Kubernetes, into your box to that. So that may take a while. In my case, I already have all these images downloaded, so it was a bit faster. What is complete we're looking for is this message here that says grenade is running, it should say running and it should be green, and then you know that you're good to go. So I'll just close this window now. With the Kubernetes cluster up and running, one of the first things that I like to do is to make sure that I am connected to the correct Kubernetes cluster. And that we can do via the cube control command line tool, which is the command line tool to interact with Kubernetes. These tools should be already installed for you with your Docker installation. So you should be able to start using it right away. I'll open up a brand new terminal. And what I'm going to do is just type cube control config. current context, hit Enter. And that is giving me back Docker desktop. So indeed, Docker desktop is the is the name of the cluster installed by Docker, once we enabled the Kubernetes cluster, so we are good to go on that side. Now it is time to start creating or declaring how we want to deploy the components into Kubernetes. For our REST API and database, do that we will need to write a few yamo files. To make this simpler. What I'd like to do is to take advantage of the granaries VS code extension. So to do that, I'll first just close this terminal. And I'll go to the extensions hub. And I'll search for Grenada is this one here should be the first heat, I'll just say install should take a few seconds. And now it's ready. So I'll close this. What I'll do now is go back to our file explorer, and I'm going to create a folder to start storing all the files that we need to deploy our resources to Kubernetes. So this is going to be our Kubernetes folder, it can really be any name as you please. And then the first one we're going to create here is going to be named catalog the job. And I'm naming it this way, because this will declare all the resources that we need to deploy our catalog REST API to Kubernetes. And also to keep things simple. To speed up the process, I'm going to take advantage of that goodness extension that we have installed to generate a little bit of code here. So I'll just say deploy, and that pops up a little bit of IntelliSense, as you can see, and then we just have to click it. And that will give us a basic shape for our deployment resource. Now the plugin resource is what you would use to declare the desired state of the containers or specifically the ports that you want to get deployed into Kubernetes. For in this case for a REST API. So let's understand what what this file means. So if you see the first line declares what we call the API version, this is something that all the coronis resources will will have. And this allows you to specify what is the API surface that you want to take advantage of in Kubernetes. So depending on the version you pick here, you will have access to more or less features of the resource that you're configuring, in this case, a deployment resource. second line declares the kind as as we know, is a payment object. And then we go to metadata name. Metadata name defines the name for these deployments. So in our case, we'll use name it catalog. And then we go to the specs section. The first part of the suspects section is the what we call the selector. And the selector is what we use to specify how is this deployment going to select the port that is it is going to manage. So in this case, it is saying Well, I'm going to say to manage all the pots that have the following labels. And in this case, we just have one label, it is called app. And then there's a value, the value that we're going to assign here is going to be good. So all the ports that have an app label name with the value catalog, will be managed by this deployment. Then we keep going into the template section. So here is where we're going to declare all of these containers that are going to be included in the, in this deployment. So one of the first things to declare here is the label or the labels for these for the bots. In this case, we're going to name this this bot as catalog that's going to be the label. So that's the way that we can identify all the bots that are related to catalog in this case, and this one has to match exactly the label that we just typed a moment ago, so that the deployment can actually manage these bots. Then we will forward to the most interesting section, which is a spec on the template. And the first thing that we're going to find here is containers. So here, we declare the list of containers that are going to be included in this deployment. And the first thing that we have to do for this very first container is we'll give it a name. So again, to keep things simple, we'll just name it the catalog. And then we have to declare, which is the image that we are going to be deployed. In our case, we're just going to be using that image that we created in the previous video that we deployed to Docker Hub. And then in my case, it was blue sea catalog, b1. So we are saying we are going to be pulling down into Kubernetes, this image named who you see catalog be one that we were saying there, but you could specify any image that you want here. Next, we go into the resources section. So here's where you declare what resources specifically in terms of memory and CPU, in this case, what resources are needed from the Kubernetes node, in order to run your REST API. In this case, I'm just saying, Well, I'm going to be needing 128 megabytes, which by the way, while may be right will be equivalent roughly to 1024 gigabytes. So that is the full value here, you could change this according to your needs. And then on the other side, we have the CPU where we're saying that we want to use 500 million CPU. So this is an interesting notation. And what it really means is, this is similar to say, I'll just type here would be kind of like 0.5 CPU, so roughly half CPU, just to understand it better. So 500. So basically, we're saying we are good to go with one half CPU for our REST API, which would be definitely enough for us. Next, let me scroll down a bit. We have the ports. So here's the word declare, which is the port that that our container is exposing. And we can communicate to in order to access the REST API. In our case, we're going to do just as we did in the previous video, where we mapped into the into port 80. Because we said that they are base ASP NET Core image overrides our port, and by using Port 80. So we will be using the same port, or 80. So that's a port inside the container where we can reach the REST API. The next thing that we're going to need in this deployment is a few environment variables. Because if you remember, when we run our container, we had to specify both the host to be able for it to be able to talk to our MongoDB container, and also the password for the user that connects to that to that database. So how do we specify environment variables in this case, it's fairly straightforward. We can use the M section, so you just type M. And then you have to declare key app name value pairs for each of the environment variables. The first of all we're going to declare is the one for host. And then if you remember, in app settings JSON, which I'm going to open right now quickly, we have this hierarchy of settings, right we have MongoDB settings. And in what we said is we have host or user and password. So I'll go back to catalog jammal. And we have to follow that same hierarchy. So I'll do Mongo DB settings. And then the way to separate add to go into the hierarchy in in this java file will be be a double underscore. And remember when we run will be passing variables into the container, we use colon, one in this java file, the convention we're going to use is going to be double underscore. So that's How you address these different settings. And then we'll give it a value. The value for the host in coronaries is going to be MongoDB. service. And we'll see in a moment how we define this MongoDB service. But for now, so yes, this is how we can address the MongoDB container that we're going to declare later on. Next, we need an environment variable for the password. But before we can declare it, we actually have to create this password, add ingredients. And luckily, coneys has this built in support for secrets. sensitive information like that. So in order to do that we're going to do is just open my terminal. And I'm going to actually use a shortcut here Ctrl J, that opens up the last terminal we used and scroll down a little bit. And then we're going to type here is the cube control an option to be able to create a secret. So that would be cube CTL. Create secret. And then I'll type generic. Generic is the type of circuit that we can use in this case, but there's a few other options that you that you can also use here, then it's fine for us. We'll name it, catalog secrets. And I'll use spooler, just because you can actually put multiple secrets in one of these secrets here. But we're only going to be using one. And in order to type it directly in the command line, what you do is say from literal. And then you have to specify the name and the value for the secret. So the name is going to be MongoDB. Password. and the value is going to be just like we did before as bad bound word one. And then I'll hit enter. So that created the secret. Now that we have created the secret, we can actually go ahead and declare it and feed it into an environment variable. To do that, we'll do something similar. So we'll say name. And again, we'll follow the the hierarchy, right, so MongoDB settings, in this case, double underscore is going to be password. And then in this case, we don't want to use the value, we want to read it from the secret. And to read it from the secret what we can say is value from Enter. And we'll say secret key ref. So we're referencing a secret that's named name is going to be catalog secrets is the name that we gave the secret. And the actual key within that catalog secrets is going to be Mongo DB. Password. So that's how you can address a secret from the declaration of an environment variable in Kubernetes. That's looking good. I'll close this terminal again, have more space here. And the next thing that we want to specify here is our our health probes. So the health probes is a mechanism that enables coronaries to constantly monitor the health of our race API, by using the health checks that we already defined. If you remember, a few episodes ago, we declared some health checks in the REST API. So now it's we're gonna we can actually, we can actually use them to let us know if our containers are in good shape or not. And he remember we had both liveness and readiness probe. So both of them we're going to be using here. So start with the liveness probe, and to declare it where you can use his liveness probe. And then the kind of probe that there's a few kinds of probe as well, what I'm going to be using here is the HTTP HTTP GET type of probe, which is just going to call some HTTP path with the get verb into the API. And so the path that it needs to use is, if you remember, that would be held live. And it needs to use Port 80 for that one. And that's it, that will be the biggest probe. And I'll just copy this to define our readiness probe. readiness probe is going to be very similar, but it ends in red. So if you remember, we would use the liveness probe to tell if our recipient is up and running, and the readiness probe to tell if any dependencies of the REST API are responding correctly are ready and basically, REST API is ready to serve requests. So with that we have properly declared a deployment for our REST API. But it is not enough. So this will go ahead and create the bots pull this pulls the containers, and environment variables and all that. But still, there's no way to reach for anybody to reach into this container from the outside. And to enable that, we need to bring in another component that's called service. So that service, we could either create in another java file, or we can use security right here, which is what I'm going to do. And the way that you separate these two different resources in the Java file is by using three dashes. And then you can go ahead and start declaring your resource. So I'll do some IntelliSense. Again here, so I'll just type service. And that brings up the query service IntelliSense. Here, so I'll click on it. And that will scaffold a little bit of pieces in there that we can take advantage of. So the service is the is the type of resource that you use to be able to address resource within Kubernetes, either internally or externally, which is what we need at this point, the service we need to give, we also need to give it a name, just like we did with deployment. So we'll name it the catalog service. And then one piece that's not listed here that, but that is important for us is the type, there's a few types of services. But in our case, we want to use a tight named load balancer. Load Balancer is the one that allows queries to request natural IP, or a natural or not, I guess, not an IP, in this case, because it's localhost. But it requests a way for two to open kind of a window to the to the outside, so that people can actually reach out to our REST API from the outside. So we'll see how that that name resolves when we run this, but you know, various responsibilities. Otherwise, we cannot reach the service from the outside. For selector, we have to specify the port. Well, the label for the the ports that we have declared before, if you remember these ports, here, we declared the template, we said that the labels for all the ports that are going to be managed by the deployment is going to be Catholic. So that same label is the one that we have to use, what we declare the service, or the color selector with, we're going to say, well, we're going to this service is going to be able to target any of the ports that have the app label with the value catalog. So that's how you connect the service with the bots. And then you also have to specify, okay, so which is going to be the port, that that from the outside, people can reach into our API from the outside, and that has to be mapped into a port in the in the container. So that port in this case is going to be we're going to be using your ad just because it's the default port for HTTP. So that will allow our clients to not even have this Wi Fi port, it will just be able to use call directly into the API. So they will go into port 80. And the target port has to be the port that we have specified for the container to remember, over here, imports, we declare container port 80. So container port 80 is the target pool that we want to use here. So it's really mapping 80, to 80. But it doesn't have to be like that, we could, we could have said, let's say 8080 maps to 80, that will be totally fine, just like we did with the container. But it is more usual to use a port 80. So now we should be ready to start deploying these well, to deploy these bodies resources, both deployment and the service. So how do you deploy this into Kubernetes. So we have to go back to our cube control tool to be able to do that. So I'll open up my terminal again, Ctrl J. And I'll switch to my release directory. The command to apply this deployment is called this this java file is cube control, apply dash F, and then the name of the file, hit Enter. And you should get a couple of messages stating that they got up the deployment has been created, and the service has been created. Now you want to see a which is a deployment or what's the state of a deployment that should be created. What you can do is to say cube control, get deployments and that will give you a list of all the created deployments this case is saying we have a one deployment named Gatling deployment and currently it is saying that zero of one of the bots is it is ready to go. So it means that it is not really ready yet. So, let's dive in a little bit more and get details about the actual bots got created. So what we can do is say, cube CTL get bought. And so as you can see all the with one pod that we have declared here, the name is starts with enable deployment. And then it gets a name for what we call the replica set, which we've not, we will not talk about in this video. And then finally, some identify for the actual pod. And then indeed, the port is not ready. So this is saying zero of one ports are ready to be used, right to be reached by the outside. But still, he says running. So this means what this really means is that our our liveness probe, that you remember, we have a liveness probe is is reporting a healthy status, but our readiness board is not reporting healthy status. So to find out a little bit more of what's going on here, and I'll expand this a little bit more. Let's actually get some logs from that catalog board. So to see cube control logs. And then the name of the bot hit Enter. And then we're seeing something interesting here. Let's let me scroll up a little bit. Yes. So here, as you can see, the our MongoDB readiness check is failing with status on healthy dubray him was cancelled. And as you can expect this is well, this is not expected because we have not really deployed any database yet. But this is great. This This confirms that our readiness health check, both have checks are actually working properly. And we just need to make sure that we fix this problem with the database, we bring it up. And then we should be able to have an REST API up and running. Let's close the terminal. And let's actually declare what we need to declare for our database. So I'll go back to migrate this directory. And I'll say new file. And this file is going to be called Mongo DB. Because everything we're going to declare here is just for the deployment of that MongoDB database. Now, the type of resource that we're going to create for MongoDB is actually called a stateful set. And see if we don't have a way to generate the skeleton for a stateful set. And yet, we're going to use the deployment template for this. So let's use to deployment select Windows deployment. And then what I'm going to do is just switch from deployment to stateful set. So let's say Phil said he has similarities with the deployment. But it is actually meant for stateful applications. So a stateful set provides guarantees about the ordering and uniqueness, uniqueness of pots. So when you see the pots that are created by a stateful set, they will not have random, random names, they will likely have some very specific order names. So for instance, in the case of this one, it may be called MongoDB, one MongoDB, two MongoDB, three. And more than that, if one of these ports dies, let's say MongoDB, one dies. And when it comes back, he will come back as MongoDB one once again. And this is very important in the case of MongoDB. Because we will attach a persistent volume to it, which will have the database data files. And we want to make sure that those files don't just get lost as as the port is reconstructed in the case that it needs to be given for any reason, right? So we want to keep it around. So the right type of resource to use for for a persistent service, like MongoDB would be a stateful set. So just like we did with deployment, one of the first things to do here is to assign a name to a stateful set. In this case, we will name it MongoDB stable set. And then one important thing that's not being generated here is what we call the service name. And the service name is used to give a some identity both to the stateful set and to the bots there are going to be a managed by it, which is not actually needed for deployments. But for a stateful set. It's it's a requirement. The name that we're going to give here is MongoDB. service. We see how the service is died later on to the MongoDB service and back to the catalog later on. Then also just like we did with deployment, we need to define which are the labels that the status is going to be using at to select the ports that is going to be managing. So in this case, let's say that our bots are going to have the Mongo DB later the MongoDB value in its app label. And we're going to do that Then we have to make sure that in the pod template down here in labels app, we have to be using the same value. So all our parts are going to have an app label with a value of MongoDB. And then the stateful set is being configured to manage all those pods with the MongoDB value in the app label. Now we keep going down into the container section inside the spec. And then let's just give the name of the container listen this name it again MongoDB. And then for the image will be we'll use the same image that we've been using so far, is just Mongo, latest version of Mongo, then we keep going down into the resources section. And we will leave these resources, they should work just fine for us. But it's up to you to modify how much memory and CPU you expect to be using for your MongoDB server and the MongoDB database. Moving on, we have to declare the the port where the MongoDB container is listening on. And by now we know that this port is 27, zero 17. Right. So that's the port that we have to use to, to connect to that MongoDB service inside the container. And once again, like we did with, with gadelha yamo, we have to define a couple of environment variables to be able to talk to that well to be able to start up our MongoDB container. And those are the username and the password for the for the user configured for for MongoDB. So let's declare and sorry, let's see clear and M section. And here, let's start declaring. So the name of this environment variable is Mongo in it, db. root user name. and the value that we're going to assign to it is the one that we're using. So far more go admin. And then for the for the password, we're going to be using really the same secret that we're using gatok. So I'm switching to catalog here. And I'll just copy our password section into MongoDB. base here and fix it a datian. And then as you see we're reading from the same location, but the name of the environment variable is just a little bit different, is going to be Mongo in it, db. root, password, right, so that's a, that's a username and password environment variables that the MongoDB container is expecting. The next thing that we need to define in the case of the MongoDB container, is what we call the persistent volume, right. So we need to declare some storage way too, ask coordinators for some storage space to place the data files for our database. Otherwise, I mean, yes, a database will exist within the MongoDB container. But when the container and the port, the containers container is killed for any reason, the data will just disappear, right? So we don't want that to happen. So to do that, we create what we call a persistent volume, and greatest persistent volume, we're going to use what we call as a volume claim template. So let's do that. And they make sure I pick the right place for this. I should be here. So let's say volume claim templates. And really the balloon claim templates is a way to declare or to ask Kubernetes for some space, some storage space in the node, where the where the pod is going to be executed, right, so I need some space. And we have to declare a some details about that space that we're going to reclaim. So first, we're going to set up some metadata. And we pretty much just need the name here. So what's the name that we're going to give to these to this volume, that's going to be data. And then we have to specify the spec specifications for the volume that we're going to ask for. So that goes into the spec section. And then here, we have to specify an access mode access mode. So access mode declares, which way is this persistent volume going to be going to be mounted into the note, and actually, this should go into a previous line to do it like this. And, for our case, the mode of READ WRITE, once, once it should be good enough, and really this one here, it means that the volume that's going to be created that's going to be mounted is going to be mounted as read write, and for a single note, so meaning that just one note can read and write to these volume at a time. If you wanted to. You wanted to have more than one node we able to write to this volume, you will have to use a different kind of access mode. And then finally, we have to define the resources that we need here. So in this case, we'll declare resources and Then requests. And finally, storage. And here's where we declare how much space we want for this volume. And for our case, let's go for one, I think the term will be gigabyte, similar to one gigabyte, that's going to be as much as storage, we're going to reclaim for this volume, say this. So with this, we have reclaimed space in the note, right? For this form for MongoDB. However, we still need to tell our container that such a space exists. And we have to map that space in the in the host machine to space into the container. And to do that, we're going to declare a volume mount, the balloon mount needs to be declared inside the container spec. And so I'll just type here, balloon mounts. And here, we're going to specify a name for it. And this name will have to match exactly the name that we have specified for the in the balloon claim template, right. So we said it's going to be data. So data is the name that we should use here. And then the mount pad is the part where traditionally MongoDB is stored its data files right inside the container. So that that space is going to be slash data slash dB. So what this really means is that when MongoDB MongoDB container writes into its data DB directory for the data files for the database, those files are going to end up into de a persistent volume that has been declared on the site here, right, so the data gets read in outside of the container and into the persistent storage in somewhere in the host. So this way, if the container goes down is the port goes down for any reason, the data is not is not lost, and they will come back as the port comes about with the same identity in the stateful set. The next thing that we need to do, just like we did with the catalog yamo is declare a service write a service that allows us to address or to get to the MongoDB service. And so I'll just please, and then I'll type service for cleaning service, so generates just like we did before. And just like before, we have to specify some name for the service, let's call it MongoDB. service. And then one important missing piece here is this thing called the cluster IP. So cluster IP is what you would use to specify the IP address for your service, right. And so by default, any service will get local IP that that can be used to talk to other services within the cluster. But in our case, we want to create what we call a headless service. So we don't want to assign an IP to the service. Because in a stateful set, we want to address each of the nodes for each of the pots individually. So in this case, we're going to say none, so we don't want an IP in this case. So it turns it into a headless service. Now for the selector, once again, we have to specify how is this service going to be mapped into the ports that exist for for MongoDB. Right, so for that, we have to go back, once again into the bottom plate, the bottom plate metadata labels app, the label that we're looking for is AP, and the value is MongoDB. So we go back, copy that into this lector MongoDB. So anytime a request comes into this service, it will find the nodes that sorry, the ports that have been tagged with the MongoDB a value in the app label. And then that's what, that's how it's going to find them. Finally, we need to specify the ports. And so just like we did with the container, we're just going to do a simple mapping of 27 zero 17. So any request that comes into 27, zero 17 should go should be redirected to the port where the container is listening on. And that that port is again, as you can see here, 27 zero 17. I'll just copy that over here. Now that we have done this, it should be ready to to get to get started with this MongoDB container. So I'm going to open up my my terminal again, Ctrl J opens terminal. I'll scroll down this a little bit. And then I'm going to switch to the Kubernetes directory. And here I'll just do cube control, apply dash F and then our demo file MongoDB demo, and I'll hit enter. So both the stateful set and this service have been graded. And so at this point, let's see, how does the stateful set look like right, so let's do cube control. Get Data Sets. And they'll give us the one stateful set that has been created MongoDB stateful set, which seems to be ready, it's healthy, it's in good state, and it's ready to be used. Now that we did that, let's take a look at all the ports that we have right now. So once again, cube control get hot. And as you can see, now we have our catalog board, it is actually ready. So it's no longer reporting 01 is reporting one out of one. And that is because the ad because the the ready the readiness probe that was trying to reach into the, into our MongoDB database, it is now able to actually do it. And that's because we now do have the MongoDB service available. If you remember, when we were in catalog, Jamel, we declared that the MongoDB settings horse was going to be MongoDB service, it was not available yet. But now that we have declared it and we have deployed it, we do have the MongoDB service that I can reach out to. And then that allows our health check to pass so we can connect to the database successfully. I just like we have that board, we also have the port, the MongoDB stateful, set zero. So as you can see, it is not a random random ID as a as in the case of deployment is more of a very specific numbered and ordered index for these stateful sets. Right. So if it dies, it needs to come back with that same number. Let's now see if our REST API is working properly. Now that is running within coordinators. So let's open up postman. And last time that we did a get against our REST API, we did it over Port 8080. So because that's the port that we exposed when run it is as part of Docker. But now we have switched to Port 80. And we can either query the API like this, or we can just remove ad because it's a default HTTP port. So this should be good enough to do a get against the API. So let's see what we get. And sure enough, we don't get any results. Because remember, this is a brand new database that's now hosted inside Kubernetes. So this effectively don't have any data. But we can go ahead and create something in there. And so I'm switching to the post up here. And I'm going to also change these to just be HTTP localhost items. And then for body, let's come up with something quickly. Let's say we're going to create a potion again, price 12. And then hit send. And sure enough, the potion has been created, we can create a just one more thing, let's say an antidote. With Price, let's say 17, hit send, and has been graded to go back to the get it sent. We are getting our two items now. So the REST API is working properly. But everything is now running within grenades. And so we talked about this capability of grenades to self heal, right. So it should be able to always enforce that desired state, regardless of what happens to the bots. So let's see how how that exactly works. So I'm back in VS code now. And what I'm going to do is just to get a little bit more space here to be able to visualize things better. So I'm going to move this left side all the way to the left. And then what I'll do is spin up another terminal with the split terminal burden. So that now we can have two terminals side by side. And I'll move things around a little bit like this, perhaps right there. And so what I'll do is on the left side, I'm going to be watching for the bots with cube control, get pods, dash W. So that lets me see any changes that happen across the the current existing bots in there. And on the right side, I'm going to simulate the killing of one of these bots. So let's say that I mean, let's imagine that the board had some bug, and that causes the bot to crash. Right that then what happens. So let's do cube control, delete board. And so let's try our catalog board or only catalog board. And I'll go ahead and delete it. So I'll hit Enter, and see on the left side, how right away. As soon as it starts terminating that port, it immediately starts spinning up a brand new container, right. So that's the capability of coordinators to always detect this discrepancy between the desired state and the actual state. And as soon as you detect the situation, it needs to do whatever it needs to be done to bring back things to consistency, right. So in this case, the Newport is up and running, and then I'll just do Ctrl C. And I'll do get pods again without the W and you can see that now. We have, again, our two bots. But now we have a catalog but with a different identity, right? You can see it's not the same identity as before. And that's because deployment type deployments, great bots are ephemeral, ephemeral in nature, right? So they are just stateless. Now, that's not the same case. As for our stateful sets, as we said, Our stateful sets should be persisting across the lifetime of a pod, right? So if we just have these MongoDB stateful, sets zero here, what happens if we deleted right? More than that what happens with the data that is being held by this MongoDB bot, because we already have data in there. So would it survive for the data to still be there, with the port come back, so let's try it out. So I'll do a wash again for the bots. And I'll copy the name of our stateful set. And so I'll do cube CTL, cube control, delete bot, and I'll do MongoDB stateful. Set, let's see what happens. And see on the left side, the pod is indeed getting terminated. But right away, Grenada is detects that it needs to bring it back. And it needs to bring it back with the same identity MongoDB safe was at zero, because this is a stateful set, right. And we don't want to lose the data that's being held by the sport. And in fact, if I just control CDs, and guys, I'll do get pods, we have our two pods. And now we should be able to verify that the data is not gone. So it should still be there. So if I go back to postman, and I query for the data, once again, we can see that the data is still there. So it has not gone anywhere. So so that means that indeed, our persistent volume got created, and the data is being stored outside of the container and into the host. And that's enabled by our stateful set. So I'll go back to VS code now. And we also talked about this a capability of grenades to easily scale the ports and the containers inside them, without really much, much stronger, right. So if we are somewhere our network we need, we have much more requests in our website, we do have not just one port for catalog, but we need to have three, well, what would we do? And how can Kubernetes help us with that. So once again, let's monitor what's happening on the left side, get pods. And then what I'm going to do here is just ask Kubernetes to scale the deployment for discovery deployment, where you can do is cube control, scale, deployments, and then it will be catalog deployment. And then you have to say how much right right now we have one. Now we want to have three. So hit enter. I noticed on the left side that immediately starts provisioning a bunch of new bots to enforce this new decided state, right, and this happens blazing fast, right. So if I just do Ctrl C, now on the left side and get bots, again, you can see that we already have three bots, and we only had one just seconds ago. So here you can tell, like the power of the combination of Docker containers, and Kubernetes, right, how we can bring in a much more instances of our containers of our of our REST API. In this case, without really much trouble just running one line, we now have three copies of the container running. And now, the whole point of having these data replicas of the pots is so that we can do some good load balancing between them, right. So when a request comes, it should land in one or another of these bots. And how can we verify that? Well, unfortunately, we don't have good means to do that right now. But I think we can easily introduce a little bit of logging into the bots so that we can easily tell which bot the request, the request is landing. And so to do that, what I'm going to do first is just I'll just close the terminals for now. And then I'll go to our Explorer, or go to our items controller. And here, I'm just going to add a little bit of logging. To add logging where we can do is bring in the standard a logger interface. So I'll do only a logger for items controller. Let's call it logger. So I logger is, is a standard object available in dotnet five, so pretty much in any application dotnet five. And so what you can do here, you just do dependency injection, as you do with any other service built in service of dotnet five. And I'll come up to the logger instance right here. Now that we have that, what we can do is just pick one of our API's and do some logging. So I'll go for the easiest one, which is going to be our Get diverse API. So in this case, I'll just open up here, one line. And I'm just going to log a little message that says how many items we found, right. So to do that, what I'll do is just logger dot log information. And then let's do a little bit of string interpolation here. First year I'm going to put here is the current current time. And I'll do that via the date time class, I'll choose the UTC time to string and then we'll show adjust the time in the format of hours, minutes and seconds. Okay, so type format there. And then I'll just do corner just say retrieved. Items that count items. Okay, so just for us to verify that things are landing in different parts. So I'll save these. And then they will not change. What we have to do now is to create a new version of our Docker image. So I'll open up our terminal now. And I'll delete one of these, so that we only have one. And here I'll do what we did in the last video. So I'll just run our Docker build command. And I'll be publishing this into Docker Hub. So I'll be I'll keep using the same format as before, using the username first, and then the name of the image. And then the one thing that I'm going to pop here is the deck because this is a new a new version of the image. So we should be bumping it, let's say to be two, this is necessary, so that coronaries can later tell that this is a new image, or that it needs to pull it down from Docker Hub, otherwise, he will not be able to do so then I'll say dot O, hit Enter. And then I'll just miss I'll just miss one parameter here, which is the dash D for the tag, you enter again, this is going to build the image, it's going to reuse some of the cache layers and then it's going to be just a piece that is needed. Okay, so the image is built. Now I'm going to do me to login into Docker Hub Docker login. And now I should be able to just push the image shorter. So I'll do Docker push, would you see catalog, B to enter. And then again, some of the layers are going to already exist in Docker Hub. So only the layer that's missing, which is my little change of one line change here is the one that is included in this image and this one that needs to be pushed into Docker Hub. Okay, so with the image in Docker Hub, we should be able to tell Kubernetes that we want to start using it. So for that, I'll go back to catalog Jamel and I'll say hey, cornice, I don't want to keep using a demonstration one, I want to use version two. Save that. And then back in the terminal, I'll switch to our coordinates folder. And here, I'll just apply this file was once again. So cube control, apply dash F, and then we'll do capital gamma. Okay, and so life is if we do cube control, get pods, watch, see what's happening. So as you can see, the old the old container dope bots are getting destroyed. And new bots are getting immediately installed stand up for the new image, the new misperception that we need to be using. So this should take us a few seconds. And so I'll Ctrl C now. And I'll see the actual status of the pods. Let's see what we got. So yeah, so we have three new copies of our a catalog REST API, the replicas of the pod. And so now we should be able to tell if we're load balancing across them. So to do that we're going to do is again, I'll just make some more space here. I'll expand this terminal has even more. And I'll split the terminal now in three. So that we can add Delta locks of the of the three pots. So first here, now go back one directory. And as they could control get pots, so we get the names of all the pots, and then I'll do one by one. I'm going to do cube control logs for these one and then I'll do dash f so that we can tell the logs and then I'll do the same Here, which is our second part, let's take a look is going to be this one here, dash F. And then the third one is these guy here for our third terminal to control logs, dash F. Okay, so now we're tailing the three parts. And I'm going to go back to postman and perhaps we can accommodate this into here just on top of the other one to see what's going on. Yep. And, yeah, so one more thing, actually that we have to change is postman is our heater. So let me maximize this for a moment. Because the default behavior of postman is that it's going to send this a connection heater with a value of pickle keepalive. And what that's going to do is actually set up a persistent TCP connection between postman and our bot. And that will actually prevent our little exercise from allowing different subsequent connections to go into different bots. So just for testing purposes, and to see how things work, I'm going to disable that, that heater here and see how these things work. And, yeah, so with that, minimize these in this way. And let's send one request and see where it lands. You see, it landed in the first part on the left side, between two items at 704 52. Let's send again. And now we landed in in our second part, let's send the game loops. Again, in the second part, and then at this point is going to be a little bit random. I mean, the algorithm that's supposed to be using is round robin. But really, things can land in any pot. That is point. So there you go, load balancing in Kubernetes, fairly straightforward, without you having to do really much work on it. And if you scaled into 1000s of bots, then all of them will be serving your requests appropriately. In this episode of The dotnet five REST API tutorial, we talked about unit testing, test driven development, and how to implement them to raise the quality of our REST API. Today, you will learn what is unit testing and why it is so important. What is test driven development, also known as DDD, and why you may want to consider it in your project, how to retest REST API controller via the x unit testing framework, how to mock dependencies via the mock framework, how to write better assertions via the fluent assertions library, and how to implement TDD in practice. So what is unit testing? This is a topic that I'm very passionate about. And to understand it, let me introduce a quick analogy. Imagine that you're a member of the team in charge of testing the SpaceX rocket for the first time, the engineers have used dozens, maybe hundreds of different parts and systems, some not even produced by SpaceX. To assemble this awesome vehicle. Everybody put their top game to build a rocket. And now we would like to see if everything worked as expected. launch day is here. And then yeah, that didn't go as expected, there has to be you can't just assemble a bunch of parts and test them all together the very first time the rocket is launched. Fortunately, this is not how they usually test a rocket before launching. Without getting too technical about rockets, because I'm definitely not an expert in the area. I just wanted to show here a simplified diagram of the parts of a rocket that I got from the NASA website. All of the different components and systems like the payload system, or the oxidizer are also individual units of this entire vehicle that all need to operate properly before the rocket can lift off from it. And the engineers don't just build this unit and send them to the assembly team to put them on a rocket and after everything is put together, figure out if all the parts work or not. Each part of the rocket is tested in isolation, likely several times, where before being sent to the final assembly into rocket. This gives certainty to the teams behind each part that as long as it is used according to specifications, that unit will work as expected. And the same goes for the team assembling the entire thing. They know that they can connect all the parts according to specification, and the rocket should lie. This saves time and money for everyone. Unlikely saves a few lives along the way. So in terms of software engineering, we can define the testing as a way to test every piece of code in isolation without external dependencies. Now coming back to our catalog, REST API. Even with a simpler screen at this point, we do have a few components that talk to each other, like the itis controller, or I didn't have auditory class, the Mongo client instance. And finally, the MongoDB database. Each of these components are made of a bunch of methods that represent the behavior that we can get out of them. For instance, the ages controller has has functions like get item, grade item, update item, delete item, and we will certainly keep adding more in the future. These are the different granular units that must individually work correctly, to ensure that the whole service provides the expected functionality. Therefore, for each of them, really to write a series of unit tests that really exercise every aspect and every corner or each of these methods to give us enough confidence on their quality way before trying out the whole service from postman or from any other client. Beyond this, unit testing has a bunch of benefits that you definitely don't want to miss. With a unit test, you can quickly verify your code without having to worry about dependencies. For instance, you can make sure that your class can retrieve items from the database without having to stand up or talk to a database server at all. And such a test can give you results in milliseconds as opposed to seconds or minutes, you can make changes without worrying about introducing regressions. After you have a unit test in place. You can refactor your code as much as needed without concerns of breaking the service. Because you know that the unit test will provide you with that safety net unit this will catch box at the point where it is easier and cheaper to fix them. Which is before merging your code to the code base on way before getting a deploy to production. fixing something that is already impacting impacting customers in prod can have an enormous cost, both in human hours and of course in the amount of money lost by anybody that use it or service. And unit test. If don't Well, can be the best augmentation of your REST API, since every use case should eventually turn into a unit test. And those tests can't lie. They must represent the way that the system works. Now that we know what unit tests are, let's also talk about test driven development or TDD. So what is TDD? Simply put, TDD is a software development approach, where you write a test before you write just enough production code to make the failing test pass. This translates into a cycle made of three phases, a red phase where you write a test that represents your software requirement. This test fails because you have not implemented any production code yet. In fact, the test doesn't even compile at this point. A green phase where you write just enough production code to make the test pass. You don't need to implement anything beyond what's needed to pass a test. And inelegant or only code is allowed at this point. Finally, if needed, you refactor the code you just wrote while you keep running the test to make sure that they stay green. It is at this point where you eventually arrive to code optimize it for readability and maintainability. You keep repeating this cycle for any new piece of functionality. This is a basic cycle of DDD. Why would you want to embrace DDD? Well, there are a lot of benefits of embracing this practice. But there are three aspects or like most we did it, you start by focusing on the requirement, not on the implementation. This gives you a lot of freedom in terms of trying to properly address the requirements, because you're not constrained by an already implemented piece of code. When you implement the code, first, you end up writing tests that verify only as much of the implemented code as you have time or patience for because you already invested a lot of time and effort in that code. You can increase it this coverage, because by definition, you would have not written any more production code other than needed to pass a test. Again, when you don't do things the DDD way, you might end up with multiple corner cases that might feel that you might forget or might not have time to test properly reducing the test coverage. Finally, clean design is enforced from the start. As you write a test, you will naturally start designing the pieces of production code in such a way that leads to a passing test. The classes and methods emerge from the test, and you'll naturally avoid the pitfalls of writing code to Cobbold to be tested. There are three main unit testing framework in the dotnet ecosystem these days, and unit, Ms test, and x unit. They all fulfill the same purpose of allowing you to write and run your unit tests in an automated way. However, for any new project, I strongly recommend you choose x unit. This framework comes from one of the original authors of the popular end unit framework. But it was really meant to be more closely in line with the dotnet platform and to help write clearer tests. It is also more intuitive than ms test which requires more attributes in test classes. Some of them not straightforward to use properly, especially for developers new to the platform. Let's see now how to implement unit testing and TDD in practice. It's time to add a new test project for our unit tests. But before we can do that, I think we should restructure things a bit to give our REST API a more specific directory that will live side by side next to our upcoming test project. So I'll start by going to our explorer view on the left side, and I'll just look for an empty section over here. And right click, and I'll say New Folder, the new folder is going to be catalog that API. And now let's move most of the directories and files over there except for the VS code being catalog, API, and OBJ. So let's grab everything else into catalog API move. And now that has all the files for the catalog REST API. Now, let's close this. And then let's delete this directory, we don't need this bin directory or this OBJ directory, those are gone. Now just to match the folder name, let's rename the project name into catalog that API. And then we'll have to make a bunch of renames in a bunch of files, just to match this new project, right file name. So I'll copy this name here, close this, and then I'll go to search and replace. And we're going to replace catalog. That's us broke into catalog that API CS broke. So let's just replace all, they will do the same thing with the DLL. So gotta look that DLL, siapa DLL, it's gonna be renamed into candidate API, that DLL is replaced these all the files. Now let's look at the namespace. So today, we have this namespace catalog. And that should turn into base base catalog that API. And then for every everywhere classes that are using that namespace, let's make sure they use the new namespace. So using catalog should turn into using catalog that API to that replacement. Now let's look at our to VS code. That's a JSON file, where we have these a workplace folder slash catalog API stand to change that, to replace these with slash gallery, that API slash how to using this file placeholder, all the entries. It's all done. And now let's go to lunch that Jason and do a very similar replacement, so workplace folder into catalog that API, or three folders slash catalog API, replace all this file. And I think that's what we have to do. So I'll just close these two. And then I'll do a Ctrl, Shift B to make sure everything is building properly. Yeah, looks like it is, or close these around this one here, you'll see that nougat packages are restored, but everything looks fine, or close terminal. Now among the things that we modified, and they'll collapse, this one is the Docker file. So the Docker file is now pointing to a catalog API that says broke. So I'll just, I just want to make sure that this is still building properly. So I'll rebuild our Docker image now. So open my terminal. Let's open a brand new partial terminal. And given this new directory structure, I'll have to go into catalog API. And here I can run my Docker build command again. So just to Docker build, dash D. And there's going to be Will you see slash catalog, B three. And so B three, because we were creating a new version of this Docker image, which was B two last time, hit enter. Okay, so the new image is created, I'll do Docker images. So it is right there, the image was created. So everything looks just fine. So this is great. I'll close terminal and close this file. So now we can actually create our display. So I will collect this for a moment. So we want to create a new display you could use at the same level. So go back to terminal, actually, and we're going to go up one directory. And to create this project, you do it very similarly to how you do for the creation of the web API. So you choose to just use a dotnet CLA. So dotnet new, and like I said before, they preferred this framework for this project is x unit. So I will go for x unit. Now let's name this project. catalog that unit tests hit Enter. And our unit display has been great, because this one over here it has a project file and an initial class, display class. Are there. Now one interesting thing that we have now here is that we need to build a not one, but two projects, right? And so anytime we want to make sure that everything is really properly, however, our physical environment has not been configured for that yet. So if you look at the JSON alkalosis, it is configured to be only the catalog API CS Pro. So how can we make it so that anytime we build it builds both projects. So there's a handy way to do this, that I'll show you. And what I'll do is I'll create a new file at the root here, just add a route that's going to be named, we'll call it yours, we'll get proud. Okay, and then I'll collapse this for a moment. And this file is going to allow us to build all the projects in one shot. So how do you how do you do? So let's declare the following. So you will do Raju SDK. And here we're going to be using the build trails traversal SDK. So to do that, you just type here, Microsoft dot build that traversal. And this was the file operation. So because he's actually going to pull a nougat package down into your machine. The last version that I found last time was 303. So I'll do that. Okay, let's go ahead and also, close this. And inside this section, you have to define an item group. So I can group, close that group. And here, you have to reference all the project files that you want to compile. So for that, you want to type like reference, include equals, and then we'll just do this, this expression. So everything, so star, that star, so any files that end in Brock, are going to be compiled by this file. Okay, so with this file, ready, let's go back to Explorer. let's actually go ahead and into task Jason. And let's ask it to no longer just build catalog API CS, but instead is going to build build that block. All right. So with that done, I'll do Ctrl Shift v. Yep. And now it's close to East. Let's close that. You can see that boat. Let me just do this for a moment. catalog that API DLL and Catherine, etc, they'll have been built by these one comment. So notice that you don't need a Visual Studio solution for these at all. This is this is my preferred way of building like all the products in solution in a solution. So build Prague use include all the break files, and that will do the trick. Right, so close these two now. And then our test break here, we'll need Of course, a reference to our API, because we're going to be testing the API controller. So let's make sure we have that reference. So open terminal again, I'll switch to my PowerShell terminal. And then let's see, I'll go into catalog that API service catalog does unit tests. And then I'll do dotnet, add reference. And then we're going to go into catalog that API. catalog API. That's Yes, bro. Right. So that adds the reference, we look at unit tests, close these, it will have that reference right here. Okay, so now the break the test probably can't use any of the files, or reference any of the files in their API project was that and then we're going to need a couple of additional nougat packages in this test project. Let's actually open these again. And these are going to be a first we're going to need the nougat package for a extension plugin abstraction. So let's do that. dotnet add Bakhash Microsoft extensions that logging abstractions. And this is because we are going to be using or trying to test our controller class, which, if you look at it quickly, the controller class does receive a logger in constructor over here. So we're going to be needing to use these a logger class. And for that, we need that to get package that we just added. The other package is the net package is called Mach. Mo Q. And this is this little framework that can help you actually mock your your classes, the classes you're using in your controller. So So that you can a test only the pieces that you care about in controller, but you don't have to worry about how to create or how or how the dependent or external dependencies of that class a work. And we're going to go into those details in a moment. But yeah, those are the two nougat package that we need for now. So I'll close terminal again. And then let's start focusing on our desk class, this case, you need this one. Let's rename this class into a more appropriate name. So rename these into items, controller tests, right, so the convention that we're following here is that if the controller is named itis controller, that's a class name, we're going to be using the class name with the suffix of tests for this class is controller tests. That's the one that we have here. And that's the one that we're going to use for the, for the class over here, titled The third test. I'm going to collapse this Navigation Pane now I'll do a Ctrl, Shift V, make sure everything is building properly. And then, if you happen to be getting any of these red squiggles here, we should not be there. But if it happens, let me just close these, what you can do is use to Ctrl Shift P, and do only sharp is dark, only sharp, or you can type that there on the sharp, we start on the sharp, and that should take care of that. Now notice this fact attribute that was added to our audio narrated this one method here. So fact is the attribute that you have to use to declare that one of the methods in this class is actually this method. So that's the only way for the test runner to recognize that it has to execute these tests. So use Don't forget to add fact to each of your test methods. There are other ways to declare or to decorate your metals assessments. But for this tutorial, we'll stick with fact. Now let's go ahead and start writing our first unit test. But before that, let's look again, other items controller class. And let's see what should be unit tested. We will write unit test for all of our, all of our methods are here. But let's start with get it basic, just because there's a couple of simple and nice cases that we can go across these these methods. In fact, after receiving an ad, as you remember, we will reboot and we will try to find the item in the repository. And if we can, if we cannot find it, if it is no, we will return not found. Otherwise, we will go ahead and convert the item into a detail. So let's write a couple of unit tests for to verify this method. So going back to our test class, one thing that I'd like to encourage you is to use is to use a good naming convention for the unit test. This is very important because it helps it really helps to identify what is this they're supposed to do what what is it really verifying, without having to go into the all the details about the unit test? So one one good naming convention that I like is the following. You want to use three parts here, that's going to be unit of work. State under test, and expected behavior. Right. So first part you into the work. So what is that you're testing? What is the function that is going to be tested by this unit test? That's unit work, then state under test. So under which conditions? Are you testing these these test methods, right? And then finally, the expected behavior. And so what do we expect from this from this unit, as we execute these tests after we execute the action part of these tests. So now translating that into our guided async method, let me just copy the name here. The unit of work is in fact, the name of this method. So gate item async. And the first case that I'm going to test is what happens when we cannot find the item. So the item, the item is full, right this section here. So in that for that case, I'm going to say with an existing item, so the item does not exist, what will be the expected behavior, then it's returned returns not found. Okay, so that should be a good name for arguing this refers to a test. Now, within the body of the reading test, there's also some other another good convention that encourages to encourage us to write the test in this way. So there's going to be three sections here. The first one is called a range. Second one is called tact. And the last one is called cert. These also a be named as AAA. Arrange, act assert. And the idea is that you're going to first have an array section where you're going to be much set up everything to be ready to execute the test. So just before securing the test, so this includes any sorts of marks. levels and inputs that you're going to need to be able to figure into this. Then we go to the x section where we actually execute the test, we perform the one action that we are testing here. And finally, the assert section where we verify whatever needs to be verified about the execution of of the of the action of the unit. Okay, so how does that translate into a unit test? So we want to test is controller. And for that, we'll have to of course, create an instance of item controller. However, remember that we need two parameters here. So we need to have a positivity and we need a lager. Now, one thing to remember here is that for the purpose of testing this unit, this get imazing method, we don't really care about the internals of how the repository for instance, accusatory behaves, so we don't care what happens. Normally, when you call get it basic, as you know, that we'll go ahead and talk to the database, retrieve the item and all those things. But we don't want to test that we don't want to test a repository, we just want to test the get itemizing method, this is the one unit that we want to test. So you have to make sure that you find a way to exclude those dependencies and the behavior of the dependencies from these tests, and just focus on testing what was right here. So to do that, of course, we cannot use a real a real Idaho story or a real logger. And here's what we have to introduce a what we call a, what we call a stops. And so I stopped is going to be a kind of a fake instance, or a fake version of these items of these classes that are going to be used just for the purposes of the test. So let me show you how that how that looks like. For this case, I'm going to say so we need a depository, right. So let's I'll say depository, stop equals new mock. And then mark is a con for the from the mock library that we installed a moment ago, using mock. So this is a library that allows us to mock any of the mock or stop any of the different dependencies of our class. So locally, our controller, as we looked at the previous videos, we made it in such a way that we can do dependency injection in there. So the controller really doesn't know what kind of repository is coming in here, or the kind of logger comes here, you just look, it's just looking at interfaces, as you can see. So that gives us the flexibility to fake these both dependencies from or from the unit test. So I'll go ahead and say okay, so this is going to be a new mock of items repository. Okay, let's see, if I'm using a meeting any space. Notice that I'm naming this as a stop and not as a mock. And that's a slight difference that I like to make, because when you do stops, you will not verify anything on the on the on this object itself. When you do mocks, you will in the assert section, you would go ahead and actually verify something that happened to the mock accuracy test. So it's a slight difference, but it is good to it's good to to do the proper naming here so that you understand what is the purpose of the variable that you're using. Okay, so now the expectation is that when we call this call to controller, when we're going back to our method, when we call the get imazing method, the idea is that it will return a no. So when returns No, we should return the controller should return not found. So we need to set up that isn't it? So how do we set up this method in the mock so that it returns No. Going back here, what you can do is this repository, stop that setup. And then you're going to say, let's say repo, repo that gate item async. And then comes the parameter. Now, at this point, it really doesn't matter what's what's the item that we are going to be passing in here. It's irrelevant, because what we want to do it revelate is what happens with the return value. So because of that, what you can do is just say it is a which is a function provided by Mark also any COVID This means whichever value comes in, it doesn't matter. So Mark will take care of providing some value there. And then that will do it should return a value of No, that's what we want. That's the expected behavior. And then, but just so that marketers doesn't get confused, we have to cast this into the item entity. And let me add Robert namespace right there. Okay, so this is setting up the scenario for artists. So we're saying again, we're saying when whenever the controller invokes get good at basic with any any code, which mark is going to provide, you have to return a null value. That's what we need for this use case. And then similarly, we'll do something With the logger, so we'll say logger stop equals new mark. I'll say, Hi logger, or items. I just control. Okay, let's see if we're missing something again. Yep. See dad remains in the construction space. Okay, so now we have two stops ready to go. And now we need to create the actual controller. So now we can say, controller equals new items controller. And then we passed it, this docks. So if I posit Ori, stuff, what we need to get actually the object property of these because that's the real object that's going to be passing out just a mock the mock object, and then logger stop that object. So that covers the arrange phase of this unit test for the act phase. Here's where we execute the action. And this is normally just one line where you execute what you're going to be testing. So I'll just say, sold, equals await. And yeah, now that I'm using a Wait, let me remember that we have to use a proper return type for these unit tests, since we're going to be calling an async function. These days, it should actually switch to be an async. task. C. So now we can do a weight controller, that good idea may sync. And then, like I said, it doesn't matter what what good we provide here. So you'll say, cool, great. And that's the action. And then finally, we'll go ahead and do the assert. So we next unit, you have a bunch of assert methods available. So let's just use assert. And then what we want to verify here is that what we got was indeed are not found, and they're not found, there's a class that is not found. So what we can say is assert that is type not found. result. And then let's see if we're missing something. Yeah, add that. And then we're going to pass here is result that result. So the result object, the result variable represents the actual result that we received. And the result property inside that result represent the actual type of result that we got, which in our case, it should be not found result. And now that we have that, we can go ahead and actually execute the test. And so there's a bunch of ways to actually run this test. In VS code. One of the ways that I use frequently is a via via using the kotlin. So as you can see, over here, there's these these set of annotations, which is, which is introduced by kotlin is to code kotlin. And you have to Will you have to do is click on Run test. And that should go ahead and run the test. Let's see what happens to running test. And that this has passed, as you can see, the one that we have passed, which is good. Now, there's another way to run the tests by using directly the dotnet. CLI. So if you go to terminal, I'll switch to here, make sure that you are in the catalog unit test directory. And here, what you can do is just do dotnet test. Yeah, so that will go ahead and run not just not just one test, but all the tests that you have across the desk like so difficult, more handy when you have you just are having more and more tests for this test project. And as you can see, it passed zero failed, one passed. Now, as the number of tests increases, you may want to have a better way to visualize the overall status of your test suite, which is cases are passing which words are failing, and so on. So So to do that, there's actually a nice Visual Studio Code extension that you can install to provide the dissertation. So let's go to our extensions hub. And let's expand this a bit. And let's look for dotnet core, this Explorer, just the first one here, I'll collapse this for a moment that will cortex explorer by June Han is the best one that I found so far for these kinds of tests. So go ahead and install it. And what you need to do about this extension is to tell it where to find the the test project. And if we go to Explorer for a moment, you'll remember that we have artists in this category test folder, gather the unit test OCS proc, so we need to provide that location to this extension. To do that, you can click this gear icon over here. Just click on that extension settings. And if any chance these settings that you see over here are not showing up for you where you can Try is just closing close to the code or closing the current folder and reopening it. And then these things should show up, it may happen the very, very first time, but after that, it should be just fine. Then what you want to do is go all the way down where it says Internet Explorer display bad. These are windows specify the path of this project. But also, do you want to go not into the into the user section, but into the work workspace section. By doing that you are going to what you're going to type in here is going to live alongside your project, as opposed to so in some place in the in your user profile. So that's good, so that you can keep everything, everything together. So here, what we want to specify is just a simple expression. So let me type that is a glob pattern where we're going to say just search all over the place inside of our catalog directory, and in all directories, and then look for tests that CS Brock, okay. And after doing that, we can close this. And if we go to these three dots here, there's now a test section. And as you can see, there's our one test is already showing up over there. And then to run it, you can either click display icon here, or you can just click the play icon on the top, and it will go ahead and run all the tests that are available there. So aspect that is green. And you can see the green bar also in on top of the test. And if there was any error that you will get some red squiggles in the location where we will test failed. So yeah, so we're using this extension across this video to to see the status of our tests as we are adding them and executing them. Okay, so now that we have that in place, and we have a test for checking for the existing item case, let's add another test for the existing items. So what happens when the item actually exists. So let me actually collapse this for a moment. So I'll do hide sidebar. And let's add a second test here. Perhaps I'll just copy the header of this test. So I'll copy that over here. Here's a new this method. And this one is going to be called get item async. Wait, existing item. returns. expected it. Okay, now, just like before, we will do the AAA. Arrange, act. And assert now for these tests is very likely that we're going to need a again, our our capacity and our logger stop boat stops. So instead of copying, then copy the instantiation over here, why not just declare a class level a couple of class level fields. And that way we can reuse them in this test and in any future test. So let me do that. So I'll go here. So I'll declare by bait read only to be marked off items repository, then I'll just copy this base here, although I could just do this. And then private with only mark of a logger, or items controller. And then it will be the loggers stuff we can use to this. And with that, we can go to our initial test case, and to simplify a little bit by not having to declare it here, because we stop there or they stop here. Okay, so going back to the new test case, for this test case, we will actually need to have an item that we can use across the desk. Because let's go back to the controller quickly, I this controller IDs. And if remember, get item async. In the case that we want to hit, which is the one that returns the DTO we need to have an item, we need to have the repository, get the return an item. And then we need to convert it to and return it. So to do that, we'll have to set up that item beforehand in our test so that it can be used it over here. So I'll go back to the test. And instead of just creating it on the fly for this test case, I think that we should have some sort of helper function that we can use not just in this case, but instead of user tests to create some random item very quickly. So I'm going to go ahead and create a private function to private identify to return an item. Let's call it create an item and this is going to say just return new And let's specify all the properties for the new item. So it will be ID, this make it good that you go in, because we don't really care what Id it uses the same way we don't really care what name these random item uses, should work with any any name. So new gu ID, to string, them for the price we want to do is probably just generate some random number so that we don't get fixed into any specific price. So for whatever, what I'll do is I'll actually create a random a variable, and let's put it at the top over here. So I'm going to declare a private read only. Random and let's name it yours around, it's going to be new. So this will be with us in a couple of places. So now we can go back here. And we can say ran that next. And then I think we said that the price should be between one and 1000. And so let's just say a maximum value of 1000. should be enough. And Rarity is going to be the time of said that UTC. Okay, so now that we have this handy method, let's go back to our test case, over here. And in terms of arrangement, what we have to do is first prepare the item that we're going to deposit or is going to return. So we're going to say bar spec, this item is create random item, then we have to do the setup for the repository. And that's going to be a little bit similar to what we did the previous test. So I'm going to copy this, this first line from the previous test there. So when we call get item async, again, with any good on what to do now is return that item. So returns async. Expected item. Okay, and then we'll go ahead and do pretty much the same thing that we did in the previous day. So copy this, these couple of lines over here. So we declared a controller with the two stops, and then we get a result, right by invoking get item async with any GUI doesn't matter. And then it is time to assert a what we got. So what would we like to assert here, so probably want to first make sure that we got the activity or not some other a result, like not found or bad requests or something like that. So I'll do a search that is type identity Oh. And let's add in a museum a space. And then we're looking at result dot value because it is the value property, the one that actually should have the deal in this case. Okay. And when we have asserted that well we can also do is, what we should do is verify that all the properties of the return to match the expected item. So for that, let's first take out that DTO. So we can do that by doing some casting here. We sold as action result of identity to that value. Okay, we can do a ser equal expected item that Id should equals do that ID. And just like that, we will need to go through every single property right, so x with the ID now expected item. That name should equal the to that name. And, and well, we'll keep going and going with the other properties. But at this point, imagine that you don't have just a couple of properties, but you have dozens of properties, right as objects can can get complex. So today is going to be become very cumbersome to just keep searching and searching and searching. And in fact, it's not a very good practice to be asserting too many things. In this case, you should try to assert or get closer, just one thing in each test, that's kind of the best practice. And so to do that, what we can do is instead of doing all this, we can switch to a very handy assertion library that's called fluent assertions. And davon will allow us to do this in a much more straightforward way. So let's bring in the terminal as well. Ctrl J and l go to PowerShell and hoovering we do so make sure that you are in the catalog that unit tests directory, and that you can do dotnet add package. fluent assertions. Okay, so with that, I'll just close terminal. So now we can do something a little bit different. So let me show you. What we can do is now we can say we sold that value And then should, then it's important if your assertions namespace be equivalent to the expected item. Okay, and then I'll remove this. What this is expected to do is that it should compare the values of the properties of the resulting DTO. With the properties of the expected item, the item that we created over here, right? So that way with this very handy method, we don't have to go property by property, it will just go ahead and compare the entire thing for us. But that the only issue here is that seeing suspected it is actually a record type. As you remember, the item is a record type record types already. Alright, the equals method of the of the object, and that will make it so that this method doesn't behave very well, right, because he believes that you have to compare the DTO to the entity directly, as opposed to comparing the properties, which is what we care about. So to address this, we'll specify an additional option here. Which is going to be Options, Options dot comparing by members of the item of the item class. Without we're saying, Hey, don't compare the DTR directly to the to the item, just focus on the properties that each of them hum and as each of them have. And as long as the property is the same name, compare the values of those properties. So that way, you will go ahead and and issue go ahead and tell us that the objects are the same. Yep. And so with that, let's go ahead and run this test case and see what we get. So we'll go ahead and click Run test. Yep. And this case is passing. And just like we did this, just to keep things consistent, let's also modify the previous test to also use fluent assertions. So in this case, is going to be result that result should be off date. Not Found result. that replaces the previous line. Okay, so let's just verify that all these cases are passing, I'll go ahead and run these in Data Explorer here. And yes, it's all looking good. Good. And so now let's move ahead into our next unit test. Let's go back to the controller briefly. And let's see what else we got there. Perhaps this and back in the controller, and what we want to test now is our first metal here, the one that returns all the items available in the REST API in the repository. So remember, these items will just go ahead, retrieve all the items, transfer them into DTO. And then he returns and that's all he does. So what we want to verify is that for any of the items that we that we set up for the suppository that we have to set up the depository, they have to be returned as details, and they should match exactly the IDs that will obtain through depository. So let's go ahead and write a unit test for that. So back into the test class. Again, I'm going to copy the heater of these this case. And I'm going to scroll down here, Copy that. Okay, so here, let's do the proper naming. So these are going to be named get I get items a think are these going to be just with exceed with existing items. He will say, returns or items. And again, let's bring in our arrange, act and assert sections. And in this case, what we need is of course to get a series of items from the repository. So what we have to do first is to declare such a set of items are we will for that we'll create a simple array. So what I'll do is I'll say bar expected items equals new and this is going to be an array. And we're going to be using our create random item method here a few times perhaps less bringing in three items. Yep, so that will do it. Very handy method. And now we can go ahead and set up the repository to return those items. So I'll do repository stop, set up where the repo where they bought the gun get it and say saying so get one gig Titan 16 is invoked, which should return the expected items. Then we have to construct the controller. So I'll do it very similar to what we did with the previous this case, I'll just go ahead and copy this line over here. And then we will go ahead and do. So bar, act two items, equals a weight, controller, get items async. Thanks, that should retrieve the items. And now we have to do the comparison. So once again, we can use that very handy method of fluent assertions to do just an equivalence of comparison. So we can say, items should be equivalent to expected items. And once again, we'll have to do the options. Because we like, again, we're dealing with record types. So otherwise things will not work, right. And then options that comparing by members, I. Okay, so with that, let's go ahead and run this test. Let's see what we get. Yep, this passing. Awesome, close that. Okay, let's move forward back to ISIS controller, it's time to test our great item async method. So this is the one that goes ahead and creates the item in the repository. So in this case, we have to provide great identity as an input. And then we can verify is that we should be returning, we should be receiving as a return added to with a graded item. That's, that's what these metals is supposed to do. And in fact, that return an item should include the ID because it is not provided in there, create that and do so return items will have an ID and he will also have a graded date. So let's write out a test that can verify all these things. So back to items, control tests, they may gain grab the heater off the desk, perhaps so I grabbed the entire thing. Just copy this, and then remove the space and and remove this piece and I removed the solid piece. Okay, now this method will be called just start with the name of the method, which is create item async. And then this will be in this case, the current state, let's name it with item to create, because we're going to be providing the idea that should be created. And the dissertation is that it returns the Create a title. Right? Now in this case, the arrange piece involves preparing the accurate identity. So in this case, it's going to be it will be tricky to try to use a created random item, as we've been doing so far. So we'll be we'll be explicit in this case. So we will say I tend to create equals new create item DTO. And here we'll provide the elements of the query in detail. So we do provide a name, which is just going to be cool nucleoid string, we will provide a price, which again is going to be just random next, with 1000 again, and I think that that will be. So let me go quickly to create a new table with 12 to make sure I've covered the properties we need. So he has a name and the price. Yep, back here. And then in this case, I will actually not need to set up anything in the repository. Because it is not interesting. What happens I mean, for the terms of of this test case, it is not interested to see what happens when the repository is invoked, if there was a really simple act to create the item. So if you look back at I just controller, what's really going to happen here is that Jehovah God needs to call greet, I are amazing. And I will go ahead and gradiated. But I will encourage you to be a bit careful about what you're going to be testing here. Because you could also decide that no, I want to make sure that they created amazing metal is called in the repository. Right. So that so that yeah, I mean, it should get created. But that's going a little bit too much into the details of the test case. So you are getting you will be making your test case to be very prone to needs changes in the case of the implementation of this method changes, right. So ideally, you want to treat each of your test cases in such a way that they only provide some inputs to the method. And then eventually they validate the outputs of the method but they don't try to make Some just sort of what is going to happen inside. So in this case, we are not going to be carrying all this metal at all. So in fact, we're not going to be setting it up, we will go ahead and go back to this case, we'll go ahead and use invoke, invoke the action. So we will say, var greeted item. Sorry, it's going to be bar result equals weight, controller dot, create item aceing. We provide the item to create. And then we can go ahead and do the assert. And the first thing we're going to do here is try to retrieve that identity. So what I'll do is, I'll do we did item is the result that result as created an action result. Okay, that's the type of result we're going to receive here is a created action result. From that one, we want to get the value. And that value will turn it into an item we do a little bit convoluted for for this case. And now we can do the same equivalence thing that we've been doing so far. So I tend to create should be equivalent to created by, okay, and then we provide options. Like we said, there will be options that comparing by members. And in this case, the data we're going to use here is actually I can be deal. Okay, which is the, the type of the object that we received from the front desk of the creditor. Okay. But additionally, we want to do one more thing here, because a, both of these a DTS don't have the same members, if you remember, if we go to F 12, to identity, Oh, this one has four properties, as you can see. But if we go into great identity, or this one has only two properties over here. So that means that if you try to compare things like this is going to fail, because you're going to say, Hey, what are you writing has more properties than the other. So this, this doesn't make sense. So in these cases, what you can do is say, only look at the properties that are common between the two objects. And that will simplify things in this case. So that's all we can do. And then in the spirit of fluent assertions, we can use to dot excluding missing members. And that should do it for that for that one assertion. Okay, so we're comparing that the two objects are equivalent, but we will not pay attention to any members that are missing from for any other. However, we may want to actually check for those additional members. So for those who will be will be a bit more explicit. So So credit item, the ID should not be empty. Because the the method, it should generate an ID for for the scooter rider, and also create an item that create a date. Should we don't know exactly what, what day we're going to get in there. But we know that it should be, it should be close to the current time, right? Because this test just take milliseconds to execute. So we will say datetimeoffset UTC now. And then, just to be safe, we're going to give it a range of precision, because we don't know exactly how much time did basically today, although it should be super fast. But we're going to give it 1000 milliseconds to for for the difference between the times of when the item is created and the data we're checking here. Okay, so that should be should be it for this test. Let's go ahead and run it from the test. see what we get. Test is passing. It's looking good. Okay, so the next test we're going to look at, but less case we're going to look at is the case of the update, update item async. Does remember this method, it gets at the item to update, it will get it from the database. And if it doesn't find it, it will say not found. And otherwise, it will create a copy of the item to become the updated item with the updated properties. And then it will go ahead and update the item in the database and finally returns no content. Okay, just to be to not spend too much time here, we're only going to be covering one case here, which is the case of where the item actually exists. But you can you can imagine how to test for the not found case, which is a bit simpler. But then again, don't don't get into the trap of verifying that the item is actually being sent to the date itemizing method of a depository. We want to we will provide an input which is these two parameters here. We expect the output of no content of added that's everything that we need to verify here. Nothing else, we don't need to worry about the implementation of the method. So let's go back to I just got a test. And let's bring in again, just I'll do a copy of our last test over here. And so, this is going to be update, I think we take existing item returns no content, okay. And then we will meet these who need a controller will need that, we will remove this species at the end. So for the range base, as you remember from this controller, we will need a when good imec, Usain Bolt, you need to return it right so that we can move forward into this case. So, I think that that situation we covered already somewhere else. So, let me go back a little bit up. So this one here, so, we will grab these from the get item async. This case, let me grab that here. So, that would allow us to have an item to be returned by the by the depositor is done. So we will name these one, please thing item ID, that's the ID that exists in there. And now we need to declare the the actual item that we're going to provide to the methods. So they updated it. So let's first grab the item ID as a variable. So the item ID is system ID that ID. So we'll grab that there. And then I tend to update these a new update ID to and so we're going to provide a name naming scheme to be cool if you go it to string. And perhaps we download line. And then for the price we can do is just pick the price of the existing item price and just increase it a by somebody, let's say by three. Okay, so that becomes the updated paper from this item. So we pretty much were changing the name because we're getting really unusual, we're changing the price by adding three to it. Then we create the controller. And I started to do the the action. So we'll say result equals await controller that update async. And then here's where we provide the item ID. And then we provide the item to update. And then finally we go for the assertion, the assertion is going to be very simple, because like I said, we only want to verify that we we get no content. So result should be of type. No content result. That's all it is. So again, we set up the return of the item from the repository, we prepare nine out of date, we modify the properties, we invoke a bit of the async. And at the end, if everything went well, we should be getting the content result. So let's go ahead and run this test. All best, I think we're missing just one method at this point. Let's go to IRS controller. So this is delete I basic, right? It's got to be very simple. To verify and very similar to update, we get an ID, it will have to a Find the Item. Again, we're not going to check all the cases, for this case, just a case where the item exists. So we'll make it so that it returns the item. And then it should return no content. And again, we don't care what happens with the repository or any of the internals here, we just care about the fact that it should return the content. So back to I just adore tests. I'm going to copy your lastest case, once again. This is going to be named delete it may sync with existing item returns no content. Yep, that's an appropriate name. The setup will work just fine for this case. But then we don't have to prepare any item to update us do that. Create the controller with those setups. And then we'll do the database sync with the it will be just the existing ID and that ID and then the assert is exactly same as before. There's should be of type knock on result. That's all it is. So I'll go ahead and run this test now. And Yep, it is passing. And in fact, if we go to our test Explorer, now, let's go to the test section here. And let's run this. As you can see, we have a full suite of tests passing at this point. Okay, so this is great, we have a bunch of test cases covering many, there's nothing in our controller. And what this gives us now is actually a lot of confidence or making any future changes across the, across the REST API. So what I'd like to do now is, there's there's been a few changes that I wanted to make across the board. But I didn't, I didn't have a way to make sure that didn't break anything. But now we do. So I'm going to make two critical changes here. One of them is that I'm going to switch our entity to not be a record type anymore. So remember, he's here if you go to the entities item. So the fact that he's a record type is actually making things a bit inflexible, I mean text. Because of this, we cannot use update existing items in the update a operation in the controller, and we have to create this copy that's not really needed. So these entities should be actively moldable. So we don't need these any stuff here, really. So we'll switch this to be a normal class. And we will also add a description property here, so we can provide some description for the items. So let's make those two changes. And let's see if our test cases can help us prevent breaking anything. So like I said, This item is going to change from record to class. And then we will not be using it here. But we will switch it to just set. So set in all of this. And now this is a normal standard class. But also, like I said, we're going to be adding a description, description for the entity. So with that done. The other thing that I like to do, actually, is to simplify the way that we use videos. Remember that we have these three files for the three videos. But it turns out that there's a much better nicer way to declare the video such as record types, which actually provides even more benefits that we are doing today. So what I'll do is I'll actually just get rid of all these files. Let me just delete the CTOs folder. Perhaps collapse these a bit, what I'm going to do is create a new file at the root of catalog API. Let's name it. videos at CS. Let's bring in some namespace, right namespace, which would be catalog that KPI details, we will declare all the details here in line in a much more a nicer way. Let me hide the sidebar. So for the first video is going to be the item detail. So we will say what do you record it to, then we will declare the properties as if we were creating like a constructor for for this property. That's something that you can do that we will say good ID. And then let's see if we're missing this system. And they will do name the new description property price, and they time offset created date. Okay, so that's you know, that's that's what you need to do to create to declare a record type in this other syntax. So as you can see, is much, much more simplified. Now, let's declare the next one is going to be only record, create item DTO. And then this is going to have no ID but the name and then the new description, property. And then the price. Let's not forget that we had set up some attributes here to make to make sure that we get valid inputs. So in the case of names, we want it to be required. It's amazing the space and in the case of price, what we want is 25 range. So the range Yeah, it was from one to 1000 Okay, we will not require description, and we will not require we will not add the required attributes to price because price is actually validate. So it cannot ever be no, you will get somebody there anyways. And we will just verify that the range is correct. Lastly, let's add our last detail that we're missing. I just copy that one. And this is going to be updated in detail. Yep. So that's all we need. So now in one file we have we're declaring all the details that we're using across the REST API as opposed to three files. Let's see what else we need to modify. So now that we make those changes, let's look at extensions. Let's see what's going on here. Yeah, so I'll hide cyber. So now that we change the way that we declared our details as record types, they have become immutable. We cannot go through this initialization anymore. We must create the DTO via the constructor. It's the only way to create instances of them from here on. And after construction, nobody can change the properties of the DTO. So we will say new identity Oh, and then we will provide it that ID. Id and the pain. Right? And that scription. I think that price, an item that created date, right? That's always Yep, we got liquid in line these over here, but it may be too much to read. So we'll just leave it like this. Okay, let's see what else we have to fix. If we go back, so there's something going on in the controller? Let's see what it is. Yep. So there's an issue with update imazing? Yep. So we cannot use this syntax anymore. Because the item is no longer a record type. Now it is a standard class. And in fact, this is this is good. This is actually exactly what we wanted to fix here. Because there's no need to create this updated item, we could just modify the existing item. So we will say, existing item that name equals item D do that name, an existing item, the price equals identity or that the price. Yep. So we don't need these additional guy here. We'll leave it like that. And then for the update, we'll use invoke existing IRA. Okay, so yeah, there's no more breaks around here. Let's see what else. So because of API, everything looks good in the unit tests. Let's see what's going on. Okay, let's hide the sidebar. Let's see. Yep. So great identity Oh, has to be weighted to define the properties inside the constructor. So we'll have to provide these for the name. And they probably will do the same thing for the description. And for the price, the random number, perhaps, so I'll delete this. And then I'll do it like this. That is it is easier to see. There. Okay. So let's see what else we have to fix here. Just in case for update identity. Oh. So let me copy this line here. So we have to provide that then we provide a description. And then we provide the price, which is going to be existing item price plus three. Okay, remove this. Yep. And with that, I think we don't have any more breaks are not in there. I can see actually. And so let's go ahead. And now let's run our tests and see what we get. So go ahead and run the tests. Yep. And, interestingly, we do have something failing here. Let's see what's going on. So great. It may sync is the one that's failing. And as you can see, we are getting the x over here, signaling that there's a problem. We get the squiggles here, signaling that there's something in there. And if this if we see the message over there, you can see it says expected member description to be no, but found some value in there. Yep. And then, so what could have happened? So let's actually go back to our controller. So I'll do f 12, from the controller. And let's go to the Create method. Over here. Let's hide this hide sidebar. And, yeah, so what happens here is if you can spot that is that we have not a percentage value for the description. So let me actually close this close these. So back to the test. Yep. So when we declared the item to create, we did add a description. But when we created the degraded item, it does not have any value for description. That is because we have not specified that here anywhere. So that's something we have to fix. And that's, that's a nice thing about using these should be equivalent to because as you add more properties, and you don't have to be remembering to do the proper checks in the test cases, right. Otherwise, anytime you you add a new property here, you have to go back to the test and other properties in there to make sure that you don't Forget what it is that this case is actually covering you, making sure that you don't forget to add those properties in the place where you're implementing the Edit method. For this case, I'll do description equals identity to that description. With that, let's go back to our test list, lets us run them again. It's all green now. And then one minor improvement that you can also do here is to change the way that we're doing some comparisons across a few test cases. So we go back to two lists test case, erasing, we created a retrospective item. If you see how we're doing B, A k be equivalent to here, these options, we need to do them because the item A during class A we're able to actually record before, so that was causing issues. Now that it's not a record type, we can stick to the normal behavior. So now we can just remove this and do the equivalent to this way. And fearless agents will know what to do. Because this is just a standard plus the same way we can go to the next case, and change this think. And that should be enough. And this is only because like I said, because what we're comparing here is the other classes are not record record type, you still have to do the other way. So let's just make sure that the test cases are still passing. So I'll go ahead and run all the tests. And everything is still all green. Okay, so that's working pretty well. And now I wanted to I'd like to switch gears into test driven development TDD. So we talked about TDD, it has some very nice benefits, because it allows you to start for the test for the requirements really, and then move forward to implementation later on. So let's, let's see, how do they work. In practice, what we're going to do is if we go back to items controller, and I'll hide these for a moment again, let's go back to our first method here, get items async. So as you see, this is the method that returns all the items. But a new requirement to our REST API is that we should be able to return a the items by a by the name. So if somebody specifies a name into into such a method, which should be able to return only the items where the name contains the specified parameter, right. So So if the if the, if you have items that have for instance, a word potion in them, like a potion, potion, potion, all these all these things, which are going to return all the items that include potion in the name, and not to the right, so it's a way of filtering things. But let's see how we can go ahead and implement such a method by using DDD. So I'll go back to I just controlled tests. So let's grab this, grab this method, get it and pick it as a sink. And then I'll just copy that just under it because there's similar methods. But in this case, we rename it to get either a sink, we will say, with matching items, returns, returns matching items. Okay, so in this case, we're going to go ahead, and we will not be using the random item anymore, because I actually want to specify a name for our items. And in fact, that's the only thing that we cared about, in the case of this test case. What do we want explicit here. So what I want to do is rearrange this a little bit, so that instead of these, what we have is, let's name these, all items are all items equals new. And then I'll just move these to the next line is going to be a bit more verbose. Like this perhaps. And then, in each of these lines, instead of these, we're going to create new items, new items, so we will say new item. And he will will provide a name. So let's use something that we can use for these tests. Like I said, Let's go for the potion. potion case. So we will have a potion there. And then let's add two more. The second one is going to be named Let's name it something completely different, like how to do it. And then the last one is going to be highbush. So in this case, we have two items that have the same, the same term portion and another one that doesn't have it. And then we'll declare a variable here that we're going to say its name, name to match equals Now notice that we are already implemented this case for this new method, but the method just does not exist at all, he has not been implemented. And that's the right way of doing DDD. So we will start with a test case that will actually fail because we don't have the method, and then we will move forward implementation later. Okay, so now we're depositary inbox, get items async, we will return all the items that we have prepared in here. Remember, this is the call to the opposite, it is not the call to the controller get is async. So then we go ahead and prepare our controller and then a constant time to make the call to the act. Now here, we're going to be a bit more explicit. The first it will now go to us in bar on the left side, because we want to signal to the to C sharp and VS code, what we're going to receive from this new method or method to be created. So in this case, what we're going to receive is an ienumerable. of item DTO. Are these going to be found items? And are we missing something? Yeah, system collection generic was amazing. And then these are going to come by calling weight controller, get items async. But not the signature, we need a new signature, where we can actually pipe them async we need a new signature, we can receive the name to match. So we're going to pass name to match here. Okay. And yeah, so yeah, that's got to be great. And then as, as our assert, what we have to verify is that we only got items that were their name, match the name to batch in this case potion. So to verify that we will say phone items should only contain. And then we can say item where item that name should be equals to item, it will be items soup, sorry, so this is all items, sub zero dot name, because that's the first one, let's scroll up a little bit. So we got zero, and we got one and two. So it should be that one. Or, and then just copy this should be I think name should be equals to a lightened suit to that name. Okay, so that's a way that you can use fluent assertions to verify that the items in the collection match some condition. So whatever we're getting, we're getting four items, a, the item should match either phusion or hipolito. In this case, okay. So if we go ahead and build this, I'll do Ctrl Shift v. Course it fails. Because we don't have such a metal gate is a thing that receives some argument. So that's kind of the red face of DDD. And now to start moving into the green phase, we need to move forward and implement implement this is meant to do that, or we can do is just click here, I'll do a Ctrl dot. And that a presents his options or we can do is use a generate method, I just controller get get isolate async. So I'll do that. And then if I do f 12. Here, the method now exists. And I'll move this up just next to the one that we have already the other overload here. Okay, and then we could go ahead and try to implement these. But as you notice, these methods are exactly the same thing. But one of them receives a parameter and the other one does not receive it. So I think it's better to just put everything in this one method, as opposed to try to implement the second one. So I'm going to just take this parameter out of here and into there. Are there Okay, and then we are not expecting to always receive the name, it depends on what the caller wants. So let's make so that these a can receive no, so it is allowed to receive. Okay, and so with that, let's go ahead and run or this case a once again, let's see what we get. I mean, at this point, you should build just fine this verify that should build Yeah, it does build. Now let's run the test. And in our suspected it is failing. It is failing because it is carrying a more items than expected. And on this as a result found items, just getting all the items is not getting only the ones that have been specified here. So let's see how we can fix this. So let's try to get green. So what we're going to do is something very simple after retrieving the list Both items, we're going to apply some filtering if we have to apply a filter. So if string.is null or whitespace. Name, name to match. That only list, let's just rename these to name as opposed to need to match. That should be enough. If name is more whitespace if it is not known as whitespace, then we will apply a filter on the list of files we have already received. So items is going to be items where item height in duck name, contain corn contains the me. And just to make sure that we don't, we don't worry about casing here. Let's do strings comparison already. Now, in our case, we that it doesn't matter. If you're looking for potions for with capital P or with smaller p, it shouldn't matter. We don't we don't care about that. So as long as as a name has been provided able to use it to do a filter on the items, so we get a filtered list of items. And that should be enough to satisfy the condition. Let's go back to the test. Let's run it. And this time it is passing. So we are agreeing, this actually confirmed that this is true by running the entire test suite now. And making sure that we have not broken anything. Yeah, as you can see, everything is green now. And so everything looks look great. So that's how you how you can use a DDD. We don't really need to do more refactoring here at this point. But if you needed to you feel free to go ahead and do more refactoring. But we have gone through the red phase, green phase. And now refactoring is not not dealing this case. What we can do now is to verify that this new functionality actually works in the in the real life. So we will start our host, and we will see how to use these from postman. Okay, so I'll go ahead and hit f5. And then going to postman are here. So let's see. To start with, we'll see what we have currently in our database. So I have here the URL to get all the items in the database. So I'll hit send. And at this point, we have a potion and antidote. And we are ready verifying that things are not broken, because we already in both this method that has been modified, it can receive a parameter now, but it seems to be working just fine. So to properly verify that the new functionality is working, I'm going to actually add a yet another another item here via the post action. So I'll just copy the URL and say plus, I'll switch this to post, pay the URL and in the body of the raw. And I'll do Jason. And then I'll just copy the body of something else here, copy this, notice that the previous items don't have a description, and that's fine. And the new item will have one let's make sure we can have one. So let's do this. That. And then to keep things simple, I'll just name this guy potion. And this is going to be stores a small amount of HP. And the price is going to be let's say seven. So let's pause this. Okay, is there. And if we go back to our get a operation I hit set, here we can see that we have the three items now create now is where we can see if the filtering is working. So now I can say that name equals and are we looking for potion right? So portion, so they should only give me the mega petition and abortion. So I'll go ahead here and hit send. And indeed, we are only getting these two items. Notice that it didn't matter that I use a smaller p here and not a capital P that we have earlier, he was still able to find the items. So things are working as expected. So yeah, that's how you can use DD to drive your your process to add new functionality to the REST API. So as always, I hope this was useful. And if you're looking to dive in deeper into what I have covered in this tutorial series, please check out the link to my full online course in the video description that's been watching and I'll see you next time.
https://www.freecodecamp.org/news/create-a-rest-api-with-dot-net-5-and-c-sharp/
CC-MAIN-2021-43
refinedweb
63,639
80.82
In any database schema, it’s extremely common to have the fields “DateCreated, DateUpdated and DateDeleted” on almost every entity. At the very least, they provide helpful debugging information, but further, the DateDeleted affords a way to “soft delete” entities without actually deleting them. That being said, over the years I’ve seen some pretty interesting ways in which these have been implemented. The worst, in my view, is writing C# code that specifically updates the timestamp when created or updated. While simple, one clumsy developer later and you aren’t recording any timestamps at all. It’s very prone to “remembering” that you have to update the timestamp. Other times, I’ve seen database triggers used which.. works.. But then you have another problem in that you’re using database triggers! There’s a fairly simple method I’ve been using for years and it involves utilizing the ability to override the save behaviour of Entity Framework. Auditable Base Model The first thing we want to do is actually define a “base model” that all entities can inherit from. In my case, I use a base class called “Auditable” that looks like so : public abstract class Auditable { public DateTimeOffset DateCreated { get; set; } public DateTimeOffset? DateUpdated { get; set; } public DateTimeOffset? DateDeleted { get; set; } } And a couple of notes here : It’s an abstract class because it should only ever be inherited from We use DateTimeOffset because we will then store the timezone along with the timestamp. This is a personal preference but it just removes all ambiguity around “Is this UTC?” DateCreated is not null (Since anything created will have a timestamp), but the other two dates are! Note that if this is an existing database, you will need to allow nullables (And work out a migration strategy) as your existing records will not have a DateCreated. To use the class, we just need to inherit from it with any Entity Framework model. For example, let’s say we have a Customer object : public class Customer : Auditable { public int Id { get; set; } public string Name { get; set; } } So all the class has done is mean we don’t have to copy and paste the same 3 date fields everywhere, and that it’s enforced. Nice and simple! Overriding Context SaveChanges The next thing is maybe controversial, and I know there’s a few different ways to do this. Essentially we are looking for a way to say to Entity Framework “Hey, if you insert a new record, can you set the DateCreated please?”. There’s things like Entity Framework hooks and a few nuget packages that do similar things, but I’ve found the absolute easiest way is to simply override the save method of your database context. The full code looks something like : public class MyContext: DbContext { public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) { var insertedEntries = this.ChangeTracker.Entries() .Where(x => x.State == EntityState.Added) .Select(x => x.Entity); foreach(var insertedEntry in insertedEntries) { var auditableEntity = insertedEntry as Auditable; //If the inserted object is an Auditable. if(auditableEntity != null) { auditableEntity.DateCreated = DateTimeOffset.UtcNow; } } var modifiedEntries = this.ChangeTracker.Entries() .Where(x => x.State == EntityState.Modified) .Select(x => x.Entity); foreach (var modifiedEntry in modifiedEntries) { //If the inserted object is an Auditable. var auditableEntity = modifiedEntry as Auditable; if (auditableEntity != null) { auditableEntity.DateUpdated = DateTimeOffset.UtcNow; } } return base.SaveChangesAsync(cancellationToken); } } Now you’re context may have additional code, but this is the bare minimum to get things working. What this does is : Gets all entities that are being inserted, checks if they inherit from auditable, and if so set the Date Created. Gets all entities that are being updated, checks if they inherit from auditable, and is so set the Date Updated. Finally, call the base SaveChanges method that actually does the saving. Using this, we are essentially intercepting when Entity Framework would normally save all changes, and updating all timestamps at once with whatever is in the batch. Handling Soft Deletes Deletes are a special case for one big reason. If we actually try and call delete on an entity in Entity Framework, it gets added to the ChangeTracker as… well… a delete. And to unwind this at the point of saving and change it to an update would be complex. What I tend to do instead is on my BaseRepository (Because.. You’re using one of those right?), I check if an entity is Auditable and if so, do an update instead. The copy and paste from my BaseRepository looks like so : public async Task<T> Delete(T entity) { //If the type we are trying to delete is auditable, then we don’t actually delete it but instead set it to be updated with a delete date. if (typeof(Auditable).IsAssignableFrom(typeof(T))) { (entity as Auditable).DateDeleted = DateTimeOffset.UtcNow; _dbSet.Attach(entity); _context.Entry(entity).State = EntityState.Modified; } else { _dbSet.Remove(entity); } return entity; } Now your mileage may vary, especially if you are not using the Repository Pattern (Which you should be!). But in short, you must handle soft deletes as updates *instead* of simply calling Remove on the DbSet. Taking This Further What’s not shown here is that we can use this same methodology to update many other “automated” fields. We use this same system to track the last user to Create, Update and Delete entities. Once this is up and running, it’s often just a couple more lines to instantly gain traceability across every entity in your database! The post Auto Updating Created, Updated and Deleted Timestamps In Entity Framework appeared first on .NET Core Tutorials.
https://online-code-generator.com/auto-updating-created-updated-and-deleted-timestamps-in-entity-framework/
CC-MAIN-2022-40
refinedweb
930
53.41
having trouble writing a video file to local storage -- ends up corrupted - jeff_melton My end goal is to use Pythonista to upload video taken on my iPhone to Vimeo by way of their API. Using their official library (installed via StaSH), uploads are easy: Just provide a path to a local file. Generally, I'd like to select a video from Photo Roll, write it to Pythonista's local storage, upload it to Vimeo, then remove it from local storage. I'm writing the file, and it has the correct length in bytes, but the upload fails (it creates a tombstone at Vimeo, a zero-length file), and the file in local storage doesn't play when I try opening it in an external resource (Quick Look -> Save in Dropbox; won't play on phone or desktop). Here's what I have so far (truncating a few bits related to patching metadata into the uploaded file, plus local storage file removal): # coding: utf-8 import vimeo import photos from io import BytesIO from objc_util import ObjCInstance client = vimeo.VimeoClient(token='my_api_token') video_asset = photos.pick_asset() video_data = video_asset.get_image_data() video_bytes = video_data.getvalue() filename = str(ObjCInstance(video_asset).filename()) with open(filename, 'wb') as video: video.write(video_bytes) video.close() video_uri = client.upload(filename) I feel like I'm missing something obvious here, but I can't figure out what it is. Any help is much obliged. :) The photosmodule doesn't really support video out of the box, and get_image_datawill always return image data – for videos, it returns just one frame (the preview image in the Photos library). You can use objc_utilto expose more functionality of the underlying Photos framework though. Here's a quick demo of how you could use the ObjC bridge to get at the file of a video asset. This isn't tested very thoroughly, and I believe it won't work for e.g. timelapse videos, but it might be good enough for your purposes. from objc_util import * import threading import photos def get_video_path(asset): if asset.media_type != 'video': raise ValueError('Not a video asset') PHImageManager = ObjCClass('PHImageManager') mgr = PHImageManager.defaultManager() e = threading.Event() result = {} def handler_func(_cmd, _av_asset, _audio_mix, _info): av_asset = ObjCInstance(_av_asset) if av_asset.isKindOfClass_(ObjCClass('AVURLAsset')): asset_url = av_asset.URL() asset_path = str(asset_url.path()) result['path'] = asset_path e.set() ph_asset = ObjCInstance(asset) handler = ObjCBlock(handler_func, restype=None, argtypes=[c_void_p]*4) mgr.requestAVAssetForVideo_options_resultHandler_(ph_asset, None, handler) e.wait() return result.get('path', None) # Demo: Pick a video asset from the library, then copy the video file to Pythonista, and show a QuickLook preview... if __name__ == '__main__': asset = photos.pick_asset() video_path = get_video_path(asset) if video_path: import shutil, console, os shutil.copy(video_path, 'video.m4v') console.quicklook(os.path.abspath('video.m4v')) else: print('Could not get video file path') - jeff_melton @omz: Thank you very much. I'd wondered if I wasn't just getting one frame of the video. This does indeed get me started.
https://forum.omz-software.com/topic/3728/having-trouble-writing-a-video-file-to-local-storage-ends-up-corrupted/1
CC-MAIN-2018-09
refinedweb
486
50.63
I have read a BMP file into a byte array. So after looking into the answers of this question: byte array to int c++. Is this way of obtaining the widht and height from a BMP information header safe and correct? long width, height; memcpy(&width, &bmp[0x12], sizeof(long)); memcpy(&height, &bmp[0x16], sizeof(long)); And what problems could this approach bring? long* width = (long*)(&bmp[0x12]); long* height= (long*)(&bmp[0x16]); According to Wikipedia BMP file format, 0x12 is the offset of the bitmap width in pixels, and 0x16 the offset of the bitmap height in pixels. PD. I have found this solution for loading the bitmap from memory buffer but I want to keep the code simple because I only need the width, the height and the raw data of the bitmap, and I do not know if that answer is safe either. Thanks! Both approaches do essentially the same thing, and both have the same fundamental problem: won't work if the host system has a different byte-order than the BMP file uses. This is always the problem with directly accessing values larger than a single byte in binary format. The latter approach also has the additional disadvantage of possibly breaking if the host cannot do a long access at the resulting addresses. In short, both "solutions" are bad. It's better to extract the value byte-by-byte and re-consititute it: static uint32_t read_uint32_t(const uint8_t *buffer, size_t offset) { buffer += offset; const uint32_t b0 = *buffer++; const uint32_t b1 = *buffer++; const uint32_t b2 = *buffer++; const uint32_t b3 = *buffer++; return (b3 << 24) | (b2 << 16) | (b1 << 8) | b0; } The above uses a smidgeon of C99 for brevity, porting it back to C89 is trivial. Edit: the above works on any arcihtecture, since it's no longer doing direct accesses. Instead it assumes buffer contains bytes in little-endian format, which I believe is what the x86-originated BMP format always uses. So, it will work even on a big-endian machine. It also no longer does possibly mis-aligned large memory accesses, since all accesses are just byte-sized which should work. The memcpy works OK as long as long is a 32-bit value (I'd personally use uint32_t instead). The cast will work if you know the architecture that runs the code is always going to be x86. [Good points by others about byteorder]. If you care about byteorder, then use something like: uint32_t width = bmp[0x12] + (bmp[0x13] << 8) + (bmp[0x14] << 16) + (bmp[0x15] << 24); and the same for length. This assumes your bmp values are unsigned char. Both approaches might be correct for Win32. But generally both are unsafe. The first variant relies on sizeof(long) == 4. Second relies on this too but requires correct alignment of data (which might be problem e.g. on ARM). Both have on common that they assume a certain endianess and will show different behavior on e.g. x86 and mips.
http://m.dlxedu.com/m/askdetail/3/5055a497bfd92c1ef33433b789d6c85b.html
CC-MAIN-2018-47
refinedweb
495
61.87
#include < #include < gl/gl.h> #include < gl/glu.h> #include < gl/glaux.h> #include < gl/glut.h> = = = = = = C :\ Users \ LJ \ Desktop \ Tracking Locate \ Camera \ Stdafx.h (43): fatal error C1083: Failed to open included file: “gl/glaux. H” : No such file or directory C:\Program Files\Microsoft SDKS \Windows\ V7.0 A\Include\gl There are only two Files under C:\Program Files\Microsoft SDKS \Windows\v7.0A\Include\gl So in VS2010, the corresponding header file cannot be found in the default lookup process C:\Program Files\Microsoft SDKS \Windows\ V7.0 A\Lib You’d better download these files from the Internet. So the problem should be solved by copying the glaux-h and glaux-lib files (sometimes using glaux-dll), respectively, to the path referenced by default in VS2010 above. Read More: - In VS2010, the compiler cannot open the file “GL / glaux. H”: no such file or directory - The first time I write OpenGL program, what should I do when I encounter “can’t open include file:” GL / glaux. H “: no such file or directory”? - Solution to the problem of unable to open glaux. H in vs2013 - Solution of VS2008 unable to open GL / glaux. H header file - Vs compiling OpenGL project, the solution of unable to open the source file “GL / glaux. H” appears - Visual studio 2019 + OpenGL environment configuration - Small problems encountered in compiling OpenGL under VS2010 - Configuration of OpenGL in VS2010 - OpenGL learning notes: Problems and Solutions - Vc2010 configuring OpenGL environment - Implementation of OpenGL rotating cube - Configuring OpenGL in Chinese version of VS2010 and problem solving - The solution of configuring OpenGL in vs2017 - Error in header file when calling OpenGL to open obj file in vs2013: unable to open include file: “GL / glut. H”: no such file or directories - [graphics] exceptions in downloading and installing OpenGL in vs2017 - VIDEOIO ERROR: V4L: can’t open camera by index 0 - Error: unable to open include file: ‘GL / glut. H’ - Vs cannot open the source file unistd. H under Windows - 0028opengl program running prompt glut32.dll missing one of the solutions - The C compiler identification is unknown solution
https://programmerah.com/vs2010-compiler-cant-open-include-file-gl-glaux-h-no-such-file-or-directory-18203/
CC-MAIN-2021-10
refinedweb
351
65.22
Hey, I ran into this problem on a project I'm working on. I dumbed it down to like 5 lines in like 4 files to prove the concept, and it failed. Can anybody tell me what the deal is?? I have 4 files: t1.c, t2.c, t1.h, t2.h t1.c t1.ht1.hCode: #include <stdio.h> #include "t1.h" #include "t2.h" int main() { val = 7; printf("val = %i\n", val); change(); printf("val = %i\n", val); } t2.ct2.cCode: int val; t2.ht2.hCode: #include "t2.h" #include "t1.h" int change() { val = 9; } Compile it, compiles and runs absolutely fine.Compile it, compiles and runs absolutely fine.Code: int change(); NOW I change the .c extensions to .cpp, compile it with g++ (was using gcc before) - get multiple definitions on 'val.' Okay, I figured, it's because t1.h is included twice...so I change it to: Still has the error, exact error:Still has the error, exact error:Code: #ifndef T1_H #define T1_H int val; #endif Obviously the problem is with the linker - this is in essence the problem I'm having (at a much larger scale) on the project I'm working on.Obviously the problem is with the linker - this is in essence the problem I'm having (at a much larger scale) on the project I'm working on.Code: g++ t1.cpp t2.cpp /tmp/ccQuwt1c.o:(.bss+0x0): multiple definition of `val' /tmp/cc0hcOlA.o:(.bss+0x0): first defined here collect2: ld returned 1 exit status This annoys me b/c I typically program C in a C way and when I use C++ it's typically object oriented - very rarely do I use C++ in a C way like I am now, but due to needing the STL for this project, I'm forced to. Can anybody shed some light on this? If not, is there any way to do some weird extern magic so that I can add numbers to a vector in C (yes, that's weird, I know). There's just no object oriented nature in this C++ code and it's obviously causing problems even though anything that compiles in C should compile in C++. Thanks in advance.
http://cboard.cprogramming.com/cplusplus-programming/133426-multiple-definitions-problems-versus-c-printable-thread.html
CC-MAIN-2015-32
refinedweb
375
76.22
There are three kinds of lies: lies, damned lies, and statistics. Introduction While surfing the depths of the Internet during the weekends, I stumbled upon a money management system I had never heard of before. It is called the Labouchere, or Cancellation system (Forex Vacuum Cleaner System using the Labouchere, in Russian). The English description of the system can be found here. The system is a variation of Martingale, since you need to raise your bet after you lose and minimize it after you win. However, it is a less aggressive version, since bets are not doubled, but are raised by a certain amount instead. Below are some passages describing the system properties that intrigued me very much: "So, please note that the amount of profitable trades should exceed 33-40% percent in order for the system to work properly and win!!!" – This is a very strong statement. However, it is not clear why the initial percentage range is so wide – from 33% to 40%. "Keep in mind, that this method can be considered to be a dishonest scheme by a gaming house". – Really? So, may be it actually works then?! "But the principle remains the same – 33% of wins compensate 66% of losses. So, if you want to apply this money management in real Forex trading, you need a trading system with the winning chance of 50% and the profit factor >=1". In fact, the mentioned article states that you need a trading system where wins are equal to losses and the win probability is 50% (or even "more than 33%"). If you have such a system, the Labouchere method can easily make it profitable! So, do we even have to look for a system with a positive mathematical expectation, since there is a way to shift it into positive territory? After all, it is not too difficult to develop a trading system featuring, say, 47% of wins... Let's see how the Labouchere system varies the stakes. The minimum bet is conventionally assumed to be equal to one. If we win, the bet size remains the same, while our trading balance increases slightly. If we lose, our bet size is increased by one – up to 2, and we add the losing bet size to the line: -1 If we win at this point, we should add 2 to our line: -1 2 Then we cross out these two numbers, since we have managed to win our loss back (in other words, we have increased our balance by one in a series consisting of two bets). Now, let's consider a longer losing series. -1 Let's bet 2. Loss: -1 -2 Let's bet 3. Loss: -1 -2 -3 Let's bet 4. Loss: -1 -2 -3 -4 Let's bet 5. Loss: -1 -2 -3 -4 -5 Let's bet 6. Loss again: -1 -2 -3 -4 -5 -6 Let's bet 7. We finally win: -1 -2 -3 -4 -5 -6 +7 Thus, we cross out "-1", "-6" and "+7", since our winning bet compensates two losing ones. The next bet is the sum of the first and the last of the values remaining in the line, i.e. it is 7 again. If we win: -2 -3 -4 -5 +7We cross out "-2", "-5" and "+7". Our next bet size is again the sum of the first and the last of the values remaining in the line. Yes, it is 7 again (some method followers recommend adding 1 to such a bet, so that you receive the minimum profit instead of 0 in case of a good luck). If we win: -3 -4 +7 We cross out all the numbers remaining in the line, since we have won our losses back. If we receive a loss at one of the intermediate stages, the loss size is also entered to the line, and the next bet is equal to the sum of the first and the last values in the line. So, what are the initial conclusions? A series of 6 losses is indeed compensated by a series of only 3 wins (however, it should actually be a series; we will talk about that later). At first glance, the system really makes it easy to leave the market with no losses. The bet size is increased much slower compared to Martingale. If we have used such a series with the original Martingale system, our final bet would have had to exceed the initial one by 64 times. The total deposit drawdown (the sum of losing bets) in the example above comprises only 21, while it would have been 63 for the original Martingale. Simple calculations show that we should suffer 13 losses in a row to lose all our funds in case the initial bet is 1% of the deposit and 44 losses in a row if it is 0.1%. You may already think: "44 losses in a row with 50/50 ratio!? The probability is vanishingly small! It is more likely that I will be struck by a meteorite! Such probability fits me just fine!", etc.). You can easily find numerous studies devoted to the drawbacks and dangers of the Martingale system. In fact, you can experience these drawbacks on your own by performing simple calculations using a pen and a paper. However, I was not able to find similar studies for the Labouchere system. The betting system looks very complicated, thus hindering the calculation of a resulting mathematical expectation. But let's go back to our losing series of bets. Let's consider that our 6 losses in a row were followed by only 2 wins, instead of 3. Then our line of numbers will look as follows: -3 -4 We bet 7 and lose: -3 -4 -7We bet 10 (note that while we lose, the bet size starts growing by 3 instead of 1 making our series much less safe for our deposit). We lose again: -3 -4 -7 -10 We have to bet 13 now. So, the system makes us raise our stakes by more than 1 in case of repeated losses. This seems to be the only way to fully overcome the drawdown. Here is where our deposit may fall into real trouble, since we need a series of wins to overcome the drawdown. Calculating the expectation on paper still seems to be too complicated or at least too boring... Are you interested in what this system is capable of? If yes, then let's delve into more details. Setting the Task: Subject and Methods The most important question is if the Labouchere money management system is really able to shift a mathematical expectation (especially into the positive area). The quoted passage about 33% of wins where win = loss sounds rather unrealistic, of course. But may be 49% or 50% of wins will be enough? And if not, maybe the Labouchere system has some other advantages? We will use statistics, which means that we need to develop an MQL program (it is MQL4 in this case, since I have not fully mastered MQL5 yet). Let our program perform millions of deals and "wipe out" thousands of deposits — we will look and analyze the results without any harm to our funds. If the program turns out to be profitable, it will be possible to implement the algorithm into real trading. The Labouchere system has been developed based on the win = loss assumption. It can be adapted for other ratios as well but that does not seem reasonable. If the system can affect the mathematical expectation with win = loss, then it can affect other ratios as well. And if it cannot, then we will simply waste our time pondering over a suitable adaptation. Besides, we can imagine the system with win = loss and the equilibrium value of 50% of winning bets much easier, since we are all familiar with coin tossing. Therefore, let's call our program CoinTest. First, we should describe the main features of our future program: We should have an ability to change the winning probability. A 50/50 ratio is just a special case of equilibrium condition. - We should have an ability to set a risk level. The Labouchere system features a fixed bet size. If we scale our initial bet according to our deposit size, the essence of the system will be lost since our deposit will never return to its initial state after all values are crossed out of the line. We can recalculate a bet size after exiting a drawdown, however, this will lead to fractional numbers which are difficult to work with. Thus, we will use the two variables to set the risk – initial deposit and initial bet. It is necessary to set the maximum number of deals per deposit. It should be big enough, so that we can find out if we are going to lose the deposit even at a very low initial risk. After all, if the deposit continues to grow, the process can be infinite and we may never know the result. We should have an ability to examine the results of trade series on a single deposit both for the program debugging and for changing our business logic. Output to a file suits our purpose well. After we are done with writing a code for a single deposit pass, we should move on to collecting statistics on a series of passes on separate deposits and (preferably) with varying parameters. As you understand, one experiment means almost nothing here. Statistical results are also sent to the file. We no more need to examine a history of individual deposits. Our bet size selection system can potentially be used in real trading, therefore we should make it a class. The actual opening of deals in MetaTrader is useless for us at this stage and extremely costly in terms of computing resources. We only need to fix the results of random deals performed using a required lot size and a given winning probability. With this in mind, we will develop a script, since this type of MQL programs is perfect for a single run as compared to Expert Advisors or indicators. Statistical Verification of the Pseudo-Random Number Generator Quality The quality of the pseudo-random number generator (PRNG) is of the utmost importance to us, since it will be used to define the outcome of each deal (win/loss). The accuracy of long win/loss series distribution is most critical. We will try to evaluate the latter without referring to complicated mathematical statistics theory. This article is not intended for a serious study of the PRNG quality (otherwise, we would have had to conduct 15 different tests). We are most interested in the PRNG properties that can affect the Labouchere system testing results and do not require too complex verification procedures. MetaTrader features the standard MathRand() PRNG function. The PRNG sequence is initialized by the MathSrand() function. Let's write a small script (RandFile) to check the standard PRNG quality. The script will have 2 parameters: Number of millions of 32-bit random words it should generate (one 32-bit word per 3 calls of the MathRand() function providing 15 significant bits). The unit of measurement is a usual decimal million instead of 2 raised to the 20th power, since we are going to examine the results visually as well. The CalcSeries logical parameter (if the distribution of similar bits series lengths should be calculated). The calculation of a bit series lengths distribution is very resource-intensive (increasing the script execution time tenfold). Therefore, it has been arranged as a separate option. The script produces the following results: - the calculation time (displayed in the journal); - amount of 1 bits detected among all generated bits (displayed in the journal); - RandFile.bin file — binary file with the PRNG operation result; - RandStat.csv file — log file containing the occurrence rates of certain bytes; - RandOnesSeries.csv file — log file containing "1" bit series lengths; - RandZerosSeries.csv file — log file containing "0" bit series lengths. - 10 million test words of 4 bytes each (40 million bytes in total); - 100 million test words of 4 bytes each (400 million bytes in total); - 1 000 million test words of 4 bytes each (4 000 million bytes in total). Now, let's check the following parameters: - Compressibility of files containing random data by WinRAR with the maximum compression settings. High-quality random data is not compressed. Of course, the incompressibility of files does not necessarily mean the high quality of the random data they contain. But if they are compressed, that means the data has statistical regularity. - Amount of "1" bits: - Occurrence rate of certain bytes' values in random files: Lengths of identical bits series. We will generate two charts for each sample size: - the first one displays the actual amount of detected identical bit series of a certain length, as well as the equilibrium value of the amount of series of that length (in logarithmic scale); - the second shows the percentage deviation of the actual amount of detected identical bit series from the equilibrium (in logarithmic scale). The linear chart scale is not suitable for us since the values we have are extremely scattered (the values ranging from 1 to 4 000 000 000 or from 0.00001 to 6 000 are present on a single chart). Besides, the chart displaying the equilibrium value of the amount of long series in logarithmic scale is shown as a straight line – while the series length is increased by 1, the probability of its occurrence is halved. So, what are the conclusions? The standard PRNG efficiency is acceptable for our task. Archiving the files containing the PRNG operation results does not lead to their compression. The amount of zero and one bits corresponds to the equidistant value. The deviation from equilibrium (in percentage) decreases as the sample size increases. The distribution of the occurrence rate of certain bytes in the PRNG operation results fluctuates within a narrow range around the equilibrium. Occurrence rate scatter is reduced as the sample size is increased. Occurrence rate of identical bits series deviates from the equilibrium only if the series are quite long (which is quite rare). With the increase of the sample length, the actual occurrence rate "deviation point" moves away from the equilibrium towards increasing of the series length and is always located around the value of 100 inclusions for the entire sequence. Thus, we have not detected any major statistical flaws in the standard PRNG that are capable of distorting our test results even with the sequences of approximately 3 billion generations (3 generations are used per 32-bit word). Writing the CLabouchere Class for Managing Position Size The CLabouchere class has turned out to be small enough. Its interface consists of only two wrapper functions for setting/receiving initial lot size and two actually working functions – for setting a deal result and receiving the current position size, as well as for resetting to the initial state: // Labouchere money management. // Take/stop is assumed = 1/1. class CLabouchere { private: protected: // Initial lot. By default - 0.1. double p_dStartLot; // The string where numbers are stored according to Labouchere double p_dLotsString[]; public: void CLabouchere(); void ~CLabouchere(); double GetStartLot() {return p_dStartLot;}; void SetStartLot(double a_dStartLot) {p_dStartLot = a_dStartLot;}; // Return a lot that is to be used during the next market entry double GetCurrentLot(); // Write the current trade result - take (true) or stop (false) void SetResult(bool a_bResult); // Reset to the initial state except for the initial lot void Init() {ArrayResize(p_dLotsString, 0);}; }; Writing the Script. Preliminary Evaluation Now, it is time to write a simple script having a hundred or so strings. The input parameters are as follows: //--- input parameters input int RepeatsCount=100000; input int StartBalance = 10000; input int Take = 50; input double SuccessPercent = 50.0; // If true, SuccessPercent is ignored input bool FiftyFifty = true; The script makes a series of deals till the deposit is lost or the RepeatsCount is reached. The case of win/loss ratio = 50/50 is made a separate parameter. In the latter case, one bits of a pseudorandom number are used as coin tossing results. Otherwise, a profit/loss boundary value is calculated and a random number is compared to it. The separate parameter for 50/50 case has been implemented because the cycle of PRNG one bits fits us quite well, though we have not evaluated the occurrence cycle of the values exceeding a boundary value. The default settings: - deposit size – 10 000; - initial bet – 50 (0.5% of the initial deposit). Approximately, at the 10th launch of the script, we receive a spectacular result – the deposit comprises 46 300 at the 2 335th step. However, the drawdown occurs at the 2 372nd step already: This is how it looks on the chart: As we can see, the balance fell to critical values twice before the deposit was finally wiped out. In some cases, the deposit was destroyed within the first few dozens of trades, and there was not even a single case when it showed the maximum lifetime of 100 000 trades. While I was trying various parameters, the following modifications came to my mind: It would be reasonable to add a parameter defining the amount of funds withdrawn from the trading account. If we manage to withdraw the funds exceeding the initial deposit before it is wiped out, then our initial deposit simply becomes a foreseeable loss. Thus, the new parameter called PocketPercent was implemented. It defines the percentage of successful trades that we withdraw from the trading account and put in the "pocket". Using the "pocket" money is forbidden, only the funds at the trading account are put to risk. After all, that is how it usually happens in real life. Of course, the deposit should be launched multiple times on a loop (it would be quite a mundane task to perform the launch hundreds of times manually). We should also vary a couple of parameters – PocketPercent and Take (the initial bet size), as well as to calculate the average results ("pocket" funds and deposit funds, since the deposit is never brought down to the entire 0 but only down to the moment when it is impossible to perform the next trade). We should have two versions of the script: the first one performs recurrent runs without writing the trading details into a file, while the second one works the opposite way. Recurrent runs mean that we should use the object code. Thus, we develop the "operating code" as the CCoinTest class, while the scripts are made as simple as possible. The code for the one-pass script is so short that I can show it here in full (all work, including writing the trade details into a file, is done by the CCoinTest class): #include <CCoinTest.mqh> //--- input parameters input int RepeatsCount=100000; input int StartBalance = 10000; input int Take = 50; input int PocketPercent = 10; input double SuccessPercent = 50.0; input string S2 = "If true, SuccessPercent is ignored"; input bool FiftyFifty = true; input string S3 = "If true, use a fixed lot instead of Labouchere"; input bool FixedLot = false; void OnStart() { MathSrand(GetTickCount()); CCoinTest Coin; Coin.SetRepeatsCount(RepeatsCount); Coin.SetStartBalance(StartBalance); Coin.SetTake(Take); Coin.SetPocketPercent(PocketPercent); Coin.SetSuccessPercent(SuccessPercent); Coin.SetFiftyFifty(FiftyFifty); Coin.SetFileName("Coin.csv"); Coin.SetFixedLot(FixedLot); Coin.Go(); } After we add the "pocket", the system operation charts look a little different (40% of profit is withdrawn in the following example): The purple line ("Pocket" balance) is very similar to the perfect trading account chart every trader dreams about. But in fact, we should pay more attention to the yellow line (total balance of the trade account and the "pocket"), which does not look so good. Besides, the following charts are much more common: Below are our conclusions at the current stage: The system actually demonstrates the behavior intended by the author: drawdowns are often overcome and the deposit tends to grow further. Sometimes, such an attempt ends in complete failure. Actually, the system has only two options after entering the drawdown – it may either overcome it, or lose an entire deposit. The longer a deposit lives, the greater heights it reaches. The initial bet in these examples is 0.5% of the initial deposit (50 out of 10 000). In the first example, the basic risk level has been reduced approximately to 0.1% (the deposit was increased 4.5 times with the initial bet remaining the same). However, these measures did not save the deposit from failure. Final Evaluation for Different Probability Values. Comparing the Results of the Labouchere and Fixed-Bet Systems Now, let's move to the most exciting part – collecting the results of many experiments. We are about to find out if the wins on successful deposits can cover the losses on failed ones. Maybe the algorithm proves to be efficient if the initial bet size is lowered (thus, providing more protection to the deposit) or increased? What profit percentage should we withdraw from a trading account? Will the Labouchere system be any different from the fixed-rate one at all? And what will happen if the initial system has a positive mathematical expectation (the "coin" wins more often)? As you can see, there are a lot of questions we should deal with appropriately. The script for launching deposits in the loop with varying parameters consists of about 100 strings. I will show only a few fragments here. The input parameters: //--- input parameters input int RepeatsCount=100000; input int StartBalance = 10000; input string S1 = "Amount of deposits lost"; input int Deposits = 100; input double SuccessPercent = 50.0; input string S2 = "If true, SuccessPercent is ignored"; input bool FiftyFifty = true; input string S3 = "If true, use a fixed lot instead of Labouchere"; input bool FixedLot = false; The arrays containing the initial bet value and the win percentage placed in the "pocket": // PocketPercent array int iPocketPercents[24] = {1, 2, 3, 5, 7, 10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 75, 80, 85, 90, 95, 97, 98, 99}; // Initial bet array int iTakes[15] = {5, 10, 15, 20, 50, 75, 100, 150, 200, 300, 400, 500, 1000, 2000, 3000}; As we can see, the initial bet size varies from 5 (0.05% of the initial deposit) to 3 000 (30% of the initial deposit). The funds placed in the "pocket" vary from 1% to 99%. The parameters are set with a safety margin that overlaps reasonable limits in both directions. Thus, the search space is two-dimensional. 360 discrete points (24 * 15) are taken within that space. The average total balance ("pocket" funds + trading account funds) and the average amount of deals before the deposit loss (deposit lifetime) are calculated for each of the points based on the series result. The amount of deposits per series is set by the Deposits parameter. The two-dimensional space calculation results are three-dimensional, which means that they are difficult to display by two-dimensional means. To overcome this issue, let's simply draw two-dimensional charts with the x-axis standing for the points' serial numbers from the search space (from 0 to 359). If necessary, some certain Takes and PocketPercent values are provided separately. After running 100 deposits, the average balance is as follows: Below is the deposit lifetime chart (in the logarithmic scale): The deposit lifetime exceeds 10 000 trades with the initial risk of 0.05% steadily decreasing to less than 10 deals with the initial risk of 30%. The high PocketPercent value also reduces the average amount of deals before a deposit is lost. That is an expected result. We can select a few promising points on the chart displaying the average contents of the "pocket" and the balance. Four of the points are located close to each other, so hopefully we can find the optimum area. Now, let's calculate the results for Deposits = 1 000 and superimpose them on the same chart: As we can see, the supposedly optimum area simply vanished under the pressure of a sufficiently large number of statistical data. Regardless of any parameters, the chart randomly fluctuates near the initial balance of 10 000. Thus, Deposits = 100 is not sufficient. All further experiments will be carried out with Deposits = 1 000. Let's display the results of the Labouchere and fixed-bet systems on a single chart: The deposit lifetime chart for Labouchere and fixed-bet systems: Conclusions: The financial result of the Labouchere system is zero coinciding with that of the fixed-bet system. Unlike the Labouchere system, the fixed-bet one shows increased data scatter around the average value. It seems that the fixed Deposits value does not conform with the statistical behavior of the fixed-bet system too well. The deposit lifetime is much lower when using the Labouchere system (10 and more times with most parameters and even more than 100 times with certain parameters). In case of a low risk level, we can see that the chart reaches the limitation set by the RepeatsCount parameter (the default value is 100 000). These results partially confirm the popular opinion that the systems capable of increasing the risk level are dangerous for a deposit. Such systems reduce the deposit lifetime, though we have not discovered any dangers for financial results yet (at least on the average and providing that a certain win percentage is withdrawn). Let's introduce a new script parameter that will allow us to collect sufficient stat data for evaluating the behavior of high-risk areas: input string S2 = "Minimum amount of deals per each pair of parameters"; input int MinDeals = 10000000; If we have less than 10 millions trades per 1000 lost deposits, then we should continue. As a result, the chart data becomes less scattered: And now let's check the operation of the systems using the initial system probabilities not equal to 50/50. The deposit lifetime: What can we see on these charts? In case of 49% of winning deals, both systems become clearly unprofitable. Financial results of the fixed-bet system are very low showing that withdrawal of profit to the "pocket" is more suitable for the Labouchere system than for the fixed-bet one in case of a win ratio less than 50%. The funds are transferred to the "pocket" only after exiting a drawdown. Unlike the fixed-bet system, the Labouchere is able to set new records over and over again (as long as there is enough money to make yet another bet) even with the win ratio of 49%. In case their deposit is decreasing rapidly, human traders will most probably not perform 100 000 or even 10 000 deals till it is completely wiped out. They will surely stop trading much earlier. The fixed-bet system algorithm cannot do that. The Labouchere system algorithm is much more human-like in this regard, since it behaves just like a trader encouraged by new records and trading till the deposit is completely destroyed. Do you remember the eulogic article I mentioned in the Introduction? It says that the system will work even with "33-40%" of wins. Let's check the upper boundary (40%) of this range just for the fun of it: Now, let's consider the positive mathematical expectation of the initial system (more than 50% of wins). We have to display the balance charts in logarithmic scale even with the win ratio of 51%. Conclusions: Both systems have moved to positive expectation. In case of a low risk level, the fixed-bet system shows the unlimited "vitality". In other words, it is almost impossible to lose a deposit. However, the Labouchere system is still capable of destroying a deposit (but do not forget about the "pocket"). The fixed-bet system makes 10 times more profit than the Labouchere with most parameters (and sometimes even 17 times more profit with certain parameters). Most readers may think that the fixed-bet system is in all respects superior to the Labouchere. Not only it protects a deposit better, but also brings 10 times more money! Unfortunately, they are deceived by statistics. The fixed-bet system bumps into the limitation of 100 000 trades per one deposit. If the RepeatsCount parameter has been 200 000, then the system would have made 2 times more profit. "But it's just wonderful!" – the readers deceived by statistics will say. And they will be wrong again. Take a look at the chart of the average profits made by the systems per trade (in logarithmic scale): The chart of the profit per trade in percentage of the initial bet makes the entire picture even clearer: Conclusions: The fixed-bet system makes 2% of the initial bet per trade. This is fully consistent with the theory, since the win/loss rate is 51/49 here. In other words, the wins exceed the losses by 2. The Labouchere system makes more profit even with the most unsuitable parameters. And if the parameters are set correctly, it may yield as much as 6-7 times more profit. So, it seems that if you have an unlimited amount of time, you can do quite well without the Labouchere system. You may argue that the fixed-bet system can be replaced with the fixed risk percentage system, so that the profit per trade is increased (actually, the profit will grow continuously, but we should use similar distances for comparison). However, in this case, a position volume should be changed for the Labouchere system as well. So, the Labouchere system seems to be more profitable, doesn't it? If you say yes, then statistics has deceived you once again. Take a look at the table: In fact, we can easily make the same amount of profit using the fixed-bet system. We simply need to raise the bet 7 times (from 0.75% up to 5% in this case). Of course, 5% is a very high risk level. But the fixed-bet system still has 10 times more "vitality" in this case. So, the fixed-bet system seems to be more beneficial, doesn't it? I think, statistics has betrayed you again. In fact, it does not matter how many deals your deposit is able to survive (on the average, of course), since we put a part of our profits in the "pocket". If the total "pocket" funds exceed the initial account balance several times, the loss of the deposit is not a significant issue. Perhaps, the most valid conclusion that can be drawn from these calculations is as follows: "If the win ratio is 51%, the profits made by the Labouchere and fixed-bet systems are roughly the same, provided that the former has the initial bet of 0.75% of a deposit and 10% of the profit is withdrawn from the account, while the latter has a fixed bet of 5% of the initial deposit and 45% of profit is withdrawn from the account. The Labouchere system reaches the same level of profitability by increasing the position size during its operation". Besides, keep in mind that any statistical conclusions are considered to be valid only after conducting a large number of experiments. A single virtual account can be virtually split into several deposits. The loss of one virtual deposit means losing a part of the trading account and returning to the initial bet size when a certain risk level is reached. However, the article shows that simulation of as much as 100 deposits still yields very scattered data. If we split an average trader's deposit into 100 parts, normal trading will be impossible. Which system is better? It is hard to say. The choice depends on traders' preferences, and the mathematical expectation of the initial system is of critical importance here. The code shown in the article allows anyone to simulate the Labouchere system operation on their own trading system. Let's examine the charts of both systems with 55% of wins: With 55% of wins, both systems become profitable. The difference between the average profits per trade has decreased from 6-7 times (51% of wins) down to about 3.7 (55% of wins). This happens due to the fact that at a higher expectation of the initial system, the Labouchere system spends less time in drawdowns and therefore, does not have to trade using an increased lot too often. Conclusion No miracle happened. The Labouchere money management system cannot turn a loss-making or even a neutral system into a profitable one. Besides, the sources of some misconceptions about the Labouchere system are clearly seen now: - Complexity that hinders calculation of the system results. - Lack of statistical data during manual tests. - Ability of the system to set new profit records over and over again even if the initial system has negative expectation, thus making traders believe in its efficiency. Is the Labouchere system worth trying with a positive expectation system? The choice is yours. The Labouchere system is quite complicated, and its efficiency can hardly be called outstanding. Anyway, I can give you two tips – do not exceed the acceptable risk level if you care about your deposit and try to improve the mathematical expectation of your trading system. Translated from Russian by MetaQuotes Software Corp. Original article:
https://www.mql5.com/en/articles/1800
CC-MAIN-2017-13
refinedweb
5,556
60.85
Speed Up Your Metabolism Ranked #2,991 in Health, #31,464 overall Speed up Your Metabolism Through Diet But really, while we may be basically aware that, all else being equal, a stalk of celery is better for your metabolism than fries with gravy, our understanding of diet and metabolism is pretty low. To fix this, the following looks at some powerful and scientific diet-related tips that will speed up your metabolism . Indeed, as you'll soon learn, it's not merely what you eat that matters; it's when, and how, too. Boost your Metabolism Increase your Metabolism with Exercise Don't Hate Calories If you suddenly decrease the amount of calories that you need, your body won't reduce weight and fat cells it will store them in reserve. You will feel more tired because your body is storing your energy. You can actually gain weight by dramatically reducing your calorie intake, instead of burning off excess fat. You should consume a daily caloric intake that is proportionate to your body size, type, and weight loss goals. Great Stuff on Amazon Alli Weight-Loss Aid, Orlistat 60mg Capsules, 120-Count Refill Pack. Amazon Price: $47.50 (as of 07/11/2009) The Fast Track One-Day Detox Diet: Boost metabolism, get rid of fattening toxins, lose up to 8 pounds overnight and keep it off for good I have done this detox 3-4 times and really like the way I feel when I do it. It is hard to maintain (for my lifestyle at least) since its hard to always eat organic or get certain vegetables in your diet everyday. I would recommend this to anyone looking to lose a few pounds and break some bad eating habits. I like the recipes and wish that section were a little bigger. Also, I am unnaturally afraid of gluten now, which I am sure that in moderation, like any food, cannot be that bad. Overall, a great way to jumpstart healthy eating and weight loss with some definitely interesting ideas... Amazon Price: (as of 07/11/2009) The Fat Flush Foods : The World's Best Foods, Seasonings, and Supplements to Flush the Fat From Every Body Ann Louise has done it again! As someone who has lost...and kept off...90 pounds with the Fat Flush Plan, I love this new book. It is full of great information about 50 of the best foods, beverages, herbs, spices and supplements to help people get (and stay) trim and healthy. The book is well organized and easy to read. It is filled with great practical tips that are helping me save time in the kitchen AND save money at the grocery store. After two years of eating the Fat Flush way, I'm picking up some great new ideas for how to be a better, more efficient Fat Flush cook. This book would be great for anyone interested in healthy eating...even those who have never tried the Fat Flush Plan. I recommend it enthusiastically!! Amazon Price: $10.85 (as of 07/11/2009) Eating More can Speed up Your Metabolism 1. People who eat throughout the day do considerably less snacking. 2. People who eat throughout the day don't experience severe hunger pangs 3. You constantly keep your metabolism in motion by eating throughout the day, Just because it's good for speeding up your metabolism to eat frequently, this doesn't mean that you can eat junk all day long! Choose Healthy snacks. You should know the overall nutritional values of what you eat and not just the calorie count. Focusing on calories is only half of the job. You will need to ensure that you're eating enough protein, carbohydrates, fats (the good unsaturated kind!), and the other vitamins and minerals that your body needs in order to function at optimal levels. How To Speed Up Your Metabolism How to Speed Up Your Metabolism. Runtime: 3:49 10 Comments: Favourite Tips to help Speed Up Your Metabolism Speed Up Your Metabolism Let us know your best method or tip for speeding up your Metabolism Eating Early Kickstarts Your Metabolism Studies show that your metabolism slows during sleep and doesn't start to speed up again until you eat something. Simply by eating breakfast you can burn more calories throughout the day because you gave your metabolism a boost. Beware of high-fat breakfasts they can make you very hungry again, very soon! Try to have a high fiber breakfasts as they take longer to digest, and the body won't be hungry again for a while. Great Stuff on Amazon Eat, Drink, and Be Healthy: The Harvard Medical School Guide. Amazon Price: $12.47 (as of 07/11/2009) Befriend Protein and Good Carbs There are some foods that are beneficial for helping you to speed up metabolism , and there are some that aren't. There are three basic food groups/types that help speed up your metabolism. 1. Protein Having enough protein in your system can increase the speed of your metabolism. This is because protein is difficult to break down. The more time your body spends breaking down protein the more calories it uses. The benefits you get from protein outweigh the fat intake. Try to find lean protein some fish and chicken is lean. 2. Carbohydrates The carbohydrates, you should look for are those that are high in fiber, and those from fruit and vegetable sources. Why? Because they don't promote fat storage. Weight Loss Articles for your Enjoyment Pilates is ia great way to speed up metabolism and loose weight - %uFFFD. More Great Lenses How To Boost Your Metabolism You often hear people talking about metabolism. Why do I have a slow metabolism? How can I boost my metabolism? One of the most commonly used words in the weight loss weight gain vocabulary would be Metabolism. Boost your Metabolism and burn calories... How To Increase Metabolism It's going to be old news for you to be reminded that exercising plays a big part in your efforts to increase metabolism and burn up calories. Unless you're born with one of those unusually active metabolisms which allows you to, almost freakishly,... Benefits of Pilates Since its introduction around 1910, many people have benefited from using Pilates and participating in Pilate classes for more than 90yrs. Here are a few of the benefits you'll get when you take a Pilates class. Improvement in Flexibility A Pilates... Please leave a comment and let me know How you enjoyed my lens. All My Lenses Lensroll this lens Add this Lens to Your Favorites Contact Me Join My Fan Club WendyKrick wrote... great lens with lots of valuable tips. Lensrolling my lens "how I lost 10 pounds in 2 weeks". 5 stars for you. internetetc wrote... Hi, I also believe in changing lifestyle improving nutrition and adding workout to daily activity. I have a blog to share information about how to burn stomach fat at. Hope you get a chance to visit and share your knowledge. thrivingmom wrote... Thank you for using Thrivingmom's Critique Service. Here's your critique: Great topic for a lens. I belong to a gym and my personal trainer says the same thing about boosting metabolism...that small meals throughout the day are the answer. If you starve the body, it will store more fat. I love your lens' main image...very cute. Over all, you have good content here, but it feels like you need something more. Perhaps add some pollaroids and some poll modules. Maybe even add a text plexo where visitors can add their metabolism boosting tips. The only thing that I see that needs fixing is that you need to put a hard return (space) between all of your paragraphs in each module. For some reason it all squished together. I wish you much luck with your lens and your metabolism. ArticleWiz wrote... Great lens, Gail! Some very informative info. Speeding up or altering your metabolism can really help anyone lose weight. Earlier this year, I started eating healthy chicken sandwiches every day first thing in the morning at around 8:30 AM (I had not eaten breakfast since I was 12, I swear). I also started a low impact workout called Mastermoves - combining Mastermoves with the change in my eating patterns resulted in me dropping from 245 to 215 in just 3 months. I feel a million times better and I am almost back at my 21 year old weight. I feel better than I have in 5 years. Great lens, Gail! Anyone serious about weight loss should pay close attention, because adjusting your metabolism is easy and it really works. Here's my favorite link: Change your life learn how to speed up your metabolism
http://www.squidoo.com/speed-up-your-metabolism-with-diet
crawl-002
refinedweb
1,472
72.87
On Thu, Jan 23, 2014 at 11:56:43AM -0800, Jonathan Nieder wrote: > Jeff King wrote: > > > I think it was a bug waiting to surface if index v4 ever got wide use. > > Ah, ok. > > In that case I think git-compat-util.h should include something like > what block-sha1/sha1.c has: > > #if !defined(__i386__) && !defined(__x86_64__) && \ > !defined(_M_IX86) && !defined(_M_X64) && \ > !defined(__ppc__) && !defined(__ppc64__) && \ > !defined(__powerpc__) && !defined(__powerpc64__) && \ > !defined(__s390__) && !defined(__s390x__) > #define NEEDS_ALIGNED_ACCESS > #endif > > Otherwise we are relying on the person building to know their own > architecture intimately, which shouldn't be necessary. Advertising Yeah, I agree it would be nice to autodetect. I just didn't know what the right set of platforms was, and assumed people would tweak the Makefile knob as appropriate (though it is probably much easier to do so within the compiler, where we have the right architecture variables set). -Peff -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
https://www.mail-archive.com/git@vger.kernel.org/msg42565.html
CC-MAIN-2016-50
refinedweb
174
62.88
Latest posts from: CraqueCast, Extra! Extra!, AlienFlower Blog, Life Less Literary, scot hacker's foobar blog, Literary Kicks, The Fever Of Phineas, Mediajunkie, xian's running monolog, Yes Justice Yes Peace!, Zeigen. "like" this entry on friendfeed.com. Consider these three word pairs:. Wrapping. Carver Park, Minnesota (Hiking) | MN, USA Click Replay for hike animation Wrapped up the visit with a lovely 3-mile walk through Carver Park Reserve with the family and kids through rolling hills. Returned with a few tics and lots of great memories. Farewell Ben – we’ll always miss you. Her voice, singing, Baked in a land of brown, black and purple. Light, milk coffee clouds; Dark, cook chocolate shadows; Sparkle Stabs of Sugared Violet. Ohne Zucker Bitte. Kein Kandis. For Stuck Between Stations, Roger Moore on how Michael Jackson liberated Eastern Europe from communism: The Aviator, Part I: As with Elvis, I dismissed most of what he did long before he left. But MJ was an arresting presence even for those who, like me, did my best to ignore him. Elvis even seems an inadequate comparison for his stratospheric global reach. A closer comparison might be Howard Hughes, another man-child of erratic brilliance, whose master aviator’s soaring heights later gave way to reclusive paranoia and heartbreaking tailspin. Then, in The Aviator, Part II: Sky Saxon Moore pays tribute to Sky Saxon of The Seeds, whose death was completely overshadowed by Jackson’s. The Seeds discovered trippy keyboards before the Doors, and were unleashing raw power before the Stooges. They were their best at their simplest, exemplifying Woody Guthrie’s dictum that if you use more than two chords, you’re showing off. See also: Mayra Andrade’s Lunar Mission 1. After interviewing Philip Roth, James Marcus turned a culturally significant Roth utterance into an audio dance track (via Moby Lives). 2. Sarah Weinman unearths another writer in the Singer family, Hinde Esther Singer. 3. Kenyon Review: “What happens when a poet’s own name is invoked in a poem of her own making?” 4. Adira Amram of the wonderful musical Amram family has released her first record. Looking forward to hearing this! 5. McNally Jackson bookstore in Manhattan now has an Espresso Book Machine. As we pointed out before, Espressos are cool. 6. One interesting thing about this Persepolis fan-fic about the Iran elections, originating in Shanghai, is how well it captures Marjane Satrapi’s style. 7. It’s an old formula, this “post some ridiculous emails you’ve received about your blog” blog post. And yet, it’s still fun. 8. Michael Jackson read books. Good for him. 9. I’m glad that Bill Ayers has the courage to publish a book, a graphic memoir. Maybe it’ll come out on the same day as Dick Cheney’s. 10. Once upon a time, Literary Kicks was a website devoted to the Beat Generation. I know some of my early readers wish I had stuck with and perfected that formula, and if I had, maybe Peter Hale’s The Allen Ginsberg Project is what this site would have been like. Hale, who works closely with the Allen Ginsberg estate, has been putting high quality stuff up — rare Kerouac videos, beautiful images, surprising texts, with a wide range of coverage and a friendly touch — week after week. If you’re into modern-era experimental/alternative literature, you might want to follow this site.. A dustup is always fun. Caleb Crain basically murdalizes a non-fiction book called The Pleasures and Sorrows of Work by Alain de Botton in today’s New York Times Book Review. It’s an exciting article, but after examining the plays in detail I’m not quite sure who wins. A critic who sets out to write a strongly negative review ought to open with a powerful point, but Caleb Crain actually punches himself with the opening paragraph, which posits many doubtful assertions as fact:. This is some dense prose, and it expresses a surprisingly shallow point. Our connections with our jobs go much deeper than money. For many people, work is identity. It gives us our pride, our sense of self. Certainly work is a key part of who we are, not an activity we engage in with calculated detachment. I really don’t know where Caleb Crain is coming from with this opener. He also doesn’t mention the book he’s reviewing. He’s better when he gets to the book, which, in his opinion, reeks of condescension. Crain finds de Botton a highly unreliable and capricious journalist, and he scores one killer punch here, describing de Botton’s account of a dull interview with a bureaucrat in London:. Crain’s point about de Botton’s unconscious snobbery is a serious one, but interestingly Crain’s prose has a snobbish undertone too, as when he drops a reference to the classical music term “ostinato” into a sentence. I can’t stand that kind of pretension — if I want to read about classical music I’ll read a damn book by Alex Ross (and, to be honest, I don’t want to read about classical music). Crain’s review also fails to connect the book to the long tradition of non-fiction literature about Americans at work: The Organization Man by Wiliam Whyte, Working by Studs Terkel, Gig by John Bowe and Marisa Bowe. All in all, I’ll hand this match to Alain de Botton. Caleb Crain does not have a strong enough offense to pull this bad review off. That’s about as exciting as this weekend’s NYTBR gets. Paul Bloom’s meditation upon The Evolution of God by Richard Wright is meant to be a rave (he calls the book brilliant) but the points I manage to glean from this review are wishy-washy. Speaking of condescension, both Bloom and Wright seem to assume that only monotheistic Western religions deserve our awe, and I don’t think much of the attitude expressed by this: In fact, when it comes to expanding the circle of moral consideration, he argues, religions like Buddhism have sometimes “outperformed the Abrahamics.” But this sounds like the death of God, not his evolution. It’s strange to imagine that anyone would want to read a modern history of religion that doesn’t take Buddhism seriously; this book is called The Evolution of God and in my observation the Eastern religions have a more highly evolved sense of God than the Western ones. Today’s NYTBR also features David Gates on Love and Obstacles by Alexsander Hemon and Jeremy McCarter on a new biography of playwright Arthur Miller by Christopher Bigsby. The {{ form }} <input after the reference to the django-profiles urlconf (you want to do this after, not before, so the last matching URL for /profiles/edit/ is the one you define, not the one django-profiles defines: from projname.appname.forms import ProfileForm ('^profiles/edit', 'profiles.views.edit_profile', {'form_class': ProfileForm,}), (r'^profiles/', include('profiles.urls')), You can pass in your custom success_url value in the same way:. Unfortunately, I was not able to find these answers from the Django docs on my own – a friend supplied the answers..: <p><strong>Address 2:</strong><br> {{ profile.address2 }} </p> <p><strong>City:</strong><br> {{ profile.city }} </p>). ——————- I have one remaining question: A common task when editing profile data would be to change one’s email address. But since the email address is included in the User model and not in the Profile model, it doesn’t show up in the {{form}} object. Anyone know how to get it in there?. I last updated this graph 15 days ago. In that time, the number of worldwide confirmed cases doubled from nearly 29,000 to nearly 60,000, according to the World Health Organization. These are not the number of fatal cases. The official count of worldwide fatalities has risen from 144 to 263. That’s a fatality rate of 0.4%, or 1 in 250. Various news reports this week stated that there were 1 million cases in the U.S. (for example, this article on the Discovery Channel’s site). Those reports are based on projections, not confirmed cases, and honestly to me the figure simply does not seem credible. The 1 million number is not backed by the CDC data, which matches the WHO’s report for U.S. cases. I do believe reporters have confused the concept of “number of vaccines needed in the worst case” with “number of people who have been infected.” However, it does seem apparent that the rate of new cases has increased. Previously we had seen about 4,500 new cases each week, for a period of three weeks in May. That increased to around 6,500 cases a week in early June. We’re now seeing about 15,500 cases per week for the last two weeks. It’s hard to say if we’ve seen the point where the number of cases is doubling consistently. It took two weeks to get from 15,000 cases to 30,000, then two weeks more to get from 30,000 cases to 60,000. It will be very interesting to see if the number of cases double again to 120,000 in the next two weeks. At that point, I predict news cycles would start to take things very seriously again. (Click to see full-size chart.) I figured they were mainly good, thought said — for the wedding night. the big day was over.. A year ago, I wrote this post attempting to debunk the superstition that deaths come in threes. With the passing of Ed MacMahon on Tuesday, along with Farrah Fawcett and Michael Jackson today, I’ve seen this superstition resurface. Yet my arguments from a year ago still stand. I’d also like to add this refutation: Dom DeLuise died alone. Take this list from Wikipedia of celebrities who died in May. I’d argue that Dom was the “most famous” of all the names listed there, but please feel free to assert differently if you disagree. So, where are the other two, if deaths do indeed come in threes? We can repeat the exercise for other months. RIP, Ed, Farrah, Michael and Dom. Please don’t cheapen their memory repeating a baseless superstition that tries to find a pattern where none exists. UPDATE June 28th: Billy Mays has also passed away today, breaking the pattern for even the current three. 1. How delightful to learn that James Joyce may have invented the word ‘blog’ during a typical conversational ramble in Finnegans Wake! Here it is in context:. Like (Today’s special guest reviewer is Scott Esposito, founder of The Quarterly Conversation, a literary review, and Conversational Reading, an associated blog.) The June 21 issue of the New York Times Book Review gets off to an bad start with Katie Roiphe’s front-page review of A Vindication of Love: Reclaiming Romance for the Twenty-First Century by Cristina Nehring (the review also briefly discusses Against Love by Laura Kipnis). The problem with Roiphe’s review is twofold: lack of specificity and excessive credulity. She continually hints at “riveting stories” and “creative interpretations,” yet, as Rolphie presents them, Nehring’s ideas sound as cliched as possible:. She asks, “Could it be that the choice of a challenging love object signals strength and resourcefulness rather than insecurity and psychological damage, as we so often hear?” If Rolphie in fact sees this for the bland attempt to be contrarian that it sounds like, she doesn’t let on. Elsewhere, Rolphie quotes Nehring: “We have been pragmatic and pedestrian about our erotic lives for too long,” and is content to let this remark stand, despite the masses of “hotter sex” books available in any bookstore, as well as the mainstreaming of various sexual devices and techniques considered the purview of perverts and Penthouse readers only a generation or two ago. The review concludes with that most damning of critical responses, faint praise: Nehring takes on our complaisance, our received ideas, our sloppy assumptions about our most important connections, and for that she deserves our admiration. Even if one doesn’t take her outlandish romantic arguments literally, this is one of those rare books that could make people think about their intimate lives in a new way. Dennis Lehane’s review of The Secret Speech, the second novel by writer Tom Rob Smith, is purely average. It’s your typical “several grafs of plot summary plus a couple grafs of opinion”; none of the writing is particularly good or bad, with the exception that one character is described as “beset by galactic levels of guilt.” I only remark on it here since it is one of only two full-length fiction reviews in this issue and therefore seems like a precious thing. Toni Bentley’s review of The East, the West, and Sex: A History of Erotic Encounters is a good example of a review that would have been fine if it was better edited. The book is about harems and Western explorers’ interaction with them, a topic not difficult to say at least a few interesting things about. Bentley does just that and quotes the book’s interesting thesis: “most of the world [pre-20th century] still subscribed to what I have been calling the harem culture, and in only the few countries of the West, the small peninsular domain of Christendom, did a different attitude prevail.” So far so good, although a little more than halfway through, the review loses focus entirely and just becomes a series of unrelated paragraphs. It probably could have been a fine review, but the length draws attention to the loss of focus; additionally Bentley, a dancer and author of books about dance, is way out of her depth here, and it shows. There are also an alarming number of annoying parentheticals, such as “It is not news that Christianity, with its Virgin Birth (just to start things off right), has had little interest in exploring human sexual desire or potential. Sexual energy is way too out of control even for the most committed Christians (see the Holy Trinity of Bakker, Swaggart and Haggard).” As a final note, none of the book’s illustrations are discussed, perhaps forgivable in a review of another book, but not in one of a book about harems. Ginia Bellafante’s review of the novel The Selected Works of T.S. Spivet (our second and last full-length fiction review), starts off annoyingly enough with a paragraph devoted to gossiping about the million dollar advance paid to the author. But after that first graf the review is actually rather good. It seems that author Reif Larsen has written something like a cross between the pomo novel of information and What Maisie Knew. That Bellafante gives a sense of this without dull plot summary or a lapse of critical opinion is fine work. Her negative review feels merited and her observations feel precise: “Roland Barthes made distinctions between those texts so micromanaged that they ensured reader passivity and those texts, active texts, that invited a greater degree of participation. The Selected Works of T. S. Spivet merely creates the illusion of choice.” However, I disagree with Bellafante that one of the plagues of MFA programs is that they produce writers who don’t “aim to mean much” with their books. I have no idea if MFA programs produce writers of this type or not, but if they do, that’s a good thing. I’ll take one writer who just cares about the craft of fiction over ten trying to make their novel “meaningful.” Good art creates its own meaning, by virtue of being good art. Ross Douthat’s review of Digital Barbarism, a nonfiction work by the novelist Mark Helprin, is interesting, largely because Helprin is one of very few public intellectuals to try and argue that American copyright law doesn’t go far enough in protecting intellectual property. However, we cannot count on Douthat to present the other side of this issue; for instance, his statement that “a more latitudinarian copyright regime” as “a cause celebre for a certain class of Internetista” is a ridiculous mischaracterization of a widespread movement backed by far more than a few over-active bloggers and cranky professors. Unfortunately it’s tough to find much of either side of the argument here. In his review, Douthat seems more interested in demeaning bloggers and commenters on websites than actually outlining what Helprin says or explaining exactly which people and ideas Helprin is arguing for or against (other than the obvious boogeyman, Lawrence Lessig). In other words, this is more like one of the op-eds that Douthat has been hired to write than a book review. The closest Douthat gets to giving us a flavor of Helprin’s argument is this sentence: Helprin worries, plausibly, that the spirit of perpetual acceleration threatens to carry all before it, frenzying our politics, barbarizing our language and depriving us of the kind of artistic greatness that isn’t available on Twitter feeds. Douthat is, of course, entitled to his beliefs (and he seems to believe that this sentence is largely accurate), but he does those beliefs no service by not even acknowledging the staleness of what Helprin says or the straw men that have been erected here. Much as I disagree with Douthat’s politics, though, at least his writing is far more engaging and professional than a lot of what Sam Tanenhaus seems –judging by this issue — to permit in his review of books. Rebecca Tuhus-Dubrow’s “Fiction Chronicle” (covering four new novels) reads roughly like publisher’s copy found on the back of new paperbacks. I understand that 300 words isn’t a whole lot of space to write about a book, but there’s a right way to do a 300-word review and a wrong way. These are wrong. For an idea of what can be accomplished in 300 words, see this review (among other successes) in the recent Review of Contemporary Fiction. But to return to the Times, the “Fiction Chronicle” does do me the service of presenting absolute worst book title I have read this week: “The Exchange Rate Between Love and Money.” And from the same book comes this quote-worthy line: “How do you make love to something that’s not even in the animal kingdom?” Maurice Isserman’s short essay on Michael Harrington and his groundbreaking study of poverty in America, The Other America, is lucid, engaging, and appreciated. It’s a nice example of how a review of books can keep important works from the past in the conversation, and Isserman’s fine piece is only marred by the sentence that opens its final paragraph: .” I must disagree: of course America’s poor are still very much unnoticed today, and if they are more seen now than before that owes more to unmitigated disasters like Hurricane Katrina than the work of journalists or (quite condescendingly) the decision of the children of the well-off to wear overpriced simulacra of the clothes worn in certain inner-city neighborhoods. Gary Rosen’s review of of The Age of the Unthinkable is a quick, clean, and successful deflating of a book that sounds pretentious, self-satisfied, and ultimately not even one-eighth as innovative as the author would hope (think of an aspiring Tom Friedman). It’s a lean, taut review, and the editors of the Review should aspire to cut down some of the more bloated pieces in their publication to resemble Rosen’s. Megan Marshall’s review of We Two by Gillian Gill is perfectly adequate and more or less bored me. So are, and did, Liz Robbins’s review of A Terrible Splendor (which, in addition to having a dreadful title, sounds like a dreadful book) and Marilyn Stasio’s roundup of crime novels. “Inside the List” informs me that something called the The Physick Book of Deliverance Dane debuted in the #2 spot for hardcover fiction, which does nothing to change my impression of the state of fiction in this country. The #1 spot is occupied by some Dean Koontz book about a novelist and a critic fighting to the death over a review. Does anyone honestly care? “Paperback Row” seems to be mostly obsessed with memoirs with awful conceits (”Gilmour, a film critic, allowed his troubled 15-year-old son to drop out of school on the condition that he watch three movies a week of Gilmour’s choosing.”) and the kind of petit cultural crit that should have remained a feature article in some glossy magazine. The inclusion at the end of Paul Auster’s previous work of fiction reminds me that he’s been publishing a lot of books lately. In the letters section it’s nice to see Ezra E. Fitz from Brentwood, Tennessee, sticking up for translators. I don’t have much to say about the “Editors’ Choice” list, except to note its lack of diversity. And rounding out this issue, the less that is said about the “Up Front: Dennis Lehane” by “The Editors,” the better. Not counting the “Fiction Chronicle,” this week’s issue of the Review covered 2 works of literary fiction, an abysmal performance by virtually any standard. All in all, the fiction coverage in this issue has done nothing to sway me from my belief that the Review is virtually irrelevant for anyone who seriously cares about literature in this country. Oddly enough, the nonfiction coverage in this issue of the Review gives me a renewed appreciation for Bookforum. True, that publication has seriously downgraded its fiction coverage over the past year, but at least the nonfiction coverage found therein is something that doesn’t consistently insult the intelligence of educated adults. And even the fiction coverage, in its weakened state, is infinitely preferable to what I read in this issue of the Review. I suppose if I were to grade this issue I could give it a “C,” in the sense that this is probably not much better and not much worse than the reviews of books still extant in the nation’s newspapers. However, if I were to grade the issue based on the standard that the Review sets for itself as the nation’s pre-eminent and most important weekly review of books, then I’d have to say that it’s failing to meet its expectations. stark-raving insane. I don’t know how they manage to deal with fame every day. It enervated me just to get my name in WIRED magazine twice. By the time the Notes From Underground clamor died down I’d sold about 350 copies, nowhere near enough to break even, and despite the good reviews I felt very discouraged. The truth is, there’s nothing like a small taste of success to make a guy feel like a real failure. It’s only when you reach for something far away, sometimes, that you discover your own limits, or ‘vi’ editor. I updated “Beat News” about once a month. There was no commenting, no community, no “Action Poetry”. I sometimes asked my stepfather Gene for business advice, and he suggested I transform the site into something commercial, perhaps an online version of Writer’s Digest. The idea didn’t thrill me.. For a year and a half I’d been looking forward to the initial public offering of NetGravity, the advertising software company I’d been closely involved with as one of the first end users. The IPO was finally scheduled for June 1998, and I was granted a valuable “friends and family” offer to buy 1000 shares at the opening price, which was wavering between $9 and $10. It was on deals like this that early investors in companies like Netscape and Amazon scored big on a popular stock’s opening day., flipped them immediately on Gene’s good advice, and netted about $200 for all my trouble. Some bonanza. Online content was just not hot in 1998, and this was especially true at Time Inc. New Media/Pathfinder, though we kept plugging away. My team (C++ programmer Diane King and data analyst Ken Gerstein) and I launched an exciting new service to help the ad sales team, the User Profile Server, a primitive attempt to support ad targeting through real-time cookie-based user profiling. It was an exciting piece of software and a true feat of engineering that took nine months of hard work, and yet it’s the sad truth that we never closed a single deal based on our ability to target ads. Another great moment in Pathfinder history. In early 1998 we got a new technology chief, Igor Shindel. The buzz about Igor was that he was a “turnaround guy”, expert at managing troubled software departments, which basically meant he was going to whip our scatter-brained asses back into marching formation. This was fine with me. I was bored with surfing the web in my office, and I wanted to work on something cool. But I didn’t want to manage the ad technology team anymore, so I asked Igor Shindel for a new responsibility. My best idea was to rebuild our web server architecture so that our magazine properties could have URLs like “Time.com” and “People.com” (instead of our embarrassing “Pathfinder.com”). gave her nothing and constantly held her back. All the magazine editors were angry about our shoddy server capabilities and performance, and I really thought my proposal had a chance. I was invited into Igor Shindel’s office about a week after I emailed the proposal around. He closed the door with the clinical grimness of a surgeon and told me it wasn’t going to happen., another complete. Of course, there’s another site, and everyone uses it every single day, but modesty demands that the only thing I say about it is that each update from this site consists of just the letters TMI. It’s kind of a crappy service. When. I’ve added Gürkan OLUÇ’s FriendFeed Comment plug-in, which should allow for any new posts I make here to have their FriendFeed comments and likes displayed as well. 1. For your Bloomsday enjoyment: comic strip artist Robert Berry is visualizing James Joyce’s Ulysses. This project appears to be off to a great start. 2. More Bloomsday action: Dovegreyreader on a new book called Ulysses and Us by Declan Kibberd. 3. Farewell to poet Harold Norse. 4. It must be a good sign that somewhere inside the giant paradox that is the nation of Iran, they are loving the inventive and hilarious early writings of Woody Allen. 5. I did not know that novelist Roxana Robinson was a member of the Beecher family. But what’s this about Lord Warburton being the man Isabel Archer should have married? I was rooting for Ralph Touchett. 6. The word technology is derived from the same root as textile. 7. We need a poetry reality show right here in the USA. 8. A digital Gutenberg would be nice to look at. 9. What could it possibly have been like to be married to Harold Pinter? Fortunately claims Antonia Fraser, it was not a Pinteresque experience. 10. “What would happen if one woman told the truth about her life?” (Or, I’d like to add, one man). 11. Eric Rosenfeld appreciates Thomas Pynchon’s use of description. 12. Kafka Tribute in New York 13. Michelle Obama reads Zadie Smith, a better choice (in my opinion) than her husband’s Joseph O’Neill. (Barack is also cited as reading What is the What?, a good choice though not exactly fiction). 14. The Who’s Quadrophenia GS Scooter has been sold at an auction. (Though it’s from the movie, not the record album photo shoot). 15. Via Bookninja, what the book you’re reading really says about you. Who let Jason Jones of the Daily Show in to talk to New York Times staffers? Hilarious and on the money. Fellow men, “Laundry” means sorting, folding, and putting away the clothes. Dumping the dirty stuff into the washer, moving it to the dryer — that’s all the easy part. I have learned this the hard way and hope you profit from my downfall. How about dem Bears? Now, please excuse me because I need to go use some power tools. Your bro, Stephen P.S. In other news, “doing the dishes” apparently means doing more than just piling the dirty dishes in the sink. I’m still investigating this one. Which of the following is racist? GREEN: What I am about to say is completely my own. No one told me what to say. No one wrote this for me. Not my lawyers, not the government, not anybody ...i's as good and bad, as men, women, and children. I started seeing them all as one, and evil, and less than human. When that happened, any natural, learned, or religious morality, that normally would have stopped this, was gone. But I see now that I was wrong .... Confession:, or for reference while writing something new. Easy to do in a desktop client. Assumed I could do similar in GMail by cmd-clicking messages to open them in various tabs, but nope – GMail doesn’t allow that – forces you to only be looking at one thing at a time. Is that a feature they haven’t implemented yet, or an intentional limitation? Feels like the latter.. There. A. BY SIKIVU HUTCHINSON.Sikivu Hutchinson is the editor of blackfemlens.org and a commentator for KPFK 90.7 FM. This:. This week at Stuck Between Stations: Roger Moore on the appearance of Metallica’s Lars Ulrich on the Rachel Maddow Show: Heavy Metal Drummer. Scot on the greatest prog rock band you’ve never heard of: The mythical Gemini Rising takes to the web’s faux airwaves. The: <?xml version="1.0"?> <?quicktime type="application/x-quicktime-media-link"?> <embed src="rtsp://streamer.domain.edu/events/131.humanity_2.0.mov" />.: <object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="480" height="376" codebase=""> <param name="SRC" value="/presentations/webcast-archive.227.ref.mov"> <param name="AUTOPLAY" value="true"> <param name="CONTROLLER" value="true"> <embed src="/presentations/webcast-archive.227.ref.mov" width="480" height="376" autoplay="true" controller="true" pluginspage=""> </object>: <param name="SRC" value="/presentations/webcast-archive.{{object.id}}.ref.mov"> which resolves to something like: <param name="SRC" value="/presentations/webcast-archive.267.ref.mov"> When the browser hits that line, it requests /presentations/webcast-archive.267.ref.mov from the server, which in turn triggers this entry in urls.py: url(r'^presentations/webcast-archive.(?P<pres_id>: <?xml version="1.0"?> <?quicktime type="application/x-quicktime-media-link"?> <embed src="rtsp://domain.edu/events/{{p.webcast_path}}/{{p.webcast_filename}}" />. The best Margarita in Alberta? The best sushi in Florence? The best Mexican food in Shanghai? The best bacon burger in Calcutta? Best canolli in Rio? Best falafel in Bangkok? Take that concept, add one obnoxious anti-social snob and you’ve got yourself a show!. Down the old Santa Fe trail sits La Fonda Hotel. Old lady: “Oh, look, it’s Jane Fonda’s hotel.” Old man: “Hanoi Jane? I’m not going in there.” The Gemological Institute of America (GIA), the world’s foremost authority on diamonds, colored stones, and pearls recently worked with Extractable to launch their new website. The new website was designed with a coherent navigational structure that promotes critical user paths. The site design and information architecture should increase student applications and stone submissions while driving repeat visitors as they have a more positive online experience with the GIA brand. If you need a stone evaluated, are interested in a jewelry career, need to buy a ring or learn more about a stone make sure to visit GIA online or visit them in Carlsbad. I’m re-organizing my music a little bit. I dropped my “Cowboy of Hope” blog and plan to just drop my tunes here as “Pages”. For now the “Music” tab above gives the playlist with everything. I’ll create a dedicated page for each song with liner notes eventually. Here’s the starter page, for my new song “Mr. Universe“. Again, I’ll add liner notes soon. One of the most important factors search engines use to rank your website for keyword phrases is analyzing the number of websites and how popular (or important) the websites that are linking to you are (note: I’ll refer to these type of links as “backward links” although other SEO professionals might call them inward links, insite links, etc). Google even patented a link analysis algorithm called Page Rank () which helps Google determine the ranking of your website on keyword phrases. Hence, link building should be an integral (and ongoing effort) in any search engine optimization (SEO) program. Where should you look to increase the number and quality of backward links to your website? To elaborate on the last point a little more; in Google’s search engine find related websites by using the following search syntax “related:” and identify any websites that might benefit from adding a link to your website. Don’t email or call the website owner blindly. You will need to build a relationship and prove value to the other website owner that creating a link to your website is in their best interests. Show value! For example, if your websites focuses on listing all the Happy Hour events in the city of San Francisco consider contacting websites like MustSeeSanFranisco.com or SFTravel.com. Who on vacation in San Francisco doesn’t want to have a drink at a local Happy Hour event? Lastly, don’t forget to “optimize” the hyperlink by including the primary keyword phrase in the actual link. Example: Instead of adding the following text to another website you are getting a link from, “Visit to see some social events including happy hours in the city” write “Visit our partner to find great happy hours events in San Francisco” The direct benefits of getting backward links is A) your website will receive more site traffic from visitors clicking through on that backward link and B) search engines will give your website more “weight” when determining where your website should appear on related keyword searches. To).. A.. Here’s a new one: Character is in a situation that triggers a memory. Now we go with that character into the memory for a while, a minute, two 30 seconds, whatever, but it’s long enough to shift context and follow a sub-narrative. Then we return to the original context, the present, with character’s face absorbed in the memory. Another character then has to jog the first character’s attention. “Joe? Joe” Where were you?” And the first character then has to come back, pretend it’s nothing and resume the first nbarrative thread. That whole jogging of the first character’s attention is completely unnecessary. It’s stupid to pretend that just because we in the audience experienced a time shift with the second thread that the characters in the first context also experienced it. The whole thing could have taken place in a split second for them. I don’t mind the actual context shift itself, I just hate the way they transition back. It’s so rote, total cliche, and they do it in the finest of dramas and films. Just skip it completely. Refuse to run to catch a train. Watching Mardi Gras parades at nola.com. Not the same. King cake acquired: Soup day. I love soup day. one bourbon, one scotch, one beer Congratulations to Campus Federal Credit Union (CFCU) based in Baton Rouge, Louisiana, on the new website launch! During the website redesign, Extractable worked with CFCU to make sure the new web experience on the CFCU website was as professional as larger financial institutions in the areas but also directly addressed the students, faculty and affiliates associated with Louisiana State University (LSU) that make up a large percentage of their member base. The website was designed for ease of use and to enable members to have a positive online banking experience. Before the website was launched benchmark figures were calculated in order to show a positive ROI on the project over the next several years. Figures and base costs originating from the website were calculated for the member call center, average products/services per member and on the total membership of the credit union. If you live in Louisiana or are affiliated with LSU please consider using CFCU as your primary financial institution because sometimes the “perfect bank for you, isn’t a bank at all”. A. Last. BBC Micro I played games on it, of course, many of them (I still remember the first night after we got it: Pacman was so burnt into my visual cortex that he continued to chase around my brain all night). But I also wrote games: typing in code from magazines and inventing small programs of my own. I even, along with my schoolfriend David Swaddle, set up a software company DSoft (which took its name from our shared initials). That never went very far (although bunking off school to hawk vapourware to all the local computer shops was kind of fun), but it was a start to something. At around the age of 16, I started to lose interest in computers. There were too many other things in life to grab my attention. But when I came to write my university dissertation five years later, my dad had just got a new PC, so I laid claim to the old BBC (which had been sold on to us by Thames for a nominal amount once the three-year loan was up) and used it for essays and revision notes. It took a few more years to rediscover programming: in fact, I was working for Olivetti, writing letters to debtors, when one day I looked at the computer I was typing on and thought “hey, I used to program these things when I was a kid. It was a lot more fun than this, and I bet I could get paid more money for doing it”. I went back to college to study C & C++, and never looked back. So eventually I’ve pitched up working at the BBC, and I guess (like many in BBC “Future Media & Technology”) you could say it was the BBC Micro which got me here. But, unlike many, it was an ITV company which had the foresight to give me that micro, and plant a seed which continues to bear fruit. I can’t imagine many companies being quite so forward-thinking nowadays, especially as in the intervening years all companies, private and public, have been “rationalised” to the extent where such costs are impossible to justify to shareholders/tax-payers. And I think that’s a very sad thing. In part one of my “2008 and thereabouts” retrospective, I talked about what I’d been up to work-wise. Now I’m going to focus on my personal and family life. I find this side of things a little harder to talk about, and recall, if only because for most of the year, I spent five days per week at work (usually in London, away from my family) and the other two days recuperating. But here goes… Of my immediate family, Rowan (now thirteen) completed her first year of secondary school, and Lola (a few weeks shy of eight) entered juniors. For Rowan the summer holidays of 2007, between primary and secondary, were some sort of chrysalis phase. Within a few weeks of starting King Edward’s she was a different person: not only in character, taste and habits (a new taste for fashion and music, a stand-offish muteness towards her parents and, for a short while, a boyfriend), but also physically: she seemed to grow about six inches in her first year (or should that be Y7 – I still can’t quite get to grips with our new American-style system) and very soon developed from a big girl into a young woman. Watching her become rapidly more independent has been wonderful, though sometimes painful. At times she can be incredibly argumentative and hurtful – like most teenagers I guess – but on those odd occasions when she lets me into her confidence, or tries unsuccessfully to hide her excitement about something, it melts my heart. I’m also immensely proud of the fact that she writes and draws keenly, and is showing real talent in both areas (she just won a Waterstone’s writing “supernatural love story” competition with a lengthy and very original tale of a girl who falls in love with a boy nobody else can see, only to find out that he’s a ghost). Lola hasn’t yet reached that troublesome age (although she can be troublesome in her own, usually much cuter, way). She is every inch the daddy’s girl, eager to please; but as she gets older she is becoming cleverer at using this to her advantage, turning on the cuteness tap when she knows it will get her what she wants. She excels at school (like her big sister before her), and seems to have an incredible quality for peace-brokering, whether this be bringing calm to a rowdy classroom or helping two friends to resolve a dispute. Teachers and other parents love her because she can (usually) be relied upon to be sensible and helpful, although I worry that as she gets older the sensible part may slip. She has also recently started piano lessons, and is learning incredibly quickly. Every week when I’m at home, she shows me her piano practice, and I have a go two, which is wonderful as it means I’m also getting to learn to play, and to read music. Gill too has been finding more outlets for her creative side. For a while she was working at a vintage clothes shop in Sheffield, but at the same time she was discovering eBay, buying and selling at first old nighties but increasingly a range of weird and wonderful items, retro and new, including dresses, handbags, purses, badges and jewellery. You can often find her abusing my eBay account. Recently, she has started to customise and combine items, so she may sew a 60s cloth doll’s face onto a 40s handbag, or make a brooch out of some tiny dollies attached to circles of Victorian lace. I bought her O’Reilly’s Fashioning Technology book for Christmas, so hopefully we’ll soon have antique accessories combined with flashing LEDs and intelligent textiles. The two of us have continued fostering with FCA, although obviously with me out of town most of the time, 99% of the work and responsibility has fallen on Gill. We are currently without a placement (and taking a bit of a break from it all – although we do have Gill’s cousin’s daughter Zoe staying with us, and her boyfriend Tyler, which is at times not too different from a foster placement). But for most of 2007 and 2008 we fostered two of our longest placements: N___, a Somali girl who was with us from the age of 15 to 17, and A___, an English boy who lived here from 16 to 17. With kids that age, for the most part you just let them get on with it. The biggest problem is getting them home on time: we have to set them curfews and, under strict foster agency/social services instructions, have to phone the police and report them missing if they’re not back by midnight. As you can imagine, this results in phone calls to missing persons on average about 3 times per week. Then we have to wait for the police to turn up, which they’re duty-bound to do, and which usually happens around 3am. Couple that with the odd petty crime and misdemeanour that kids in care tend to get themselves into, and we soon became pretty familiar with most of the local force (in fact, we were already fairly well known to them after we had a panic button installed when a previous placement, a young Muslim girl, heard that her family were threatening to burn her alive after hearing rumours that she’s been seen out with men). Which kinda brings me on to the subject of challenging situations. We’ve had a few: alongside the panic button incident, having most of our electrical goods stolen (a Powerbook laptop, several digital cameras, a mobile phone, iPod…) was one of the more minor incidents. Other stuff, I wouldn’t ever want to go into on this blog, but it makes you thankful for who you are and the fact that you come from a stable, supportive background. While appalled at some of the things human beings do to one another, and saddened at the things people do to children, I’ve felt myself growing as a person as a result of my ability to deal with some of these crises, and support Gill as she deals with them. But it doesn’t half make it difficult reading the newspapers, which make me alternately despair all over again at some peoples’ cruelty, and despair even more at the cluelessness of some newspapers’ leader and comment-writers, wittering on in the most judgemental terms on subjects they truly know nothing about. And me? Where have I been throughout all of this? Well, as I mentioned I’ve mainly been at work, travelling backwards and forwards to London. And my personal development hasn’t been solely related to fostering incidents: freelancing has taught me lessons which would have passed me by had I stayed closeted-up in my office. Most of all, I’ve learned to embrace the new, to constantly experiment and re-invent. Part of the problem with my previous long stretch at home was that I was never exposed to new influences, and so I became more and more stuck in the same groove, the same way of doing things. I don’t think that will ever happen to me again: I now know that, in order to stay alive, stay fresh, I need to seek out adventure and learning wherever I can find it. The only downside of this year of discovery has been that my photography career, which was really starting to blossom over 2007, has had to take a back seat. Although I’ve done some half-dozen weddings this year, and early in the year I was hired to cover some amazing events like the Creative Sheffield launch and the Vivienne Westwood exhibition VIP party, I haven’t had the time I’d like to edit photos, or to push my career forwards. Towards the end of the year, I’ve photographed a few private views in London galleries, but my rate of photography has gone right down, and as a result I’ve got a bit rusty (photography, like sport, is something you need to practice almost daily in order to stay on top of your game). I did manage to produce a wonderful little Working Nights photobook in June this year but my (slightly unexpected) BBC iPlayer career swept me off my feet so fast that, to date, I’ve only managed to hawk it round a few shops, and haven’t found time to send it out to all of the magazines, galleries and, indeed, friends who I had intended. My New Year’s resolution for 2009: get some books in the post! Since. One of the most frustrating situations for any online marketer is not getting credit for sales that take place in the companies’ brick-and-mortar stores when the initial lead was generated online. This often occurs when running a Pay-Per-Click (PPC) campaign which attracts customers to the companies’ website (where they can purchase the product online) but who still choose to purchase the product at the companies brick-and-mortar store. Here’s a trick on how to setup one of your Pay-Per-Click campaigns so you can get credit for the sale and receive the allocades of your coworkers you know you deserve! Setup one of your Pay-Per-Campaigns so the ads only display in a major city where your company has most of their brick-and-mortar stores. Example: If your company focuses on selling competitive priced jewelry, setup a PPC campaign to only display ads in New York (assuming that’s where a majority of your stores are located) and bid on keywords like “discount jewelry, jewelry distributor, diamond wholesaler”. Next, write all your ads to lead with the city abbreviation “NY” (an obvious abbreviation for anyone living in New York) and then include some of the keyword phrases that you are bidding on (eg. NY Diamond Wholesaler). Use the second line of the ad to explain what your company sells (eg. necklaces, bracelets, rings etc) and use the last line of the ad to “hook” your customer (eg. advertise free shipping and a coupon for 10-20% off any purchase). Keeping best practices in mind, create a specific landing page for this campaign. Include (and better yet bold) the keywords you are bidding on, pictures of your products, etc. Most importantly include a 10-20% coupon that can be used online upon checkout or printed out for in-store purchases. If you’re a PPC rockstar you’ll probably already realize that setting up a geographic targeted PPC campaign with targeted ads that include the city name and take customers to a custom landing pages will result in: 1. Higher clickthrough rates (don’t be surprised if you get close to 10%)! 2. Higher online conversions (who doesn’t like a good 10-20% discount on a product they are already interested in?) 3. Higher total sales (since you’ll get credit for offline sales generated online). Have you figured out how number 3 happens? The coupon code! By setting up your campaign this way, you’ll have customers print off and use the coupon in-store (in order to get the 10-20% discount)! Since, this coupon is only on your PPC landing page you’ll get credit for the sale! Six. I love that whenever I write London on this blog, SEO Smart Links auto-links it to one of my favourite little blog posts. London. Congratulations to Credit Union ONE for launching an enhanced website which provides members additional features and benefits. CU ONE approached Extractable to help design a website that would “provide exceptional value to CU ONE members by delivering outstanding products and services anytime, anywhere.” By having the website function as a 24 hour online member center (by empowering members to do more of their financial tasks online and by organizing information on the website more clearly) the website is poised to be a success! Some great CU ONE site features include: In the next month CUONE will be working to implement RSS feeds on their website and dynamically pull in rates into specific webpages in order to ensure their members have the latest rate information possibly available. If you live in Michigan (or surrounding states) and are looking for a stable financial institution that still feels “personal” please make sure to visit Credit Union ONE. When. When of the areas that I believe that is most often overlooked when “QAing” a website before it is launched is verifying that the sites analytic and search engine strategies are in place.. Extractable’s clients use their sites to accomplish a broad set of goals (Lead Generation, Online/Offline Revenues, Reach/Awareness, Customer Loyalty). One key to discovering which variables influence conversion of visitors is knowing whether or not visitors convert in 1 visit, 2 visits, 3 visits, etc. Whether filling out a lead form, purchasing an upgrade, or entering some product feedback, we typically see that the most valuable actions from visitors are on the 2nd+ plus visit. So why is it that most sites look the exact same each time a visitors comes back? The first time visitors see Amazon.com, the visitors can be impressed with the sites wide selection of products, the wealth of information about every product, and the ease of purchasing. But the most impressive aspect of Amazon is what happens on the 2nd visit, 3rd visit, 4th Visit, etc. The site keeps track of what you looked at (whether you made a purchase or not). The site makes personalized recommendations based on what you viewed and how many items you viewed. Sites like LinkedIn and Facebook are personalizing navigation and recommendations based on past navigation patterns. BannaRepublic is customizing product recommendations based on the products that you looked at most recently. With a lot of the sites that we view, the first visit is an introduction. The visitor is looking at high level product and organizational information – they are browsing around at wide breadth of content. The first time visitor is validating the site/product as a viable option. On the second visit, their navigation is much more focused. When a user comes back, they tend to be a little more focused in their clicks/searches. Knowing what content/products a customer has looked at makes a big impact on what they view on their second visit. Most sites should follow Amazon’s example. It doesn’t take a significant about of planning and programming to think about how to make that 2nd visit a little easier and ideally, get a better conversion rate. We’ve had great success with clients websites by simply placing quick links to previously viewed promotions on the homepage. I am cheap. No, I am not trying to ask my boss indirectly for a raise (although with gas prices and my long commute I wouldn’t mind one) its just that I have just been using the Internet since Al Gore invented it (jk) and am accustomed to getting cool services for free on the Internet - news, language translation tools, playing in a fantasy league,etc. I have even found some great FREE search engine optimization tools (that can be used as plug-ins with Firefox) that I would highly recommend: The tools above capture and display a lot of valuable information that you will need when optimizing your website for search engines - Google Page Rank, backlinks, internal/external links, Alexa ranking, cached site pages, IP address, whois info, robots file, sitemap, compete rank, keyword density, etc. The SEO Quake and Search Status tools can be used when viewing a particular website while SEO Book shows much of the same vital SEO information from search engine results pages. Happy optimizing! I think 12 frogs is onto something here with Why social software is good for introverts.[The Power of Many] H.[Radio Free Blogistan] Looks like his team forgot to register the domain: The Connecticut for Lieberman Party[Edgewise]”?[Edgewise] I was looking at the Haddock blogs aggregator and in their links gutter I came across a transcript of a presentation given at Notacon 3 (whatever that is) in April of this year by Jason Scott. You can listen to the audio if you prefer. I tend to like the Wikipedia idea, warts and all, but this talk is a pretty compelling look at its flaws. Here are a few choice excerpts that jumped out at me: What. and. and, also Wikipedia tends to be, at this point, the first hit for most proper and non-proper nouns. Putting in anything gives you the Wikipedia entry. In fact, if you have Trillian, Trillian has an automatic setting so that any word you have in there that matches on Wikipedia ends up as an underlined word. You click on it, and it tells you what the answer is. To someone who’s using instant messaging, they don’t know where this entry came from when they clicked on it, they also tend to be out of date because they index it across the Trillian … and so on. So as a result, you can’t say just go in and change it, because it’s actually using older and older indexes. That’s what I mean by the concern I have, the worry that I have, when I make these big points.[The Power of Many] K: If you know a developer - pass the word along.If you know a developer - pass the word along. -. Perhaps the vision of a universal single sign-on on the Web isn’t just a utopian pipedream after all?[The Power of Many] Suzanne Stefanac is writing a book on blogging called Dispatches from Blogistan (catchy title, eh?) for Peachpit / New Riders. Naturally, she’s been blogging the whole process and posting snippets of work in progress and the texts of interviews she’s conducted for the book. I know Suzanne from The Well, where I host the blog conference and where I’m known as <xian> and she’s known as <zorca>. A while back she interviewed me via email and she recently published the results on her book’s blog: Dispatches From Blogistan - interview with christian crumlish. In the interview we talk about blogging (of course) as well as social media, RSS, wikis, politics, media, authority, trust, online presence, the long tail, and other stuff I hope you’ll find interesting. I know I had fun doing it.[Radio Free Blogistan] Jim Goldstein was up in Alaska in the Arctic National Wildlife Refuge recently and brought back these photographs. He says, “A conservative friend asked me, ‘Is ANWR as really as ugly as they say it is? This alarmed me a great deal after having one of the best photo trips I’ve taken to date. The beauty of ANWR is almost unparalleled.”[wake up!] “You should stop blaming your parents for your quarrel with reality,” said Dr. Carnes, casually. He leaned back nimbly in his chair, hands behind his head, framed diplomas on the paneled wall behind him. I almost thought he was going to prop his feet up on the desk in front of him. My psychiatrist wasn’t much older than me - maybe thirty. “I’m not blaming my parents,” I said to the shrink. “I’m just telling you what happened.” “Well, go on, then. You say your mother gave you paregoric?” I studied the pastel Aztec pattern in the arm of my comfortably stuffed easy chair. Nice texture. “You know what paregoric is, right?” I asked, still looking down. “They stopped making paregoric in the late fifties,” Dr. Carnes answered correctly. “It was a medicine made from camphor and alcohol with a small amount of morphine. They gave it to children for cough medicine.” “Very good,” I said, looking at him. “Well, my mother says she used to rub it on my gums when my teeth were coming in. When I was a baby. I have this memory of lying in my crib in my bedroom. There were these cartoon pictures on my wall. Eight pictures – two on each wall. They were Snow White and the Seven Dwarfs. You know, Happy, Sleepy, Doc…” “Yes, I’m familiar with the dwarves,” said the shrink, a bit impatiently, I thought. “But you were very young. You actually remember this?” Ignoring his question, I continued, “So I’m lying there, and I look at the picture of Grumpy, and he seems to be frowning at me. It was scary. His eyebrows moved up and down and he blinked. Then I looked at Happy, and his red grin got wide and crazy and his nose started stretching and bending sideways. His big eyes were crossed and his tongue stuck out! It scared me so I looked away and closed my eyes. Then I could see stars glittering, and a big, bright golden crescent moon. In slow motion, a cow floated up into the black, starry sky and sailed over the moon!” “Were you traumatized?” said the doctor, stifling a laugh. “I think so. But I felt so good I didn’t care." “But, Bill,” the shrink frowned. Relying momentarily on his neck muscles to support his head, he used both hands to brush back his hair in a motion that ended with his hands clasped again behind his head. “You were too young to even know what paregoric was. How…” “No, listen,” I said. “Years later, my mother found those pictures of Snow White and the Seven Dwarfs when she was cleaning out the attic. She said, ‘Do you remember these?’ and I said, ‘Yeah’ and then she told me how, when I was a baby, teething, I would cry and cry, because teething hurts, so she said she rubbed paregoric on my gums. After that, she said, I stopped crying and just looked up at those pictures until I fell asleep.” “Did you use any other drugs when you were a kid?” asked Dr. Carnes. “I had bad hay fever.” “Allergic to pollen?” the shrink clarified unnecessarily. “Yeah,” I said. “It made my eyes itch I sneezed a lot. I had to take antihistamine for years. Sometimes the antihistamine allowed me to dream these amazing Technicolor dreams if I took it at night.” “I’ve dreamed in color,” said the shrink. “Some people say we only dream in black and white, but I’ve dreamed in color.” Whoop-de-doo, I thought. Big deal. I never doubted people dreamed in color. “Sometimes,” I continued, “When the pollen was extra bad, I had to stay indoors. While other guys were playing baseball, I was inside drawing pictures and writing stories. Our kitchen had a linoleum floor with all kinds of squiggly designs in it, and if I stared at those squiggles I saw faces and other things.” “People do the same thing looking up at clouds,” said the doctor. “I’ve seen big shapes in the clouds,” I said. “But there is something more … intimate, when faces emerge from the floor tiles. I also saw them, sometimes, in the towels hanging in the bathroom. In the little threads.” “Is that why you are so interested in Richard Shaver’s art?” asked Dr. Carnes. Very astute. I should explain who Richard Shaver was. Primarily a writer of science fiction, he also created some unusual art. He split rocks open and saw patterns in the grain, then used paint and ink to enhance the images so that other people could see them. He called these "rock books" and said that an ancient civilization had created them. Shaver was, by all accounts, a strange man. You can read about him on the Internet, but I’ll give you a little background. A man named Hugo Gernsback created the first science fiction magazine, Amazing Stories, in 1926. Amazing Stories is the magazine that Forrest J. Ackerman famously says, “jumped into his hands” when he was a boy and inspired him to become a literary agent and later the editor of Famous Monsters magazine. Around 1940, Richard Shaver sent a story to the magazine about a race of evil mutants, called Dero, who lived in underground caverns and sometimes captured humans to torture and eat. According to Shaver, aliens from another planet had abandoned these subterranean creatures on Earth, back in ancient times, and centuries of inbreeding underground had made them insane and sadistic. Shaver also claimed that the Dero were using some kind of energy beam to send disturbing voices into his own mind. He called this mental harassment "tamper." The story was all the more remarkable because Richard Shaver claimed that it was entirely true! It was never clear whether Ray Palmer, the magazine’s editor, believed that Richard Shaver was serious or not, but Amazing Stories continued publishing Shaver stories because it increased their sales and thousands of letters poured in. Some of the letter writers claimed that they, too, heard strange voices in their heads. This annoyed the more serious science fictions fans, who looked upon the "Shaver Mystery" as a ridiculous hoax. Years later, in an interview, Palmer admitted that Shaver, like me, had spent some time in a mental institution[Telegraph] David Hinojosa has got a project called Stock Artist that offers a simulation (for now) of a rationalize the art market. I’m not sure I fully understand the concept, but this appears to be the nut of it: The central nucleus of Stockartist is the “transformed art piece’s concept.” This concept consists in dividing the value of one work, or a group of them into little pieces called “stock-art.” The stock-arts have two characteristics: they represent one part of the value of the “transformed art piece” and they are themselves art works. In other words, the stock-arts are at the same time art works and an instrument of investment that besides of representing their own value, they represent other’s. The stock-arts share some common physical characteristics as: maximum weight, maximum size, security codes, etc, and they contain unique characteristics imposed by their creator.[The Power of Many].
http://www.antiweb.net/feeds/
crawl-002
refinedweb
10,924
69.11
@apollo/react-hoc API reference Installation npm install @apollo/react-hoc graphql(query, [config])(component) import { graphql } from '@apollo/react-hoc'; The graphql() function is the most important thing exported by the @apollo/react-hoc package. With this function you can create higher-order components that can execute queries and update reactively based on the data in your Apollo store. The graphql() function returns a function which will “enhance” any component with reactive GraphQL capabilities. This follows the React higher-order component pattern which is also used by react-redux’s connect function. The graphql() function may be used like this: function TodoApp({ data: { todos } }) { return ( <ul> {todos.map(({ id, text }) => ( <li key={id}>{text}</li> ))} </ul> ); } export default graphql(gql` query TodoAppQuery { todos { id text } } `)(TodoApp); You may also define an intermediate function and hook up your component with the graphql() function like this: // Create our enhancer function. const withTodoAppQuery = graphql(gql`query { ... }`); // Enhance our component. const TodoAppWithData = withTodoAppQuery(TodoApp); // Export the enhanced component. export default TodoAppWithData; The graphql() function will only be able to provide access to your GraphQL data if there is a <ApolloProvider/> component higher up in your tree to provide an ApolloClient instance that will be used to fetch your data. The behavior of your component enhanced with the graphql() function will be different depending on if your GraphQL operation is a query, a mutation, or a subscription. Go to the appropriate API documentation for more information about the functionality and available options for each type. Before we look into the specific behaviors of each operation, let us look at the config object. The config object is the second argument you pass into the graphql() function, after your GraphQL document. The config is optional and allows you to add some custom behavior to your higher order component. export default graphql( gql`{ ... }`, config, // <- The `config` object. )(MyComponent); Lets go through all of the properties that may live on your config object. config.options config.options is an object or a function that allows you to define the specific behavior your component should use in handling your GraphQL data. The specific options available for configuration depend on the operation you pass as the first argument to graphql(). There are options specific to queries and mutations. You can define config.options as a plain object, or you can compute your options from a function that takes the component’s props as an argument. Example: export default graphql(gql`{ ... }`, { options: { // Options go here. }, })(MyComponent); export default graphql(gql`{ ... }`, { options: props => ({ // Options are computed from `props` here. }), })(MyComponent); config.props The config.props property allows you to define a map function that takes the props (and optionally lastProps) added by the graphql() function ( props.data for queries and props.mutate for mutations) and allows you to compute a new props (and optionally lastProps) object that will be provided to the component that graphql() is wrapping. The function you define behaves almost exactly like mapProps from Recompose providing the same benefits without the need for another library. config.props is most useful when you want to abstract away complex functions calls into a simple prop that you can pass down to your component. Another benefit of config.props is that it also allows you to decouple your pure UI components from your GraphQL and Apollo concerns. You can write your pure UI components in one file and then keep the logic required for them to interact with the store in a completely different place in your project. You can accomplish this by your pure UI components only asking for the props needed to render and config.props can contain the logic to provide exactly the props your pure component needs from the data provided by your GraphQL API. Example: This example uses props.data.fetchMore. export default graphql(gql`{ ... }`, { props: ({ data: { fetchMore } }) => ({ onLoadMore: () => { fetchMore({ ... }); }, }), })(MyComponent); function MyComponent({ onLoadMore }) { return ( <button onClick={onLoadMore}> Load More! </button> ); } To access props that are not added by the graphql() function, use the ownProps keyword. For example: export default graphql(gql`{ ... }`, { props: ({ data: { liveImage }, ownProps: { loadingImage } }) => ({ image: liveImage || loadingImage, }), })(MyComponent); To access lastProps, use the second argument of config.props. For example: export default graphql(gql`{ ... }`, { props: ({ data: { liveImage } }, lastProps) => ({ image: liveImage, lastImage: lastProps.data.liveImage, }), })(MyComponent); config.skip If config.skip is true then all of the React Apollo code will be skipped entirely. It will be as if the graphql() function were a simple identity function. Your component will behave as if the graphql() function were not there at all. Instead of passing a boolean to config.skip, you may also pass a function to config.skip. The function will take your components props and should return a boolean. If the boolean returns true then the skip behavior will go into effect. config.skip is especially useful if you want to use a different query based on some prop. You can see this in an example below. Example: export default graphql(gql`{ ... }`, { skip: props => !!props.skip, })(MyComponent); The following example uses the compose function to use multiple graphql() enhancers at once. export default compose( graphql(gql`query MyQuery1 { ... }`, { skip: props => !props.useQuery1 }), graphql(gql`query MyQuery2 { ... }`, { skip: props => props.useQuery1 }), )(MyComponent); function MyComponent({ data }) { // The data may be from `MyQuery1` or `MyQuery2` depending on the value // of the prop `useQuery1`. console.log(data); } config.name This property allows you to configure the name of the prop that gets passed down to your component. By default if the GraphQL document you pass into graphql() is a query then your prop will be named data. If you pass a mutation then your prop will be named mutate. While appropriate these default names collide when you are trying to use multiple queries or mutations with the same component. To avoid collisions you may use config.name to provide the prop from each query or mutation HOC a new name. Example: This example uses the compose function to use multiple graphql() HOCs together. export default compose( graphql(gql`mutation (...) { ... }`, { name: 'createTodo' }), graphql(gql`mutation (...) { ... }`, { name: 'updateTodo' }), graphql(gql`mutation (...) { ... }`, { name: 'deleteTodo' }), )(MyComponent); function MyComponent(props) { // Instead of the default prop name, `mutate`, // we have three different prop names. console.log(props.createTodo); console.log(props.updateTodo); console.log(props.deleteTodo); return null; } config.withRef By setting config.withRef to true you will be able to get the instance of your wrapped component from your higher-order GraphQL component using a getWrappedInstance method available on the instance of your higher-order GraphQL component. You may want to set this to true when you want to call functions or get access to properties that are defined on your wrapped component’s class instance. Below you can see an example of this behavior. Example: This example uses the React ref feature. class MyComponent extends Component { saySomething() { console.log('Hello, world!'); } render() { // ... } } const MyGraphQLComponent = graphql(gql`{ ... }`, { withRef: true })( MyComponent, ); class MyContainerComponent extends Component { render() { return ( <MyGraphQLComponent ref={component => { const wrappedInstance = component.getWrappedInstance(); assert(wrappedInstance instanceof MyComponent); // We can call methods on the component class instance. wrappedInstance.saySomething(); }} /> ); } } config.alias By default the display name for React Apollo components is Apollo(${WrappedComponent.displayName}). This is a pattern used by most React libraries that make use of higher order components. However, it may get a little confusing when you are using more than one higher order component and you look at the React Devtools. To configure the name of your higher order component wrapper, you may use the config.alias property. So for example, if you set config.alias to 'withCurrentUser' your wrapper component display name would be withCurrentUser(${WrappedComponent.displayName}) instead of Apollo(${WrappedComponent.displayName}). Example: This example uses the compose function to use multiple graphql() HOCs together. export default compose( graphql(gql`{ ... }`, { alias: 'withCurrentUser' }), graphql(gql`{ ... }`, { alias: 'withList' }), )(MyComponent); graphql() options for queries props.data The higher-order component created when using graphql() will feed a data prop into your component. Like so: render() { const { data } = this.props; // <- The `data` prop. } The data prop contains the data fetched from your query in addition to some other useful information and functions to control the lifecycle of your GraphQL-connected component. So for example, if we had a query that looked like: { viewer { name } todos { text } } Your data prop would contain that data: render() { const { data } = this.props; console.log(data.viewer); // <- The data returned by your query for `viewer`. console.log(data.todos); // <- The data returned by your query for `todos`. } The data prop has some other useful properties which can be accessed directly from data. For example, data.loading or data.error. These properties are documented below. Make sure to always check data.loading and data.error in your components before rendering. Properties like data.todos which contain your app’s data may be undefined while your component is performing its initial fetch. Checking data.loading and data.error helps you avoid any issues with undefined data. Such checks may look like: render() { const { data: { loading, error, todos } } = this.props; if (loading) { return <p>Loading...</p>; } if (error) { return <p>Error!</p>; } return ( <ul> {todos.map(({ id, text }) => ( <li key={id}>{text}</li> ))} </ul> ); } data.loading A boolean representing whether or not a query request is currently in flight for this component. This means that a query request has been sent using your network interface, and we have not yet gotten a response back. Use this property to render a loading component. However, just because data.loading is true it does not mean that you won’t have data. For instance, if you already have data.todos, but you want to get the latest todos from your API data.loading might be true, but you will still have the todos from your previous request. There are multiple different network states that your query may be in. If you want to see what the network state of your component is in more detail then refer to data.networkStatus. Example: function MyComponent({ data: { loading } }) { if (loading) { return <div>Loading...</div>; } else { // ... } } export default graphql(gql`query { ... }`)(MyComponent); data.error If an error occurred then this property will be an instance of ApolloError. If you do not handle this error you will get a warning in your console that says something like: "Unhandled (in react-apollo) Error: ...". Example: function MyComponent({ data: { error } }) { if (error) { return <div>Error!</div>; } else { // ... } } export default graphql(gql`query { ... }`)(MyComponent); data.networkStatus data.networkStatus is useful if you want to display a different loading indicator (or no indicator at all) depending on your network status as it provides a more detailed view into the state of a network request on your component than data.loading does. data.networkStatus is an enum with different number values between 1 and 8. These number values each represent a different network state. loading: The query has never been run before and the request is now pending. A query will still have this network status even if a result was returned from the cache, but a query was dispatched anyway. setVariables: If a query’s variables change and a network request was fired then the network status will be setVariablesuntil the result of that query comes back. React users will see this when options.variableschanges on their queries. fetchMore: Indicates that fetchMorewas called on this query and that the network request created is currently in flight. refetch: It means that refetchwas called on a query and the refetch request is currently in flight. - Unused. poll: Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to pollevery 10 seconds whenever a poll request has been sent but not resolved. ready: No request is in flight for this query, and no errors happened. Everything is OK. error: No request is in flight for this query, but one or more errors were detected. If the network status is less then 7 then it is equivalent to data.loading being true. In fact you could replace all of your data.loading checks with data.networkStatus < 7 and you would not see a difference. It is recommended that you use data.loading, however. Example: function MyComponent({ data: { networkStatus } }) { if (networkStatus === 6) { return <div>Polling!</div>; } else if (networkStatus < 7) { return <div>Loading...</div>; } else { // ... } } export default graphql(gql`query { ... }`)(MyComponent); data.variables The variables that Apollo used to fetch data from your GraphQL endpoint. This property is helpful if you want to render some information based on the variables that were used to make a request against your server. Example: function MyComponent({ data: { variables } }) { return ( <div> Query executed with the following variables: <code>{JSON.stringify(variables)}</code> </div> ); } export default graphql(gql`query { ... }`)(MyComponent); data.refetch(variables) Forces your component to refetch the query you defined in the graphql() function. This method is helpful when you want to reload the data in your component, or retry a fetch after an error. data.refetch returns a promise that resolves with the new data fetched from your API once the query has finished executing. The promise will reject if the query failed. The data.refetch function takes a single variables object argument. The variables argument will replace variables used with either the query option or the query from your graphql() HOC (depending on whether or not you specified a query) option to refetch the query you defined in the graphql() function. Example: function MyComponent({ data: { refetch } }) { return <button onClick={() => refetch()}>Reload</button>; } export default graphql(gql`query { ... }`)(MyComponent); data.fetchMore(options) The data.fetchMore function allows you to do pagination with your query component. To learn more about pagination with data.fetchMore, be sure to read the pagination recipe which contains helpful illustrations on how you can do pagination with React Apollo. data.fetchMore returns a promise that resolves once the query executed to fetch more data has resolved. The data.fetchMore function takes a single options object argument. The options argument may take the following properties: [query]: This is an optional GraphQL document created with the gqlGraphQL tag. If you specify a querythen that query will be fetched when you call data.fetchMore. If you do not specify a query, then the query from your graphql()HOC will be used. [variables]: The optional variables you may provide that will be used with either the queryoption or the query from your graphql()HOC (depending on whether or not you specified a query). updateQuery(previousResult, { fetchMoreResult, variables }): This is the required function you define that will actually update your paginated list. The first argument, previousResult, will be the previous data returned by the query you defined in your graphql()function. The second argument is an object with two properties, fetchMoreResultand variables. fetchMoreResultis the data returned by the new fetch that used the queryand variablesoptions from data.fetchMore. variablesare the variables that were used when fetching more data. Using these arguments you should return a new data object with the same shape as the GraphQL query you defined in your graphql()function. See an example of this below, and also make sure to read the pagination recipe which has a full example. Example: data.fetchMore({ updateQuery: (previousResult, { fetchMoreResult, variables }) => { return { ...previousResult, // Add the new feed data to the end of the old feed data. feed: [...previousResult.feed, ...fetchMoreResult.feed], }; }, }); data.subscribeToMore(options) This function will set up a subscription, triggering updates whenever the server sends a subscription publication. This requires subscriptions to be set up on the server to properly work. Check out the subscriptions guide and the subscriptions-transport-ws and graphql-subscriptions for more information on getting this set up. This function returns an unsubscribe function handler which can be used to unsubscribe later. A common practice is to wrap the getDerivedStateFromProps and perform the subscription after the original query has completed. To ensure the subscription isn't created multiple times, you can add it to component state. See the example for more details. [document]: Document is a required property that accepts a GraphQL subscription created with graphql-tag’s gqltemplate string tag. It should contain a single GraphQL subscription operation with the data that will be returned. [variables]: The optional variables you may provide that will be used with the documentoption. [updateQuery]: An optional function that runs every time the server sends an update. This modifies the results of the HOC query. The first argument, previousResult, will be the previous data returned by the query you defined in your graphql()function. The second argument is an object with two properties. subscriptionDatais result of the subscription. variablesis the variables object used with the subscription query. Using these arguments you should return a new data object with the same shape as the GraphQL query you defined in your graphql()function. This is similar to the fetchMorecallback. [onError]: An optional error callback. In order to update the query's store with the result of the subscription, you must specify either the updateQuery option in reducer option in your graphql() function. Example: class SubscriptionComponent extends Component { state = { subscriptionParam: null, unsubscribe: null, }; static getDerivedStateFromProps(nextProps, prevState) { if (!nextProps.data.loading) { // Check for existing subscription if (prevState.unsubscribe) { // Only unsubscribe/update state if subscription variable has changed if (prevState.subscriptionParam === nextProps.subscriptionParam) { return null; } prevState.unsubscribe(); } return { // Subscribe unsubscribe: nextProps.data.subscribeToMore({ document: gql`subscription {...}`, variables: { param: nextProps.subscriptionParam, }, updateQuery: (previousResult, { subscriptionData, variables }) => { // Perform updates on previousResult with subscriptionData return updatedResult; }, }), // Store subscriptionParam in state for next update subscriptionParam: nextProps.subscriptionParam, }; } return null; } render() { ... } } data.startPolling(interval) This function will set up an interval and send a fetch request every time that interval ellapses. The function takes only one integer argument which allows you to configure how often you want your query to be executed in milliseconds. In other words, the interval argument represents the milliseconds between polls. Polling is a good way to keep the data in your UI fresh. By refetching your data every 5,000 milliseconds (or 5 seconds, for example) you may effectively emulate realtime data without needing to build up a realtime backend. If you call data.startPolling when your query is already polling then the current polling process will be cancelled and a new process will be started with the interval you specified. You may also use options.pollInterval to start polling immediately after your component mounts. It is recommend that you use options.pollInterval if you don’t need to arbitrarily start and stop polling. If you set your interval to 0 then that means no polling instead of executing a request every JavaScript event loop tick. Example: class MyComponent extends Component { componentDidMount() { // In this specific case you may want to use `options.pollInterval` instead. this.props.data.startPolling(1000); } render() { // ... } } export default graphql(gql`query { ... }`)(MyComponent); data.stopPolling() By calling this function you will stop any current polling process. Your query will not start polling again until you call data.startPolling. Example: class MyComponent extends Component { render() { return ( <div> <button onClick={() => { this.props.data.startPolling(1000); }} > Start Polling </button> <button onClick={() => { this.props.data.stopPolling(); }} > Stop Polling </button> </div> ); } } export default graphql(gql`query { ... }`)(MyComponent); data.updateQuery(updaterFn) This function allows you to update the data for your query outside of the context of any mutation, subscription, or fetch. This function only takes a single argument which will be another function. The argument function has the following signature: (previousResult, { variables }) => nextResult The first argument will be the data for your query that currently exists in the store, and you are expected to return a new data object with the same shape. That new data object will be written to the store and any components tracking that data will be updated reactively. The second argument is an object with a single property, variables. The variables property allows you to see what variables were used when reading the previousResult from the store. This method will not update anything on the server. It will only update data in your client cache and if you reload your JavaScript environment then your update will disappear. Example: data.updateQuery(previousResult => ({ ...previousResult, count: previousResult.count + 1, })); query. To see what other options are available for different operations, see the generic documentation for config.options. Example: export default graphql(gql`{ ... }`, { options: { // Options go here. }, })(MyComponent); export default graphql(gql`{ ... }`, { options: props => ({ // Options are computed from `props` here. }), })(MyComponent); options.variables The variables that will be used when executing the query operation. These variables should correspond with the variables that your query definition accepts. If you define config.options as a function then you may compute your variables from your props. Example: export default graphql( gql` query ($width: Int!, $height: Int!) { ... } `, { options: props => ({ variables: { width: props.size, height: props.size, }, }), }, )(MyComponent); options.fetchPolicy The fetch policy is an option which allows you to specify how you want your component to interact with the Apollo data cache. By default your component will try to read from the cache first, and if the full data for your query is in the cache then Apollo simply returns the data from the cache. If the full data for your query is not in the cache then Apollo will execute your request using your network interface. By changing this option you can change this behavior. Valid fetchPolicy values are: cache-first: This is the default value where we always try reading data from your cache first. If all the data needed to fulfill your query is in the cache then that data will be returned. Apollo will only fetch from the network if a cached result is not available. This fetch policy aims to minimize the number of network requests sent when rendering your component. cache-and-network: This fetch policy will have Apollo first trying to read data from your cache. If all the data needed to fulfill your query is in the cache then that data will be returned. However, regardless of whether or not the full data is in your cache this fetchPolicywill always execute query with the network interface unlike cache-firstwhich will only execute your query if the query data is not in your cache. This fetch policy optimizes for users getting a quick response while also trying to keep cached data consistent with your server data at the cost of extra network requests. network-only: This fetch policy will never return you initial data from the cache. Instead it will always make a request using your network interface to the server. This fetch policy optimizes for data consistency with the server, but at the cost of an instant response to the user when one is available. cache-only: This fetch policy will never execute a query using your network interface. Instead it will always try reading from the cache. If the data for your query does not exist in the cache then an error will be thrown. This fetch policy allows you to only interact with data in your local client cache without making any network requests which keeps your component fast, but means your local data might not be consistent with what is on the server. If you are interested in only interacting with data in your Apollo Client cache also be sure to look at the readQuery()and readFragment()methods available to you on your ApolloClientinstance. no-cache: This fetch policy will never return your initial data from the cache. Instead it will always make a request using your network interface to the server. Unlike the network-onlypolicy, it also will not write any data to the cache after the query completes. Example: export default graphql(gql`query { ... }`, { options: { fetchPolicy: 'cache-and-network' }, })(MyComponent); options.errorPolicy The error policy is an option which allows you to specify how you want your component to handle errors that can happen when fetching data from GraphQL. There are two types of errors that can happen during your request; a runtime error on the client or server which results in no data, or some GraphQL errors which may be delivered alongside actual data. In order to control how your UI interacts with these errors, you can use the error policy to tell Apollo when you want to know about GraphQL Errors or not! Valid errorPolicy values are: none: This is the default value where we treat GraphQL errors as runtime errors. Apollo will discard any data that came back with the request and render your component with an errorprop. ignore: Much like none, this causes Apollo to ignore any data from your server, but it also won't update your UI aside from setting the loading state back to false. all: Selecting all means you want to be notified any time there are any GraphQL errors. It will render your component with any data from the request and any errors with their information. It is particularly helpful for server side rendering so your UI always shows something Example: export default graphql(gql`query { ... }`, { options: { errorPolicy: 'all' }, })(MyComponent); options.pollInterval The interval in milliseconds at which you want to start polling. Whenever that number of milliseconds elapses your query will be executed using the network interface and another execution will be scheduled using the configured number of milliseconds. This option will start polling your query immediately when the component mounts. If you want to start and stop polling dynamically then you may use data.startPolling and data.stopPolling. If you set options.pollInterval to 0 then that means no polling instead of executing a request every JavaScript event loop tick. Example: export default graphql(gql`query { ... }`, { options: { pollInterval: 5000 }, })(MyComponent); options.notifyOnNetworkStatusChange Whether or not updates to the network status or network error should trigger re-rendering of your component. The default value is false. Example: export default graphql(gql`query { ... }`, { options: { notifyOnNetworkStatusChange: true }, })(MyComponent); options.context With the flexiblity and power of Apollo Link being part of Apollo Client, you may want to send information from your operation straight to a link in your network chain! This can be used to do things like set headers on HTTP requests from props, control which endpoint you send a query to, and so much more depending on what links your app is using. Everything under the context object gets passed directly to your network chain. For more information about using context, check out the docs on context with links partialRefetch If true, perform a query refetch if the query result is marked as being partial, and the returned data is reset to an empty Object by the Apollo Client QueryManager (due to a cache miss). The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases. Example: export default graphql(gql`query { ... }`, { options: { partialRefetch: true }, })(MyComponent); graphql() options for mutations props.mutate The higher order component created when you pass a mutation to graphql() will provide your component with a single prop named mutate. Unlike the data prop which you get when you pass a query to graphql(), mutate is a function. The mutate function will actually execute your mutation using the network interface therefore mutating your data. The mutate function will also then update your cache in ways you define. To learn more about how mutations work, be sure to check out the mutations usage documentation. The mutate function accepts the same options that config.options for mutations accepts, so make sure to read through the documentation for that to know what you can pass into the mutate function. The reason the mutate function accepts the same options is that it will use the options from config.options by default. When you pass an object into the mutate function you are just overriding what is already in config.options. Example: function MyComponent({ mutate }) { return ( <button onClick={() => { mutate({ variables: { foo: 42 }, }); }} > Mutate </button> ); } export default graphql(gql`mutation { ... }`)(MyComponent); mutation. To see what other options are available for different operations, see the generic documentation for config.options. The properties accepted in this options object may also be accepted by the props.mutate function. Any options passed into the mutate function will take precedence over the options defined in the config object. Example: export default graphql(gql`mutation { ... }`, { options: { // Options go here. }, })(MyComponent); export default graphql(gql`mutation { ... }`, { options: props => ({ // Options are computed from `props` here. }), })(MyComponent); function MyComponent({ mutate }) { return ( <button onClick={() => { mutate({ // Options are component from `props` and component state here. }); }} > Mutate </button> ); } export default graphql(gql`mutation { ... }`)(MyComponent); options.variables The variables which will be used to execute the mutation operation. These variables should correspond to the variables that your mutation definition accepts. If you define config.options as a function, or you pass variables into the props.mutate function then you may compute your variables from props and component state. Example: export default graphql( gql` mutation ($foo: String!, $bar: String!) { ... } `, { options: props => ({ variables: { foo: props.foo, bar: props.bar, }, }), }, )(MyComponent); options.optimisticResponse Often when you mutate data it is fairly easy to predict what the response of the mutation will be before asking your server. The optimistic response option allows you to make your mutations feel faster by simulating the result of your mutation in your UI before the mutation actually finishes. To learn more about the benefits of optimistic data and how to use it be sure to read the recipe on Optimistic UI. This optimistic response will be used with options.update and options.updateQueries to apply an update to your cache which will be rolled back before applying the update from the actual response. Example: function MyComponent({ newText, mutate }) { return ( <button onClick={() => { mutate({ variables: { text: newText, }, // The optimistic response has all of the fields that are included in // the GraphQL mutation document below. optimisticResponse: { createTodo: { id: -1, // A temporary id. The server decides the real id. text: newText, completed: false, }, }, }); }} > Add Todo </button> ); } export default graphql(gql` mutation($text: String!) { createTodo(text: $text) { id text completed } } `)(MyComponent); options.update function. options.update takes two arguments. The first is an instance of a DataProxy object which has some methods which will allow you to interact with the data in your store. The second is the response from your mutation - either the optimistic response, or the actual response returned by your server (see the mutation result described in the mutation render prop section for more details). In order to change the data in your store call methods on your DataProxy instance like writeQuery and writeFragment. This will update your cache and reactively re-render any of your GraphQL components which are querying affected data. To read the data from the store that you are changing, make sure to use methods on your DataProxy like readQuery and readFragment. For more information on updating your cache after a mutation with the options.update function make sure to read the Apollo Client technical documentation on the subject. Example: const query = gql`{ todos { ... } }`; export default graphql( gql` mutation ($text: String!) { createTodo(text: $text) { ... } } `, { options: { update: (proxy, { data: { createTodo } }) => { const data = proxy.readQuery({ query }); data.todos.push(createTodo); proxy.writeQuery({ query, data }); }, }, }, )(MyComponent); options.refetchQueries Sometimes when you make a mutation you also want to update the data in your queries so that your users may see an up-to-date user interface. There are more fine-grained ways to update the data in your cache which include options.updateQueries, and options.update. However, you can update the data in your cache more reliably at the cost of efficiency by using options.refetchQueries. options.refetchQueries will execute one or more queries using your network interface and will then normalize the results of those queries into your cache. Allowing you to potentially refetch queries you had fetched before, or fetch brand new queries. options.refetchQueries is either an array of strings or objects, or a function which takes the result of the mutation and returns an array of strings or objects. If options.refetchQueries is an array of strings then Apollo Client will look for any queries with the same names as the provided strings and will refetch those queries with their current variables. So for example if you have a GraphQL query component with a query named query Comments { ... }), and you pass an array of strings containing options.refetchQueries then the Comments query will be re-executed and when it resolves the latest data will be reflected in your UI. If options.refetchQueries is an array of objects then the objects must have two properties: query: Query is a required property that accepts a GraphQL query created with graphql-tag’s gqltemplate string tag. It should contain a single GraphQL query operation that will be executed once the mutation has completed. [variables]: Is an optional object of variables that is required when queryaccepts some variables. If an array of objects with this shape is specified then Apollo Client will refetch these queries with their variables. Example: export default graphql(gql`mutation { ... }`, { options: { refetchQueries: ['CommentList', 'PostList'], }, })(MyComponent); import { COMMENT_LIST_QUERY } from '../components/CommentList'; export default graphql(gql`mutation { ... }`, { options: props => ({ refetchQueries: [ { query: COMMENT_LIST_QUERY, }, { query: gql` query($id: ID!) { post(id: $id) { commentCount } } `, variables: { id: props.postID, }, }, ], }), })(MyComponent); export default graphql(gql`mutation { ... }`, { options: { refetchQueries: mutationResult => ['CommentList', 'PostList'], }, })(MyComponent); Please note that refetched queries are handled asynchronously, and by default are not necessarily completed before the mutation has completed. If you want to make sure refetched queries are completed before the mutation is considered done (or resolved), set options.awaitRefetchQueries to true. options.awaitRefetchQueries Queries refetched using options.refetchQueries are handled asynchronously, which means by default they are not necessarily completed before the mutation has completed. Setting options.awaitRefetchQueries to true will make sure refetched queries are completed before the mutation is considered done (or resolved). options.awaitRefetchQueries is false by default. options.updateQueries Note: We recommend using options.update instead of updateQueries. updateQueries will be removed in the next version of Apollo ClientQueries function. options.updateQueries takes an object where query names are the keys and reducer functions are the values. If you are familiar with Redux, defining your options.updateQueries reducers is very similar to defining your Redux reducers. The object looks something like this: Make sure that the key of your options.updateQueries object corresponds to an actual query that you have made somewhere else in your app. The query name will be the name you put after specifying the query operation type. So for example in the following query: query Comments { entry(id: 5) { comments { ... } } } The query name would be Comments. If you have not executed a GraphQL query with the name of Comments before somewhere in your application, then the reducer function will never be run by Apollo and the key/value pair in options.updateQueries will be ignored. The first argument to the function you provide as the value for your object will be the previous data for your query. So if your key is Comments then the first argument will be the last data object that was returned for your Comments query, or the current object that is being rendered by any component using the The second argument to your function value will be an object with three properties: mutationResult: The mutationResultproperty will represent the result of your mutation after hitting the server. If you provided an options.optimisticResponsethen mutationResultmay be that object. queryVariables: The last set of variables that the query was executed with. This is helpful because when you specify the query name it will only update the data in the store for your current variable set. queryName: This is the name of the query you are updating. It is the same name as the key you provided to options.updateQueries. The return value of your options.updateQueries functions must have the same shape as your first previousData argument. However, you must not mutate the previousData object. Instead you must create a new object with your changes. Just like in a Redux reducer. Example: export default graphql( gql` mutation ($text: String!) { submitComment(text: $text) { ... } } `, { options: { updateQueries: { Comments: (previousData, { mutationResult }) => { const newComment = mutationResult.data.submitComment; // Note how we return a new copy of `previousData` instead of mutating // it. This is just like a Redux reducer! return { ...previousData, entry: { ...previousData.entry, comments: [newComment, ...previousData.entry.comments], }, }; }, }, }, }, )(MyComponent); withApollo(component) import { withApollo } from '@apollo/react-hoc'; A simple enhancer which provides direct access to your ApolloClient instance. This is useful if you want to do custom logic with Apollo. Such as calling one-off queries. By calling this function with the component you want to enhance, withApollo() will create a new component which passes in an instance of ApolloClient as a client prop. If you are wondering when to use withApollo() and when to use graphql() the answer is that most of the time you will want to use graphql(). graphql() provides many of the advanced features you need to work with your GraphQL data. You should only use withApollo() if you want the GraphQL client without any of the other features. This will only be able to provide access to your client if there is an <ApolloProvider/> component higher up in your tree to actually provide the client. Example: function MyComponent({ client }) { console.log(client); } export default withApollo(MyComponent);
https://www.apollographql.com/docs/react/api/react-hoc/
CC-MAIN-2020-24
refinedweb
6,188
57.98
I can't add a Web Reference Discussion in 'ASP .Net Web Services' started by Alexander Walk shared assembly in the add referencebabu dhayal via .NET 247, Aug 5, 2004, in forum: ASP .Net - Replies: - 2 - Views: - 6,363 - Nelson Xu - Aug 17, 2004 I can't add a Web ReferenceAlexander Walker, Feb 2, 2006, in forum: ASP .Net - Replies: - 4 - Views: - 3,368 - tremmorkeep - Dec 15, 2007 Can I add web reference to my VB.NET project at run time?Annie, Feb 4, 2004, in forum: ASP .Net Web Services - Replies: - 1 - Views: - 598 - Jan Tielens - Feb 4, 2004 why i can't add web referencexjbsky, Aug 28, 2004, in forum: ASP .Net Web Services - Replies: - 0 - Views: - 144 - xjbsky - Aug 28, 2004 procedure to add web reference which will not create new namespace just add class in existing namespDeep Mehta via .NET 247, May 28, 2005, in forum: ASP .Net Web Services - Replies: - 2 - Views: - 522 - Dave A - May 31, 2005
http://www.thecodingforums.com/threads/i-cant-add-a-web-reference.785810/
CC-MAIN-2015-18
refinedweb
163
82.44
PROBLEM LINK Contest Author: Adithi Narayan Tester: Hareesh Editorialist: Adithi Narayan DIFFICULTY Easy PREREQUISITES BFS PROBLEM Given a grid where each cell holds a direction [T,L,D,R], find the path from top left to bottom right given that you can either move in the direction specified in the cell or pay a penalty to move in some other direction. (Note that for a cell in the grid the change of direction can only be done once.) EXPLANATION We have to reach (m - 1, n - 1) from (0, 0) with a path that minimizes the penalty paid. For each cell, you have 2 choices: - The cell that can be reached by following the direction [say L] - Three other cells that can be reached via the other directions [say T, D and R] Thus we have 1 edge of weight 0 and 3 edges of weight 1 [as we incur a penalty]. The problem now reduces to a simple path finding problem. The default choice of algorithm to solve this would be Dijkstra’s but it’s time complexity is O(E + V log V). However, if we notice the constraints we can see that the edges are binary weighted. We can either follow the directions to reach the cell with cost 0 or change the direction and incur a penalty of 1. So, we can use a more efficient algorithm: 0-1 BFS which uses a deque and has the time complexity of O(E + V) In the normal BFS, we do the following changes: - If the adjacent cell has a cost of 0 [following direction], append it to the left of the queue else append the cell to the right - Always pop the node at the left This makes sure that we visit all nodes of a lower cost difference before moving on to the ones with a higher cost difference. Setter's Solution from collections import deque def minCost(grid, m, n): q = deque([[0, 0]]) dirp = [[-1, 0], [1, 0], [0, -1], [0, 1]] dirv = ['T', 'D', 'L', 'R'] vis = set([]) res = 0 while q: t = q[0] q.popleft() ci, cj = t[0]//n, t[0] % n if t[0] not in vis: res = t[1] vis.add(t[0]) if ci == m-1 and cj == n-1: return res for i, dv in enumerate(dirp): x, y = ci+dv[0], cj+dv[1] p = x*n + y if x < 0 or x >= m or y < 0 or y >= n or (p in vis): continue q.appendleft([p, t[1]]) if i == dirv.index( grid[ci][cj]) else q.append([p, t[1]+1]) return res m, n = map(int, input().split()) print(minCost([input().split() for i in range(m)], m, n))
https://discuss.codechef.com/t/chaat7-editorial/95548
CC-MAIN-2021-49
refinedweb
458
70.67
(Eric is out camping; this posting is prerecorded. I'll be back in the office after Labour Day.) The word "type" appears almost five thousand times in the C# 4 specification, and there is an entire chapter, chapter 4, dedicated to nothing but describing types. We start the specification by noting that C# is "type safe" and has "a unified type system" (*). We say that programs "declare" types, and that declared types can be organized by namespace. Clearly types are incredibly important to the design of C#, and incredibly important to C# programmers, so it is a more than a little bit surprising that nowhere in the eight hundred pages of the specification do we ever actually define the word "type". We sort of assume that the developer reading the specification already has a working understanding of what a "type" is; the spec does not aim to be either a beginner programming tutorial or a mathematically precise formal language description. But if you ask ten working line-of-business developers for a formal definition of "type", you might get ten different answers. So let's consider today the question: what exactly is this thing you call a "type"? A common answer to that question is that a type consists of: * A name * A set (possibly infinite) of values And possibly also: * A finite list of rules for associating values not in the type with values in the type (that is, coercions; 123.45 is not a member of the integer type, but it can be coerced to 123.) Though that is not a terrible definition as a first attempt, it runs into some pretty nasty problems when you look at it more deeply. The first problem is that of course not every type needs to have a name; C# 3 has anonymous types which have no names by definition. Is "string[][]" the name of a type? What about "List<string[][]>" -- does that name a type? Is the name of the string type "string" or "String", or "System.String", or "global::System.String", or all four? Does a type's name change depending on where in the source code you are looking? This gets to be a bit of a mess. I prefer to think of types as logically not having names at all. Program fragments "12" and "10 + 2" and "3 * 4" and "0x0C" are not names for the number 12, they are expressions which happen to all evaluate to the number 12. That number is just a number; how you choose to notate it is a fact about your notational system, not a fact about the number itself. Similarly for types; the program fragment "List<string[][]>" might, in its context, evaluate to refer to a particular type, but that type need not have that fragment as its name. It has no name. The concept of a "set of values" is also problematic, particularly if those sets are potentially infinite "mathematical" sets. To start with, suppose you have a value: how do you determine what its type is? There are infinitely many sets that can contain that value, and therefore infinitely many types that the value can be! And indeed, if the string "hello" is a member of the string type, clearly it is also a member of the object type. How are we to determine what "the" type of a value is? Things get even more brain-destroying when you think, oh, I know, I'll just say that every type's set of values is defined by a "predicate" that tells me whether a given value is in the type or not. That seems very plausible, but then you have to think about questions like "are types themselves values?" If so, then "the type whose values are all the types that are not members of themself" is a valid predicate, and hey, we've got Russell's Paradox all over again. (**) Moreover, the idea of a type being defined by a predicate that identifies whether a given value is of that type or not is quite dissimilar to how we typically conceive of types in a C# program. If it were, then we could have "predicate types" like "x is an even integer" or "x is not a prime number" or "x is a string that is a legal VBScript program" or whatever. We don't have types like that in the C# type system. So if a type is not a name, and a type is not a set of values, and a type is not a predicate that determines membership, what is a type? We seem to be getting no closer to a definition. Next time: I'll try to come up with a more workable definition of what "type" means to both compiler writers and developers. ------------ (*) An unfortunate half-truth, as pointer types are not unified into the type system in the version of the C# language which includes the "unsafe" subset of functionality. (**) When Russell discovered that his paradox undermined the entire arithmetic theory of Frege, he and Whitehead set about inventing what is now known as the "ramified theory of types", an almost impossible-to-understand theory that is immune to these sorts of paradoxes. Though the mathematical underpinnings of type theory/set theory/category theory/etc are fascinating, I do not understand them nearly well enough to go into detail here. Remember, what we're looking for is a definition of "type" that is amenable to doing practical work in a modern programming language. I think that in the scope of modeling an application into the programing language, a type means some kind of creation which the programmer makes. that's some integer coercion that turns 12.345 into 123. =) Defining a type as a set of values is not a problem because you couldn't ask what +the+ type of an expression is: after all, indeed, due to subclassing, values may have multiple types. The subtype is just a (smaller) set of values that all belong to the set of values of the base type. An important property of types not mentioned yet is that it describes a way to shape new objects – although that doesn't do for a definition either (since there are types that you cannot create new objects from, e.g. static types) @yie, the type of 12.345 is DecaDouble. You have to assume that Eric is right… 🙂 As an aside to people interested in it, there are in fact languages where things like "x is an even integer" or "x is a string that is a legal VBScript program" are types. This is a consequence of the Curry-Howard correspondence (which actually says that proof systems and programs can be expressed as each other, not types, so I'm glossing over some very necessary details for the full picture). Definitely worth checking out if mathematics don't scare you too much (there's lots of words and not many numbers in formal logic, so don't worry). Not the approach taken by mainstream languages like C#, obviously. @Jasper Actually, in the .NET/C# type system, for any given value, there is a type that is member specific (i.e., a subset of) all other types that the value or expression is a member of. That is what is usually what is referred to when one refers to "the" type of a value or expression. Simply calling a type a set of values is unsufficient, as not all sets of values are types. Instead, I would define a type using something along the lines of "A logical construct that defines a set of possible values and what operations can be performed on those set of values." Hmm… Types are a tool programmers use to structure data and the valid operations on the data. Defining a type as a set of valid values is too academic to be useful in implementing a compiler. A type is metadata, the actual form of which necessarily depends on the features of the programming language. Another problem with using the "set of values" definition is structurally identical compound types. Imagine you have two classes, X and Y, whose definition are identical. For example, a class Height and class Width, which are basically wrappers over an Int (single public Int field named "value," and no methods). Should a Height with value 10 be considered the same type as a Width with value 10? The set of values that they take are identical. But logically, they are different classes, and you want your type system to know the difference between Heights and Widths. After all, the main benefit of static type systems is checking program correctness. But in order to do so, you have to take two identical sets of values and somehow separate them. my best shot: a type is a blueprint for values or references. pointer types seem to be out of this category. @Logan Gordon: Just because Width and Height have the same structure, it doesn't mean they describe the same set of values. Surely an instance of Height with value=10 is not just of a different type from an instance of Width with value=10, but actually an entirely distinct value. It might have the same in-memory representation, but that's surely an unimportant implementation detail. A Type is a set of rules for how to tread a region of memory. I bet it's really called a "Type" because "Class" and "Structure" were already taken, it was late at night, it made sense and it sounded good. Of course, the definition of a type is dependant on context – I think of types in the CLR and types in C++ and types in Haskell as completely different things, and they are all programming language types! For CLR languages, the obvious answer is: A type is: An optional name, an optional namespace, an accessability, the assembly in which it is defined, an optional type from which it inherits, an optional set of types which it implements, an optional list of array dimensions, an optional type for which this is a pointer to, an optional list of generic arguments and a set of members (did I miss anything?). Obviously, that isn't terribly useful a definition for either semantics or implementation, but there you go 🙂 Semanticaly, a type is the association of a set of values with operations on them: 3 may be a value that is in the types byte, ushort, int, double, BigInteger, (in some languages) string, etc…, but without the association with a type (even if it's just object), you can't actually do anything with it – except perhaps, depending on your interpretation of when a value's existance begins, create a new instance of a type from it. Interestingly, this answers why expressions with the 'same' operations on the same values can have different results: eg 6 / 4 gives 1.5 with double division, but 1 with int division, and 100 * 2 gives 200 with byte multiplication, but -56 with sbyte multiplication. I prefer splitting the type from it's definition, this simplifies anonymous types (a type without any definitions) and typedef/type forwarding (a type with multiple definitions). I don't find it hard to believe that the "set of values" approach to defining types is not a total description of what we understand by "type", but I'm not yet convinced by Eric's arguments against it. 'suppose you have a value: how do you determine what its type is?' This seems a strange question to ask. What is it to "have a value"? Are we talking about a person looking at marks on a page? A compiler looking at expressions in a program text? A CPU looking at bytes in RAM? In most of the cases we care about,. When I was learning how to program I had a hard time in creating a mental modelof what types were. I finally came up with something simple, when I reversed the logic. I started by thinking what a program actually is to the computer. *) What is a program? It's a block of memory containing instructions for the cpu. *) What is an (object) instance? It's a block of memmory containing data those instructions should operate on. *) Since both can occupy (physically, though not at the same time) the same memory address, you need to tell the difference. *) Then what is a type? It's a block of memory that describes (definitiion) how another block of memory is to be interpreted. You can read a block of memory with the wrongtype, but that will (moslty) give you garbage. This model has worked fine by me for years now. There is some recursion going on here, (what describes the type?) but that is ok, you need a compiler to build a compiler too. (sorry if this is a double post, butfirst attempt was not accepted after 10 minutes, which weems a bit too long) ." Eric's point is not that we couldn't know *a* type if pressed but that it's hard to know *the* type — the one we care about in our language. "42" could be an integer or a string or a pixel set or a bunch of curves, depending on my symbolism, but that doesn't really help a compiler if I don't restrict my choices. If the type "meaningless scribbles" is allowed (or "top" or whatever you want to call it) then all values are certainly of at least that type, but that's of theoretical interest only. On the other end, "32 bit machine word" is only slightly more useful if you want to have a high-level language. If you will, Eric is using "value" in a common-sense way of "something that's undoubtedly a value in some type system, but not obviously of one particular type in the type system we're interested in (and it's our job to find out what it." Good luck writing a compiler that doesn't fret about what type a value is, but does "worry about the relationships between the types we care about". At the lowest level of your translation cycle is a bunch of meaningless scribbles. You'll have to type them in some way eventually. The more flexible you make typing, the more complex type interactions get. Even languages with type inference generally "prefer" to make decisions quickly rather than leave the question open until the entire set of all operations that could possibly happen is known, not just for implementation reasons but also because extremely open-ended typing tends to lead to surprises. Anyone who's worked with a script language that has some unexpected type conversion rules (most of them have at least one) knows what I'm talking about. That's not to say it isn't possible to take this view and stick with it, but the difficulty is a very real one worth fretting about for most compiler writers. This has changed so much from the NT daze. Eric, what are your top five fav blogs that you follow? Just curious. :O) @JM: Scribbles on paper and bytes in RAM were not given as examples of values, but of symbols. What I was saying is that in order to have a value at all you must *first* have some context that tells you that those four bytes are an unsigned integer or a single precision float or four ASCII characters or whatever else. If you don't have the context then you don't really have the value. "Good luck writing a compiler that doesn't fret about what type a value is" Oh dear, that is not what I meant at all. I said that you can't have a value without some kind of context. What I was trying to say is that it that it doesn't seem particularly important to try to define (say) some function that takes an utterly arbitrary value and tells you its type because it's the context that tells you what other values it could have had, not the value itself. When talking about the value "hello", perhaps the context tells you that it could have been any sequence of characters (i.e., any string). The useful questions are then whether this type – the set of all strings – is a subset of some other type we are interested in, say the set of all objects, or whether a string can be coerced to another type, and so on. That's what I mean by "the relationships between the types we care about". I don't think anything I said precludes any particular compiler/interpreter implementations. I'm just talking about the question at hand – what is a type; and Eric's reasons for why a "set of possible values" is not a suitable definition of a type. I'd have considered this to be a relatively abstract question about the principles behind programming languages, not a specific mechanism for implementing a compiler or interpreter. How about this – a type T is: 1) A set of operations that can *create* distinct values ("instances of T"). 2) A set of operations that can *be performed on instances* of T. There's some subtlety in the meaning of the word "distinct" in that first paragraph that I am not quite sure how to get across – something to the effect that the values thus created must be tagged with the identity of T so that other types cannot ever produce the same values. But I think overall this kind of definition applies as a working definition of how the concept of a Type is used in the CLR. A type is union of: – data storage specification (at least size); – agreement about meaning of that data (e.g. "this is character"). … and optional set of operations defined for this data. This covers c# (and it's .Net underpinnings) only, java would be similar in some ways but the lack of user defined value types means a bunch of things are not required. A Type is a set of Capabilities and Restrictions relevant (but in subtly different ways) to any storage location and instances of objects. These are defined in several places, in some cases the c# spec, in others your code some in the CLR specification itself. They are likewise implemented in multiple places, the compiler, the runtime, the resulting code from the compiler. Types can be reified in two ways, At runtime through reflection (either by asking the compiler to get it via typeof() or by asking the runtime to get it from an object instance with GetType() or moral equivalent). The other was added in 2.0 with the addition of generics. A generic type 'T' exists as something which can be interacted with at compile time, it is in essence a placeholder in which you can substitute a type, but once picked for a specific instance/storage location cannot be changed. These reifications, precisely because they make some abstractions concrete do not encompass all aspects of Types, they can be very loosely analogous to pictures of types (in the sense of reflection) or silhouettes of types (generics). Thus all further definitions here will indicate precisely when it is talking about either of these reifications. Types exist without objects, if you have a variable foo which is defined to contain an int then the only things that knows about that is the compiler (both csc and the jit) and the runtime (so it can know there is/isn't a need to trace through that location when determining the live set). Types also exist outside of storage locations (you may have a storage location defined as type "object" but the value referenced by it has type Flibble. Note that There is no requirement that the runtime actually creates all the cruft associated with the type of string is defined anywhere (see escape analysis and enregistration). The capabilities come in to play in a few ways: The operations which may be performed on something contained within a storage location (the type in question being the type of the storage location) verses the code which will be used to determine the actual behaviour which may be defined by the type of the instance which is present in the storage location. What fields (themselves storage locations defined by their type and name) are present on the type. Can instances of the type be blitted. What conversions between types are possible (and again how this happens) Some of these capabilities imply virtual dispatch The Restrictions, far more of these, for example How may a specific type be constructed. How visible is the type (for this the concept of module, a collection of types must also be defined). Can the type be extended for implementation inheritance. How much space is required to hold an instance of the type in a storage location. For reference types this is defined to always be done through managed references, which abstract the problem away by always being IntPtr.Size. For value types the sizes must be known at compile time. Does assignment to another storage location require a copy (or at least require the *semantics* of a blit based copy) (ref and out parameters are aliases to the _same_ storage location). Many of these became much more complex and subtle when generics came in. Some types are 'special' in the sense that they only appear at certain points (say only at compile time). dynamic is one such type. It ceases to exist at runtime (if you attempt to reflect on it this will be obvious), instead be replaced by specific instances of other types which are responsible for ensuring the behaviours expected of it are adhered to. Generics in java would be another example as they apply at compile time but cease to exist at runtime (again reflection or simply casting allow you to violate the specifications the compiler enforced) . Another is pointers, which have many aspects akin to types (capabilities and restrictions) but they are markedly different from other types and as such cannot be reified in the same fashion (no reflection, not no boxing, no use in generics) Much of the subtlety in the specification (and compiler design) comes from which capabilities and restrictions exist at a point in time, and which order they are applied in (if at all). (this is a retry, my first attempt seems to be munched, sorry if it shows up doubly after all!) @JM: Indeed there are more sophisticated type systems where you could define types like 'a string representing a valid VB program' – but either you'll have to pack more info with the string to have it be a value of that type (namely data proving that it is, in fact, a representation of a valid VB program) or you'll have to be content with your type judgement being undecidable, i.e. not being able always to tell whether value x belongs to type y or not. An undesirable trait, IMO, especially for compilers wanting to give guarantees of correctness. I think the type is a combination of rules we put together. A type can be some sort of imaginary we make in mind when we see a value. I agree that the value is should have a type but this "type" is some how semi hidden My try on the meaning of type without reading through the article: A type is implied set of rules for natrual interpretation and manipulation of data. @Amin: Value may not necessarily be associated with types if our defination is not bounded to .NET realm. See C++ macro defined values for example, also a value referenced by untyped pointer for another example. An interesting question, 'are type values themselves?'. Certainly there is the type Type, and the operator typeof() and method object.GetType() yield values in that type. But one cannot say e.g. Type mytype = condition() ? String : Int64; -or- String.GetType(). So there is a difference between the (compile-time) type indications we use to type variables with or use the new operator on, and the (run-time) Type-valued objects representing these types. That said, by reflection we can use the latter to create new instances with, so maybe types are values themselves after all. Russell's paradox is avoided since values seem (implicitly) to have a reference to their types. Defining a new subtype B of A that doesn't extend A in any way doesn't suddenly yield all A-typed objects to be B-objects as well – this in contrast to a set-theoretic view when types are just sets of values. (Hope this post doesn't get lost on the way – chances are 50-50 up to now :-S Nimrand, I tried to reply to you twice, but no luck) @cheong00 : What I mean is not bounded to a special programming language. Think about my word in real life examples. I think what you say is something we call 'feature' of a programming language or 'specification' or 'model of creation' of a language , but if we don't bound ourselves to some programming platform and focus on the deep meaning of the 'Type' we come to the common rules for natrual interpretation and manipulation of data as you said yourself. And another interesting thing I think of : sometimes values can make new types… what do you think ? >> To start with, suppose you have a value: how do you determine what its type is? I think this counterpoint is subtly wrong, for the simple reason that it makes certain assumptions about what a "value" is – and surely, if we're defining "types" in terms of "values", we should first define what a "value" is with similar rigor? On the other hand, if "value" itself is defined as data tagged with a type – which resembles more what we actually see in CLR – then there's no contradiction. A type then is, indeed, just a predicate, and every value is tagged with one (and only one) type, which is how we can determine the "actual" type of any value. @Amin: For values that makes new type, that doesn't make many difference if you're using my defination. You still have to obey the function contract (memory size, properties, methods) provided by the new type, and provide a way to interprete the value it holds. Actually I'll agree my defination is a bit dull and not stimulating imagination, just that it helps to fit all essential parts to think about while talking about the term "type" when we talk about programming. Not that difficult really, something like, "A logical, hierarcichal, and tractable classification of values that can be bound to a function." > but then you have to think about questions like "are types themselves values?" If so, then "the type whose values are all the types that are not members of themself" is a valid predicate, and hey, we've got Russell's Paradox all over again. (**) Isn't that exactly the difference between naive set theory and type theory? Things that classify values aren't values themselves. Instead you have different levels and only entities from lower levels can be used to compose an entity of a higher level, thus preventing loops and avoiding Russell's Paradox. Going a bit beyond C# and looking at Scala or Haskell you can see it better: "values" are classified by "types" and "types" are classified by "kinds". So you already have three layers. Ωmega (an academic language) even has an infinite count of layers ("kinds" are classified by "sorts", …). Why is Russell's Paradox a "Bad Thing"? It makes me think of the man who goes to doctor complaining about how it hurt if he poked himself.. just don't define a "stupid predicate" like that and you wouldn't run into the paradox. Sure that isn't the most elegant solution, but programming is already full of "so just don't do that"'s. Consider the tuple (x=2, y=4). What function does it belong to? Well, 2*2 = 4, so it might belong to the function y = 2*x. But 2² = 4 as well, so it equally belongs to the function y = x². So how do you determine what the function of (2, 4) is? I think you’ll agree this question makes no sense. There is no reason that a tuple must belong to a single function and no other. In your post the rhetorical question “how do you determine what its type is?” is on the same shelf. I do indeed conceptualise types as sets of possible values, i.e. your option #2, and the fact that a value can belong to any number of conceivable types does not pose a problem to me.
https://blogs.msdn.microsoft.com/ericlippert/2011/08/29/what-is-this-thing-you-call-a-type-part-one/?replytocom=12038
CC-MAIN-2018-39
refinedweb
4,828
58.72
You are not logged in. Pages: 1 6 This ([email protected]), ([email protected]) for emailing me some pointers on clarifying this answer. From: lore Try this: char gimme_char(int fd) { char * buf = (char *)NULL; buf = (char *)malloc(1); if (recv(fd, buf, 1, 0)) return ((char)*buf); } From: GinShinzou ok this code is very sloppy (no offense, but i see malloc and no free...) what you didn't realize is that malloc keeps the memory assigned until the application terminates. you should allways put free() as close to the malloc call as possible. if you use this code, you'll get a really, really big memory leak lol. especially in server applications, who tend to read massive amounts of data and stay up for days at a time! try this: char gimme_char(int fd) { char buf; if ( recv(fd, &buf, 1, 0) ) return buf; else return '\0'; } it's much easier to understand too! this will sleep until a character is available to read. if an error occurs (like the connection terminating), it will return a null character. Offline Pages: 1
http://developerweb.net/viewtopic.php?pid=12650
CC-MAIN-2019-13
refinedweb
181
72.56
PTHREAD_COND_TIMEDWAI... BSD Library Functions Manual PTHREAD_COND_TIMEDWAI... NAME pthread_cond_timedwait -- wait on a condition variable for a specific amount of time SYNOPSIS #include <pthread.h> int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime); DESCRIPTION. Values for struct timespec can be obtained by adding the required time interval to the the current time obtained using gettimeofday(2). Note that struct timeval and struct timespec use different units to spec- ify the time. Hence, the user should always take care to perform the time unit conversions accordingly. EXAMPLE struct timeval tv; struct timespec ts; gettimeofday(&tv, NULL); ts.tv_sec = tv.tv_sec + 0; ts.tv_nsec = 0; RETURN VALUES If successful, the pthread_cond_timedwait() function will return zero. Otherwise, an error number will be returned to indicate the error. ERRORS pthread_cond_timedwait() will fail if: [EINVAL] The value specified by cond, mutex or abstime is invalid. [ETIMEDOUT] The system time has reached or exceeded the time spec- ified in abstime. SEE ALSO pthread_cond_broadcast(3), pthread_cond_destroy(3), pthread_cond_init(3), pthread_cond_signal(3), pthread_cond_wait(3), gettimeofday(2) STANDARDS pthread_cond_timedwait() conforms to ISO/IEC 9945-1:1996 (``POSIX.1''). BSD July 28, 1998 BSD Mac OS X 10.8 - Generated Thu Aug 30 05:38:51 CDT 2012
http://www.manpagez.com/man/3/pthread_cond_timedwait/
CC-MAIN-2018-05
refinedweb
201
50.73
In Eclipse, you can create a project jar with its required dependencies in an adjacent sub-folder by doing ... Export->Java->Runnable JAR file Select Library handling option: Copy required libraries into a sub-folder next to the generated JAR Is the In my app I want to show photo and name instead of Bluetooth name without connecting Bluetooth.. like shown in image. There is list of searched Bluetooth device using search button in my app, By default in list, there is show name of Bluetooth , but I'm able to get all those things as shown in my code below, but unable to retrieve email from the user profile. What can I do for this? Any kind of help will be appreciated. Earlier I was using this source to get details of Facebook user and was fetc I recently started using kivy, and I have a question about the change of the background. I need to create multiple widgets with different backgrounds. I'm doing it wrong, but I did not get: Kv file: <[email protected]>: canvas.before: Color: rgb: s I am getting List of running background applications. To kill those applications by using: List<RunningAppProcessInfo> listprocInfos =actvityManager.getRunningAppProcesses(); if(RunningAppProcessInfo procInfos : listprocInfos ) { activityManager.kil I am using sendkeys method in Appium android to enter text in textfield but it is taking large time to perform sendkeys action. So is there any method to reduce the time of sendkeys action. WebElement emailField = driver.findElement(By.id("email" I am working with a small game in pure android, and I stuck at creating a levels game selection screen. Here is the sample image of design . User can scroll levels list or moving background to the current level. It looks like the horizontal list usin I have a table with following structure. public static final String TABLE_NAME = "contact"; public static final String ID = "_id"; public static final String DEVICE_ID = "device_id"; public static final String NAME = "na I am developing an Android application which requires me to process visual data. The current outline of the relevant code is as follows: public class ProcessFrames extends Activity implements Camera.PreviewCallback { ... @override public void onPrevi How to give opacity to a textview inside a fragment? Initially i having a horizontal circular ViewPager, and TextView inside my fragment should fade in and fade out when focusing to the screen and leaving the screen respectively. I done some experime I created a custom view and want to play a sound when touched. In my attrs.xml file I added an attribute called sound. <attr name="sound" format="integer"/> In my layout file I set sound to my sound file in the raw package <cu I want to implement visualization on camera image. For Example: if in camera view there is any wall and closed surface you can color that surface by choosing color from colorPicker. For a reference you can see dulux visualizer. Can anyone suggest me I already implemented how to share image in Facebook and WhatsApp messenger. But i wanted it in different way. code ActivityManager mActivityManager =(ActivityManager)c.getSystemService(Context.ACTIVITY_SERVICE); if(Build.VERSION.SDK_INT > 20){ mPack I came to know that we can play video in texture view. But I saw only how to play videos capturing by camera but I want to play an available video in it to perform any animations. I have tried this code but I don't know where to place video.mp4 publi I have can WebView in Fragment, when move tab Fragment,and I touch Button aboutUs--> move in Fragment AboutUs; I repeat about 10times. Error is same picture. can everyone help me?. Thank : Code Fragment load WebView : public class InAppBrowserFragmen String chooseTitle = activity.getString(R.string.select_or_take_picture); Intent getIntent = new Intent(); getIntent.setType("image/*"); getIntent.setAction(Intent.ACTION_GET_CONTENT); Intent galleryIntent = new Intent(Intent.ACTION_PICK, androi Here is my scenario. I am making a listview extending a ArrayAdapter class. In that class I am making a text and a check box dynamically. In that view I want to capture what check box clicked by user. Here is my ArrayAdapter class's getView method... I am trying to load a html file in a webView that contains Bangla sentences.But I'm having trouble to do this.Web page is showing, But the fonts or the sentences are not showing. My code is here... protected void onCreate(Bundle savedInstanceState) { I need to populate ListView with icon and their title. I have created array in resources for menu icon and their title like: For titles: <array name="menu_title_array"> <item>@string/menu_name_text</item> </array> For ico Is it possible to print backtrace of a thread ( I have thread id and process id ) from adb shell /or by any other method without modifying the code ? --------------Solutions------------- You can: Attach a debugger (if the app is debuggable). Attach D
http://www.dskims.com/category/android/
CC-MAIN-2018-34
refinedweb
809
56.96
James McCaffrey Consider the problem of identifying abnormal data items in a very large data set, for example, identifying potentially fraudulent credit-card transactions, risky loan applications and so on. One approach to detecting abnormal data is to group the data items into similar clusters and then seek data items within each cluster that are different in some sense from other data items within the cluster. There are many different clustering algorithms. One of the oldest and most widely used is the k-means algorithm. In this article I’ll explain how the k-means algorithm works and present a complete C# demo program. There are many existing standalone data-clustering tools, so why would you want to create k-means clustering code from scratch? Existing clustering tools can be difficult or impossible to integrate into a software system, they might not be customizable to deal with unusual scenarios, and the tools might have copyright or other intellectual property issues. After reading this article you’ll be able to experiment with k-means clustering and have the base knowledge to add clustering functionality to a .NET application. The best way to get a feel for what k-means clustering is and to see where I’m headed in this article is to take a look at Figure 1. The demo program begins by creating a dummy set of 20 data items. In clustering terminology, data items are sometimes called tuples. Each tuple here represents a person and has two numeric attribute values, a height in inches and a weight in pounds. One of the limitations of the k-means algorithm is that it applies only in cases where the data tuples are completely numeric. Figure 1 Clustering Using k-Means The dummy data is loaded into an array in memory. Next, the number of clusters is set to three. Although there are advanced clustering techniques that can suggest the optimal number of clusters to use, in general data clustering is an exploratory process and the best number of clusters to use is typically found through trial and error. As you’ll see shortly, k-means clustering is an iterative process. The demo program has a variable maxCount, which is used to limit the number of times the main clustering loop will execute. Here that value is arbitrarily set to 30. Next, behind the scenes, the demo program uses the k-means algorithm to place each data tuple into one of three clusters. There are many ways to encode a clustering. In this case, a clustering is defined by an array of int where the array index represents a tuple, and the associated array value represents the 0-based cluster ID. So, in Figure 1, tuple 0 (65.0, 220.0) is assigned to cluster 0, tuple 1 (73.0, 160.0) is assigned to cluster 1, tuple 2 (59.0, 110.0) is assigned to cluster 2, tuple 3 (61.0, 120.0) is assigned to cluster 2 and so on. Notice there are eight tuples assigned to cluster 0, five tuples assigned to cluster 1, and seven tuples assigned to cluster 2. Next, the demo program displays the data, grouped by cluster. If you examine the clustered data you’ll see that cluster 0 might be called the heavy people cluster, cluster 1 might be called the tall people cluster, and cluster 2 might be called the short people cluster. The demo program concludes by analyzing the tuples assigned to cluster 0 and determines that by some criterion, tuple 5 (67.0, 240.0) is the most abnormal tuple. In the sections that follow, I’ll walk you through the code that produced the screenshot in Figure 1 so that you’ll be able to modify this code to meet your own needs. This article assumes you have at least intermediate-level programming skill with a C-family language, but does not assume you know anything about data clustering. I coded the demo program using C#, but I used a non-OOP style so you shouldn’t have too much difficulty refactoring the demo to another language if you wish. I present all the source code for the demo program in this article. The source code is also available at archive.msdn.microsoft.com/mag201302kmeans. In principle, at least, the k-means algorithm is quite simple. But as you’ll see, some of the implementation details are a bit tricky. The central concept in the k-means algorithm is the centroid. In data clustering, the centroid of a set of data tuples is the one tuple that’s most representative of the group. The idea is best explained by example. Suppose you have three height-weight tuples similar to those shown in Figure 1: [a] (61.0, 100.0) [b] (64.0, 150.0) [c] (70.0, 140.0) Which tuple is most representative? One approach is to compute a mathematical average (mean) tuple, and then select as the centroid the tuple that is closest to that average tuple. So, in this case, the average tuple is: [m] = ((61.0 + 64.0 + 70.0) / 3, (100.0 + 150.0 + 140.0) / 3) = (195.0 / 3, 390.0 / 3) = (65.0, 130.0) And now, which of the three tuples is closest to (65.0, 130.0)? There are several ways to define closest. The most common approach, and the one used in the demo program, is to use the Euclidean distance. In words, the Euclidean distance between two tuples is the square root of the sum of the squared differences between each component of the tuples. Again, an example is the best way to explain. The Euclidean distance between tuple (61.0, 100.0) and the average tuple (65.0, 130.0) is: dist(m,a) = sqrt((65.0 - 61.0)^2 + (130.0 - 100.0)^2) = sqrt(4.0^2 + 30.0^2) = sqrt(16.0 + 900.0) = sqrt(916.0) = 30.27 Similarly: dist(m,b) = sqrt((65.0 - 64.0)^2 + (130.0 - 150.0)^2) = 20.02 dist(m,c) = sqrt((65.0 - 70.0)^2 + (130.0 - 140.0)^2) = 11.18 Because the smallest of the three distances is the distance between the math average and tuple [c], the centroid of the three tuples is tuple [c]. You might wish to experiment with the demo program by using different definitions of the distance between two tuples to see how those affect the final clustering produced. With the notion of a cluster centroid established, the k-means algorithm is relatively simple. In pseudo-code: assign each tuple to a randomly selected cluster compute the centroid for each cluster loop until no improvement or until maxCount assign each tuple to best cluster (the cluster with closest centroid to tuple) update each cluster centroid (based on new cluster assignments) end loop return clustering If you search the Web, you can find several good online animations of the k-means algorithm in action. The image in Figure 2 shows the clustering produced by the demo program. The circled data item in each cluster is the cluster centroid. Figure 2 Clustered Data and Centroids The overall program structure for the demo shown in Figure 1, with a few minor edits, is listed in Figure 3. I used Visual Studio 2010 to create a new C# console application named ClusteringKMeans; any recent version of Visual Studio should work, too. In the Solution Explorer window I renamed file Program.cs to ClusteringKMeansProgram.cs, which automatically renamed the template-generated class. I removed unneeded using statements at the top of the file. Figure 3 Overall Program Structure using System; namespace ClusteringKMeans { class ClusteringKMeansProgram { static void Main(string[] args) { try { Console.WriteLine("\nBegin outlier data detection demo\n"); Console.WriteLine("Loading all (height-weight) data into memory"); string[] attributes = new string[] { "Height", "Weight" };("\nRaw data:\n"); ShowMatrix(rawData, rawData.Length, true); int numAttributes = attributes.Length; int numClusters = 3; int maxCount = 30; Console.WriteLine("\nk = " + numClusters + " and maxCount = " + maxCount); int[] clustering = Cluster(rawData, numClusters, numAttributes, maxCount); Console.WriteLine("\nClustering complete"); Console.WriteLine("\nClustering in internal format: \n"); ShowVector(clustering, true); Console.WriteLine("\nClustered data:"); ShowClustering(rawData, numClusters, clustering, true); double[] outlier = Outlier(rawData, clustering, numClusters, 0); Console.WriteLine("Outlier for cluster 0 is:"); ShowVector(outlier, true); Console.WriteLine("\nEnd demo\n"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } // Main // 14 short static method definitions here } } For simplicity I used a static method approach and removed all error-checking. The first part of the demo code sets up the height and weight data to be clustered. Because there are only 20 tuples, I hardcoded the data and stored the data in memory in an array named rawData. Typically, your data will be stored in a text file or SQL table. In those cases you’ll have to write a helper function to load the data into memory. If your data source is too large to fit into machine memory, you’ll have to modify the demo code to iterate through an external data source rather than a data array. After setting up the raw data, the demo program calls helper function ShowMatrix to display the data. Next, variables numAttributes, numClusters, and maxCount are assigned values of 2 (height and weight), 3 and 30, respectively. Recall maxCount limits the number of iterations in the main algorithm processing loop. The k-means algorithm tends to converge quickly, but you might have to experiment a bit with the value of maxCount. All the clustering work is performed by method Cluster. The method returns an int array that defines how each tuple is assigned to one cluster. After finishing, the demo program displays the encoded clustering and also displays the raw data, grouped according to cluster. The demo program concludes by analyzing the clustered data for outlier, possibly abnormal, tuples using method Outliers. That method accepts a cluster ID and returns the values of the data tuple that’s the farthest (as measured by Euclidean distance) from the cluster centroid (most representative tuple). In this case, for cluster 0, the heavy person cluster, the outlier tuple is (67.0, 240.0), the heaviest person. Recall that a cluster centroid is a tuple that is most representative of the tuples assigned to a cluster, and that one way to determine a cluster centroid is to compute a math average tuple and then find the one tuple that’s closest to the average tuple. Helper method UpdateMeans computes the math average tuple for each cluster and is listed in Figure 4. Figure 4 Method UpdateMeans static void UpdateMeans(double[][] rawData, int[] clustering, double[][] means) { int numClusters = means.Length; for (int k = 0; k < means.Length; ++k) for (int j = 0; j < means[k].Length; ++j) means[k][j] = 0.0; int[] clusterCounts = new int[numClusters]; for (int i = 0; i < rawData.Length; ++i) { int cluster = clustering[i]; ++clusterCounts[cluster]; for (int j = 0; j < rawData[i].Length; ++j) means[cluster][j] += rawData[i][j]; } for (int k = 0; k < means.Length; ++k) for (int j = 0; j < means[k].Length; ++j) means[k][j] /= clusterCounts[k]; // danger return; } Method UpdateMeans assumes that an array of arrays named means already exists, as opposed to creating the array and then returning it. Because array means is assumed to exist, you might want to make it a ref parameter. Array means is created using helper method Allocate: static double[][] Allocate(int numClusters, int numAttributes) { double[][] result = new double[numClusters][]; for (int k = 0; k < numClusters; ++k) result[k] = new double[numAttributes]; return result; } The first index in the means array represents a cluster ID and the second index indicates the attribute. For example, if means[0][1] = 150.33 then the average of the weight (1) values of the tuples in cluster 0 is 150.33. Method UpdateMeans first zeros out the existing values in array means, then iterates through each data tuple and tallies the count of tuples in each cluster and accumulates the sums for each attribute, and then divides each accumulated sum by the appropriate cluster count. Notice that the method will throw an exception if any cluster count is 0, so you might want to add an error-check. Method ComputeCentroid (listed in Figure 5) determines the centroid values—the values of the one tuple that’s closest to the average tuple values for a given cluster. Figure 5 Method ComputeCentroid static double[] ComputeCentroid(double[][] rawData, int[] clustering, int cluster, double[][] means) { int numAttributes = means[0].Length; double[] centroid = new double[numAttributes]; double minDist = double.MaxValue; for (int i = 0; i < rawData.Length; ++i) // walk thru each data tuple { int c = clustering[i]; if (c != cluster) continue; double currDist = Distance(rawData[i], means[cluster]); if (currDist < minDist) { minDist = currDist; for (int j = 0; j < centroid.Length; ++j) centroid[j] = rawData[i][j]; } } return centroid; } Method ComputeCentroid iterates through each tuple in the data set, skipping tuples that aren’t in the specified cluster. For each tuple in the specified cluster, the Euclidean distance between the tuple and the cluster mean is calculated using helper method Distance. The tuple values that are closest (having the smallest distance) to the mean values are stored and returned. Method UpdateCentroids calls ComputeCentroid for each cluster to give the centroids for all clusters: static void UpdateCentroids(double[][] rawData, int[] clustering, double[][] means, double[][] centroids) { for (int k = 0; k < centroids.Length; ++k) { double[] centroid = ComputeCentroid(rawData, clustering, k, means); centroids[k] = centroid; } } Method UpdateCentroids assumes that an array of arrays named centroids exists. Array centroids is very similar to array means: The first index represents a cluster ID and the second index indicates the data attribute. To summarize, each cluster has a centroid, which is the most representative tuple in the cluster. Centroid values are computed by finding the one tuple in each cluster that’s closest to the average tuple (the mean) in each cluster. Each data tuple is assigned to the cluster whose cluster centroid is closest to the tuple. Method ComputeCentroid calls a Distance method to determine which data tuple is closest to a cluster mean. As described earlier, the most common way to measure distance from tuples to means is to use Euclidean distance: static double Distance(double[] tuple, double[] vector) { double sumSquaredDiffs = 0.0; for (int j = 0; j < tuple.Length; ++j) sumSquaredDiffs += Math.Pow((tuple[j] - vector[j]), 2); return Math.Sqrt(sumSquaredDiffs); } You might want to consider alternative ways to define distance. A very common option is to use the sum of the absolute values of the differences between each component. Because Euclidean distance squares differences, larger differences are weighted much more heavily than smaller differences. Another important factor related to the choice of distance function in the k-means clustering algorithm is data normalization. The demo program uses raw, un-normalized data. Because tuple weights are typically values such as 160.0 and tuple heights are typically values like 67.0, differences in weights have much more influence than differences in heights. In many situations, in addition to exploring clustering on raw data, it’s useful to normalize the raw data before clustering. There are many ways to normalize data. A common technique is to compute the mean (m) and standard deviation (sd) for each attribute, then for each attribute value (v) compute a normalized value nv = (v-m)/sd. With a method to compute the centroid of each cluster in hand, it’s possible to write a method to assign each tuple to a cluster. Method Assign is listed in Figure 6. Figure 6 Method Assign static bool Assign(double[][] rawData, nt[] clustering, double[][] centroids) { int numClusters = centroids.Length; bool changed = false; double[] distances = new double[numClusters]; for (int i = 0; i < rawData.Length; ++i) { for (int k = 0; k < numClusters; ++k) distances[k] = Distance(rawData[i], centroids[k]); int newCluster = MinIndex(distances); if (newCluster != clustering[i]) { changed = true; clustering[i] = newCluster; } } return changed; } Method Assign accepts an array of centroid values and iterates through each data tuple. For each data tuple, the distance to each of the cluster centroids is computed and stored in a local array named distances, where the index of the array represents a cluster ID. Then helper method MinIndex determines the index in array distances that has the smallest distance value, which is the cluster ID of the cluster that has centroid closest to the tuple. Here’s helper method MinIndex: static int MinIndex(double[] distances) { int indexOfMin = 0; double smallDist = distances[0]; for (int k = 0; k < distances.Length; ++k) { if (distances[k] < smallDist) { smallDist = distances[k]; indexOfMin = k; } } return indexOfMin; } In Assign, if the computed cluster ID is different from the existing cluster ID stored in array clustering, array clustering is updated and a Boolean flag to indicate that there has been at least one change in the clustering is toggled. This flag will be used to determine when to stop the main algorithm loop—when the maximum number of iterations is exceeded or when there’s no change in the clustering. This implementation of the k-means algorithm assumes that there’s always at least one data tuple assigned to each cluster. As given in Figure 6, method Assign does not prevent a situation where a cluster has no tuples assigned. In practice, this usually isn’t a problem. Preventing the error condition is a bit tricky. The approach I generally use is to create an array named centroidIndexes that works in conjunction with array centroids. Recall that array centroids holds centroid values, for example (61.0, 120.0) is the centroid for cluster 2 in Figure 2. Array centroidIndexes holds the associated tuple index, for example [3]. Then in the Assign method, the first step is to assign to each cluster the data tuple that holds the centroid values, and only then does the method iterate through each remaining tuple and assign each to a cluster. This approach guarantees that every cluster has at least one tuple. Method Cluster, listed in Figure 7, is the high-level routine that calls all the helper and sub-helper methods to actually perform the data clustering. Figure 7 The Cluster Method static int[] Cluster(double[][] rawData, int numClusters, int numAttributes, int maxCount) { bool changed = true; int ct = 0; int numTuples = rawData.Length; int[] clustering = InitClustering(numTuples, numClusters, 0); double[][] means = Allocate(numClusters, numAttributes); double[][] centroids = Allocate(numClusters, numAttributes); UpdateMeans(rawData, clustering, means); UpdateCentroids(rawData, clustering, means, centroids); while (changed == true && ct < maxCount) { ++ct; changed = Assign(rawData, clustering, centroids); UpdateMeans(rawData, clustering, means); UpdateCentroids(rawData, clustering, means, centroids); } return clustering; } The main while loop repeatedly assigns each data tuple to a cluster, computes the new tuple means for each cluster, then uses the new means to compute the new centroid values for each cluster. The loop exits when there’s no change in cluster assignment or some maximum count is reached. Because the means array is used only to compute centroids, you might want to refactor Cluster by placing the call to UpdateMeans inside method UpdateCentroids. Before kicking the processing loop off, the clustering array is initialized by method InitClustering: static int[] InitClustering(int numTuples, int numClusters, int randomSeed) { Random random = new Random(randomSeed); int[] clustering = new int[numTuples]; for (int i = 0; i < numClusters; ++i) clustering[i] = i; for (int i = numClusters; i < clustering.Length; ++i) clustering[i] = random.Next(0, numClusters); return clustering; } The InitClustering method first assigns tuples 0 through numClusters-1 to clusters 0 through numClusters-1, respectively, so that every cluster will start with at least one tuple assigned. The remaining tuples are assigned to a randomly selected cluster. A somewhat surprising amount of research has been done on k-means clustering initialization and you may want to experiment with alternatives to the approach given here. In many cases, the final clustering produced by the k-means algorithm depends on how the clustering is initialized. One way to use data clustering is to simply explore different clusterings and look for unexpected or surprising results. Another possibility is to look for unusual data tuples within a cluster. The demo program checks cluster 0 to find the tuple in that cluster that’s farthest from the cluster centroid using a method named Outlier, which is listed in Figure 8. Figure 8 The Outlier Method static double[] Outlier(double[][] rawData, int[] clustering, int numClusters, int cluster) { int numAttributes = rawData[0].Length; double[] outlier = new double[numAttributes]; double maxDist = 0.0; double[][] means = Allocate(numClusters, numAttributes); double[][] centroids = Allocate(numClusters, numAttributes); UpdateMeans(rawData, clustering, means); UpdateCentroids(rawData, clustering, means, centroids); for (int i = 0; i < rawData.Length; ++i) { int c = clustering[i]; if (c != cluster) continue; double dist = Distance(rawData[i], centroids[cluster]); if (dist > maxDist) { maxDist = dist; Array.Copy(rawData[i], outlier, rawData[i].Length); } } return outlier; } After initializing means and centroids arrays, method Outlier iterates through each tuple in the specified cluster and computes the Euclidean distance from the tuple to the cluster centroid, then returns the values of the tuple that has the greatest distance to the centroid values. A minor alternative for you to consider is to return the index of the farthest data tuple. There are many other ways you can examine clustered data for abnormalities. For example, you might want to determine the average distance between each tuple and its assigned cluster centroid, or you might want to examine the distances of the cluster centroids from each other. For the sake of completeness, here are some simplified display routines. The code download has slightly fancier versions. If you use these simplified routines, you’ll have to modify their calls in the Main method. To display raw data, means and centroids you can use: static void ShowMatrix(double[][] matrix) { for (int i = 0; i < numRows; ++i) { Console.Write("[" + i.ToString().PadLeft(2) + "] "); for (int j = 0; j < matrix[i].Length; ++j) Console.Write(matrix[i][j].ToString("F1") + " "); Console.WriteLine(""); } } To display the clustering array you can use: static void ShowVector(int[] vector) { for (int i = 0; i < vector.Length; ++i) Console.Write(vector[i] + " "); Console.WriteLine(""); } To display an outlier’s values you can use: static void ShowVector(double[] vector) { for (int i = 0; i < vector.Length; ++i) Console.Write(vector[i].ToString("F1") + " "); Console.WriteLine(""); } And to display raw data grouped by cluster you can use: static void ShowClustering(double[][] rawData, int numClusters, int[] clustering) { for (int k = 0; k < numClusters; ++k) // Each cluster { for (int i = 0; i < rawData.Length; ++i) // Each tuple if (clustering[i] == k) { for (int j = 0; j < rawData[i].Length; ++j) Console.Write(rawData[i][j].ToString("F1") + " "); Console.WriteLine(""); } Console.WriteLine(""); } } Data clustering is closely related to and sometimes confused with data classification. Clustering is an unsupervised technique that groups data items together without any foreknowledge of what those groups might be. Clustering is typically an exploratory process. Classification, in contrast, is a supervised technique that requires the specification of known groups in training data, after which each data tuple is placed into one of these groups. Classification is typically used for prediction purposes. The code and explanation presented in this article should give you enough information to experiment with k-means data clustering, or to create a fully customizable standalone clustering tool, or to add clustering features to a .NET application without relying on any external dependencies. There are many other clustering algorithms in addition to k-means and I’ll present some of these in future MSDN Magazine articles, including data entropy minimization, category utility and Naive Bayes inference.: Darren Gehring Very nice article, would also have wanted to see the plot results of the data points. Should be interesting to see for large data sets in online clustering Great article. You really should consider putting all these algorithm articles into a (Kindle) book. Would make it much easier to find the algorithm I need right now, but can't remember where I read about six months ago. (from the author) Thanks to reader Tom Denevan for pointing out that the clustering algorithm presented here is more accurately called k-medoid (sometimes spelled medioid) clustering because the representative point in each cluster is one of the data points rather than an arithmetic mean of points. James M More MSDN Magazine Blog entries > Browse All MSDN Magazines Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
http://msdn.microsoft.com/en-us/magazine/jj891054.aspx
CC-MAIN-2013-48
refinedweb
4,075
54.42
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How to create field with dynamic label name???? Hiiii, I select "March" we get 31 days in sequence like 1,2,3,4..........31 with their respective 'days' like Mon,Tue.....Sun . Now 31 field should be created with Label name Mon 1 June,Tue 2 June etc....... This should happen with all 12 month. Thanks Jack this is rather tricky to do via the XML files. More effective is to overwrite fields_view_get method (tested for OE 7.0), like so: def fields_view_get(self, cr, uid, view_id=None, view_type=None, context=None, toolbar=False, submenu=False): """ overwriting to set dynamic label on the field reading_normal. """ res = super(meter_reading_electricity, self).fields_view_get( cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) if view_type == 'form': doc = etree.XML(res['arch']) nodes = doc.xpath("//field[@name='reading_normal']") nodes[0].set('string', 'My dynamic label') res['arch'] = etree.tostring(doc)
https://www.odoo.com/forum/help-1/question/how-to-create-field-with-dynamic-label-name-23284
CC-MAIN-2017-09
refinedweb
177
52.97
There are two ways numbers are represented internally - integers and floating point numbers. Even though the numbers 1 and 1.0 have the same value their internal representation are very different. Computations with integers are exact, whereas those that involve floating point numbers are not. The accuracy of a floating point computation depends on the precision of the numbers used. Greater the precision, the more accurate the result. But there is limit to the precision of floating numbers. The precision is limited to the number of bits used. 32-bit floating point numbers have lower precision than 64-bit numbers. There is also a limit to how big or how small a floating point number you can represent. For a 32-bit representation the range is (+/-) 3.4E38 and for 64-bit representation the range is (+/-) 1.8E308. There is also a limit to the range of integers that you can represent. With 32 bits the range is -231 to (231 - 1). In mixed operations, those that involve both integers and floating numbers, integers are converted to floating point numbers and the computation performed. Careful: consider this expression: 3.5 + (6/4). The result is 4.5 and not 5.0 as you would expect because the (6/4) is computed as an integer division which truncates the fractional portion of the quotient. For even larger integer numbers Python has a third numeric type called a long int. The long int is not restricted by the number of bits and can expand to the limit of the available memory. To indicate that a number should be represented as a long int append an upper case ( L ). x = 12345678987654321L You can explicitly convert numbers of one type to another with built-in functions that Python provides: x = 123 y = float (x) # y = 123.0 z = 34.89 w = int (z) # w = 34 p = 75 q = long (p) # q = 75LNote that when you convert to int, the function truncates instead of rounding. There are lots of useful functions in the Math Library. To use this library the first statement in your program must be import mathThe Math Library not only has functions but also useful constants like π and e. To use the functions or the constants in your program you must apply the dot operator. The general syntax for usage is math.function() or math.constant. The table below gives just a subset of all the functions available. There are computations that require you to generate random numbers. Python provides a pseudo random number generator. The word pseudo in this context means that the random number generator is deterministic and after a certain cycle of generating random numbers it starts repeating that cycle. However, for most simple computations the pseudo random number generator works fine since the cycle length is extremely large. All of the random number generating functions comes in a module called random and has to be imported in the program to be used. Your first line of code should read: import randomTo use the functions you must use the dot operator. The general usage is random.function(). The table below gives a subset of the functions that are available in the random module. Here are some examples of using the random number generator: # Random float x in the range 0.0 <= x < 1.0 x = random.random() # x = 0.386265456797 # Random integer in the range 7 to 23 inclusive x = random.randint(7, 23) # x = 18 # Random float x in the range -1.0 <= x < 1.0 x = random.uniform (-1.0, 1.0) # x = -0.0742003025108 # Choose a random number from 1 to 100 that is divisible by 3 x = random.randrange(3, 100, 3) # x = 30 # Choose a random element from a sequence seq = ['a', 'e', 'i', 'o', 'u'] x = random.choice(seq) # x = 'o' # Choose 2 elements from a population x = random.sample (seq, 2) # x = ['u', 'e'] # Shuffle a sequence random.shuffle (seq) # seq = ['e', 'a', 'o', 'i', 'u']
http://www.cs.utexas.edu/~mitra/csSummer2011/cs303/lectures/math.html
CC-MAIN-2013-48
refinedweb
665
67.86
Hi there, I have a bit of an odd problem, which I’m hoping someone can help me out with. I’m working on a game that uses many different particle effects. Some are created using keypresses (using DirectObject.accept), while some are created in tasks. The following code, which can be called by a keypress or a task, is used to create all of them: def showEffect(type, color1, color2, position): effect = self.particleFactory.createParticleEffect (type, color1, color2) effect.reparentTo(render) effect.start() effect.setPos(position) ParticleFactory is a class that takes in a number of parameters and uses them create a new instance of a particle effect. Some code snippets from it: class ParticleFactory: def createParticleEffect(self, type, color1, color2): if type == 'ball': return self.createBall(color1, color2) ... def createBall(self, color1, color2): ball = ParticleEffect() ball.reset() ... # set up particles ... return ball The problem I’m running into is that particle effects generated when the showEffect function is called by a task don’t seem to be appearing on the screen, while those generated when the function is called by a keypress do appear. The showEffect function is called with the identical parameters regardless of whether it is triggered by a task or a keypress, so I know the problem is somewhere inside the function. I have tried creating the particle effect when I start running and then just moving it with a task or keypress, and that seems to work. The problem only starts when I try to create a new one with a task. Does anyone know why I can’t seem to create particle effects inside of a task? Thanks
https://discourse.panda3d.org/t/problem-creating-particle-effects-in-tasks/1974
CC-MAIN-2022-27
refinedweb
275
54.12
No project description provided Project description pyPhpTree module Module for Python 3. Tiny parser of PHP source code, which finds lines with class/function/namespace/trait declarations. It reads PHP code only inside <? ... ?> tags (any count of fragments in one file), and outside of /* ... */ and // ... comments, and outside of single/double-quoted strings (multi-line strings supported, escape backslash supported), and outside of heredoc/herenow blocks. API Function get_headers(filename, lines) finds all entities, in given “lines” list, and gets dicts: { 'line': int, # 0-based line index, where name found 'col': int, # 0-based position in line, where name found 'level': int, # 0-based level of item. each item of level K+1 # is nested into (nearest upper) item of level K 'name': str, # name of entity # empty for anonymous funcs 'kind': str, # "class", "function", "namespace", "trait" } It’s generator (yield), so to get list, use list(get_headers(...)). 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. Source Distribution pyphptree-1.0.3.tar.gz (9.8 kB view hashes)
https://pypi.org/project/pyphptree/
CC-MAIN-2022-05
refinedweb
190
55.84
22 December 2011 06:57 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The new plant will double the producer’s current IPA capacity to 60,000 tonnes/year, the source said. ISU Chemical, the smaller of the two IPA producers in Market participants said the company is likely to try growing its exports to the key Chinese market, but is likely to face strong competition from domestic producers. “IPA prices have been weak this year because of the ample supply of competitively priced local product,” a source based in “Next year, the market may continue to be tough because of economic uncertainty,’’ the source added. In For more on isoprop
http://www.icis.com/Articles/2011/12/22/9518671/south-koreas-isu-chemical-to-start-up-ipa-line-next.html
CC-MAIN-2015-14
refinedweb
110
58.82
Recursion in Functional JavaScriptBy M. David Green You may have come across references to recursive functions while programming in JavaScript. You may even have tried to construct (or deconstruct) a few yourself. But you probably haven’t seen a lot of examples of effective recursion in the wild. In fact, other than the exotic nature of this approach, you may not have considered when and where recursion is useful, or how dangerous it can be if used carelessly. What is Recursion Good For? Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. Most loops can be rewritten in a recursive style, and in some functional languages this approach to looping is the default. More from this author However, while JavaScript’s functional coding style does support recursive functions, we need to be aware that most JavaScript compilers are not currently optimized to support them safely. Recursion is best applied when you need to call the same function repeatedly with different parameters from within a loop. While it can be used in many situations, it is most effective for solving problems involving iterative branching, such as fractal math, sorting, or traversing the nodes of complex or non-linear data structures. One reason that recursion is favored in functional programming languages is that it allows for the construction of code that doesn’t require setting and maintaining state with local variables. Recursive functions are also naturally easy to test because they are easy to write in a pure manner, with a specific and consistent return value for any given input, and no side effects on external variable states. Looping The classic example of a function where recursion can be applied is the factorial. This is a function that returns the value of multiplying a number again and again by each preceding integer, all the way down to one. For example, the factorial of three is: 3 × 2 × 1 = 6 The factorial of six is: 6 × 5 × 4 × 3 × 2 × 1 = 720 You can see how quickly these results get big. You can also see that we’re repeating the same behavior over and over. We take the result of one multiplication operation and multiply it again by one less than the second value. Then we do that again and again until we reach one. Using a for loop, it’s not difficult to create a function that will perform this operation iteratively until it returns the correct result: var factor = function(number) { var result = 1; var count; for (count = number; count > 1; count--) { result *= count; } return result; }; console.log(factor(6)); // 720 This works, but it isn’t very elegant from a functional programming perspective. We have to use a couple of local variables that maintain and track state in order to support that for loop and then return a result. Wouldn’t it be cleaner if we could ditch that for loop, and take a more functional JavaScript approach? Recursion We know JavaScript will let us write functions that take functions as arguments. So what if we want to use the actual function we’re writing and execute it in the context of running it. Is that even possible? You bet it is! For example, take the case of a simple while loop like this: var counter = 10; while(counter > 0) { console.log(counter--); } When this is done, the value of counter has been changed, but the loop has done its job of printing out each value it held as we slowly sucked the state out of it. A recursive version of the same loop might look more like this: var countdown = function(value) { if (value > 0) { console.log(value); return countdown(value - 1); } else { return value; } }; countdown(10); Do you see how we’re calling the countdown function right inside the definition of the countdown function? JavaScript handles that like a boss, and just does what you would hope. Every time countdown is executed, JavaScript keeps track of where it was called from, and then works backward through that stack of function calls until it’s finished. Our function has also avoided modifying the state of any variables, but has still taken advantage of a passed in value to control the recursion. Getting back to our factorial case, we could rewrite our earlier function like this to use recursion: var factorial = function(number) { if (number <= 0) { // terminal case return 1; } else { // block to execute return (number * factorial(number - 1)); } }; console.log(factorial(6)); // 720 Writing code this way allows us to describe the whole process in a stateless way with no side effects. Also worth noticing is the way we test the value of the argument being passed in to the function first thing, before doing any calculations. We want any functions that are going to call themselves to exit quickly and cleanly when they get to their terminal case. For a factorial calculated this way, the terminal case comes when the number passed in is zero or negative (we could also test for negative values and return a different message, if we so desired). Tail Call Optimization One problem with contemporary implementations of JavaScript is that they don’t have a standard way to prevent recursive functions from stacking up on themselves indefinitely, and eating away at memory until they exceed the capacity of the engine. JavaScript recursive functions need to keep track of where they were called from each time, so they can resume at the correct point. In many functional languages, such as Haskell and Scheme, this is managed using a technique called tail call optimization. With tail call optimization, each successive cycle in a recursive function would take place immediately, instead of stacking up in memory. Theoretically, tail call optimization is part of the standard for ECMAScript 6, currently the next version of JavaScript, however it has yet to be fully implemented by most platforms. Trampoline Functions There are ways to force JavaScript to perform recursive functions in a safe manner when necessary. For example, it’s possible to construct a custom trampoline function to manage recursive execution iteratively, keeping only one operation on the stack at a time. Trampoline functions used this way can take advantage of JavaScript’s ability to bind a function to a specific context, so as to bounce a recursive function up against itself, building up results one at a time until the cycle is complete. This will avoid creating a deep stack of operations waiting to be performed. In practice, making use of trampoline functions usually slows down performance in favor of safety. Additionally, much of the elegance and readability we obtain by writing our functions in a recursive manner gets lost in the code convolutions necessary to make this approach work in JavaScript. If you’re curious, I encourage you to read more about this concept, and share your thoughts in the discussion below. You might start with a short thread on StackOverflow, then explore some essays by Don Taylor and Mark McDonnell that dig deeper into the ups and downs of trampolines in JavaScript. We’re Not There Yet Recursion is a powerful technique that’s worth knowing about. In many cases, recursion is the most direct way to solve a complex problem. But until ECMAScript 6 is implemented everywhere we need it with tail call optimization, we will need to be very careful about how and where we apply recursion.
https://www.sitepoint.com/recursion-functional-javascript/
CC-MAIN-2017-34
refinedweb
1,246
57.61
fredrikj.net / blog / Modular forms in Arb October 8, 2014 There's a saying (attributed to Martin Eichler) that there are five elementary arithmetical operations: addition, subtraction, multiplication, division, and modular forms. The first four have been well-supported in Arb for some time, and the fifth is just now coming along! More precisely, the git trunk of Arb now supports arbitrary-precision rigorous-interval evaluation of two famous modular forms: the Dedekind eta function, and Klein's j-invariant. It also supports working with modular transformations and evaluating theta sums. With these building blocks, one can easily implement other modular forms such as Eisenstein series (and indeed, my plan is to provide such functions in the future, as well as elliptic functions). Geometrically, modular forms are fractals, and thus lend themselves to making pretty pictures. Arb doesn't really have a plotting interface just yet, but it wasn't much work to write a program that converts function values to RGB values and dumps them to a .ppm bitmap, after translating the domain coloring code in mpmath to C (I might clean up this code and put it in the library later): The j-invariant on the complex interval $[-2, 2] + [0, 1]i$. Click for 8192x2048 resolution. The Dedekind eta function on the complex interval $[0, 24] + [0, 1]i$. Click for 24576x1024 resolution. These high-resolution plots (16 and 25 megapixels respectively) were rendered at 128-bit working precision, and took 5-10 minutes each on a single core (parallelization should be trivial, but I didn't bother as I only had a single-core system when rendering these). Thus, at fairly low precision, Arb manages something like 50,000 function evaluations per second. This is 1-2 orders of magnitude faster than mpmath, and even more when getting close to the real axis (where mpmath currently slows down exponentially). Indeed, with arbitrary precision and a robust evaluation algorithm comes the possibility to do ultra deep zooms. Below are two plots with a magnification factor of 1 googol $= 10^{100}$: The phase of the Dedekind eta function on the complex interval $[\sqrt{2}, \sqrt{2} + 10^{-101}] + [0, 2.5 \times 10^{-102}]i$. Click for 4096x1024 resolution. The j-invariant on the complex interval $[\sqrt{13}, \sqrt{13} + 10^{-101}] + [0, 2.5 \times 10^{-102}]i$. Click for 4096x1024 resolution. These 4-megapixel renders took 25 minutes each (on one core) and were done at a working precision of 1024 bits. Note that there are sampling artifacts if you look closely at these plots. This problem can be avoided with subsampling. In fact, with ball/interval arithmetic, you could generate provably correct plots by evaluating the function on each pixel as a whole (viewed as a rectangle in the complex plane), rather than on infinitesimal sample points, and adaptively subdividing until you can determine the correct averaged color for each pixel. But that is a whole different project! Modular forms satisfy myriads of functional relations, and tend to have interesting values at special points. For example, as the Wikipedia article about the Dedekind eta function points out, the j-invariant and the eta function are related as $$j(\tau) = \left( \left(\frac{\eta(\tau)}{\eta(2\tau)}\right)^8 + 2^8 \left(\frac{\eta(2\tau)}{\eta(\tau)}\right)^{16} \right)^3$$ and the j-invariant has the special value $$j\left(\frac{1+\sqrt{-163}}{2}\right) = -640320^3$$ which is related to the fact that $e^{\pi\sqrt{163}} \approx 640320^3+743.99999999999925\dots$ is amazingly close to an integer. Here is a short program that tests these identities. Using ball/interval arithmetic, we expect different formulas for the same mathematical value to output intervals that overlap with each other, and of course also contain the exact value. The program also measures the execution time for the respective function: #include "acb_modular.h" #include "profiler.h" int main() { acb_t tau, eta1, eta2, j, t, u, ans; long prec; acb_init(tau); acb_init(eta1); acb_init(eta2); acb_init(j); acb_init(t); acb_init(u); acb_init(ans); for (prec = 64; prec <= 2e6; prec *= 4) { acb_set_si(tau, -163); acb_sqrt(tau, tau, prec); acb_add_ui(tau, tau, 1, prec); acb_mul_2exp_si(tau, tau, -1); printf("prec = %ld\n", prec); printf("j: "); TIMEIT_START acb_modular_j(j, tau, prec); TIMEIT_STOP printf("eta: "); TIMEIT_START acb_modular_eta(eta1, tau, prec); TIMEIT_STOP acb_mul_2exp_si(tau, tau, 1); acb_modular_eta(eta2, tau, prec); acb_div(t, eta1, eta2, prec); acb_pow_ui(t, t, 8, prec); acb_inv(u, t, prec); acb_mul(u, u, u, prec); acb_mul_2exp_si(u, u, 8); acb_add(t, t, u, prec); acb_pow_ui(t, t, 3, prec); acb_set_si(ans, -640320); acb_pow_ui(ans, ans, 3, 64); printf("overlap: %d, containment: %d\n", acb_overlaps(j, t), acb_contains(j, ans) && acb_contains(t, ans)); acb_printd(j, 25); printf("\n"); acb_printd(t, 25); printf("\n"); printf("\n"); } acb_clear(tau); acb_clear(eta1); acb_clear(eta2); acb_clear(j); acb_clear(t); acb_clear(u); acb_clear(ans); flint_cleanup(); } The program outputs the following: prec = 64 j: cpu/wall(s): 6.7e-06 7.18e-06 eta: cpu/wall(s): 6.1e-06 6.28e-06 overlap: 1, containment: 1 (-262537412640767998.515625 - 9.583016555401524595206054e-12j) +/- (9.25, 3.81e-07j) (-262537412640767999 - 0.2065797845092608606506644j) +/- (78.9, 64.3j) prec = 256 j: cpu/wall(s): 1.1e-05 1.24e-05 eta: cpu/wall(s): 1e-05 1.09e-05 overlap: 1, containment: 1 (-262537412640768000 + 6.175588219646460466328569e-68j) +/- (1.8e-57, 9.07e-65j) (-262537412640768000 - 5.265609339283016719999099e-60j) +/- (1.26e-56, 1.02e-56j) prec = 1024 j: cpu/wall(s): 3e-05 3.14e-05 eta: cpu/wall(s): 3.6e-05 3.66e-05 overlap: 1, containment: 1 (-262537412640768000 - 6.191850416649493269947559e-299j) +/- (1.16e-288, 5.89e-296j) (-262537412640768000 + 2.416555834579265876442343e-290j) +/- (7.94e-288, 6.47e-288j) prec = 4096 j: cpu/wall(s): 0.00024 0.000248 eta: cpu/wall(s): 0.00036 0.00038 overlap: 1, containment: 1 (-262537412640768000 - 4.985688509409972576666983e-1224j) +/- (2e-1213, 1.51e-1220j) (-262537412640768000 + 8.757024093526885406242355e-1216j) +/- (1.34e-1212, 1.09e-1212j) prec = 16384 j: cpu/wall(s): 0.0024 0.00249 eta: cpu/wall(s): 0.005 0.0052 overlap: 1, containment: 1 (-262537412640768000 - 5.476336188603508228685505e-4923j) +/- (1.75e-4912, 1.37e-4919j) (-262537412640768000 + 6.406024267686023293746183e-4914j) +/- (1.18e-4911, 9.61e-4912j) prec = 65536 j: cpu/wall(s): 0.022 0.0235 eta: cpu/wall(s): 0.056 0.0571 overlap: 1, containment: 1 (-262537412640768000 - 4.637927148537148503405785e-19720j) +/- (1.04e-19708, 8.59e-19716j) (-262537412640768000 + 9.510026173830554939511924e-19711j) +/- (7e-19708, 5.71e-19708j) prec = 262144 j: cpu/wall(s): 0.25 0.266 eta: cpu/wall(s): 0.6 0.616 overlap: 1, containment: 1 (-262537412640768000 + 1.342790082833536950147581e-78904j) +/- (1.29e-78893, 1.18e-78900j) (-262537412640768000 + 1.04058336851956512210966e-78895j) +/- (6.82e-78893, 5.56e-78893j) prec = 1048576 j: cpu/wall(s): 2.06 2.122 eta: cpu/wall(s): 4.83 4.997 overlap: 1, containment: 1 (-262537412640768000 + 5.517708769240461892678295e-315644j) +/- (3.1e-315633, 3.4e-315640j) (-262537412640768000 + 6.105172555794133440925373e-315635j) +/- (2.08e-315632, 1.7e-315632j) Notably, evaluation of modular forms is very fast at high precision: even a million bits just takes a couple of seconds (this is due to the rapid convergence of the theta function series).
http://fredrikj.net/blog/2014/10/modular-forms-in-arb/
CC-MAIN-2017-13
refinedweb
1,193
66.33
#include <Spectrum.h> Inherits Marsyas::MarSystem. Computes the complex spectrum (N/2+1 points) of the input window using the Fast Fourier Transform (FFT). The output is a N-sized column vector (where N is the size of the input audio vector), using the following format: [Re(0), Re(N/2), Re(1), Im(1), Re(2), Im(2), ..., Re(N/2-1), Im(N/2-1)] Note that the DC and Nyquist frequencies only have real part, and are output as the two first coefficients in the vector. Overall, the output spectrum has N/2+1 unique points, corresponding to the positive half of the complex spectrum. Definition at line 50 of file Spectrum.h.
http://marsyas.info/docs/sourceDoc/html/classMarsyas_1_1Spectrum.html
crawl-003
refinedweb
116
63.9
Let: a = 5; that distinguishes it from the others, for example, in the previous code the variable identifiers were a, b and result, but we could have called the variables any names we wanted to invent, as long as they were valid identifiers. Another rule that you have to consider when inventing your own identifiers is that they cannot match any keyword of the C++ language nor your compiler's specific ones, which are reserved keywords. The standard reserved keywords are: asm, auto, bool, break, case, catch, char, class, const, const_cast,.. int a; float mynumber; be signed, therefore instead of the second declaration above we could have written: int MyAccountBalance;; } 4 Do not worry if something else than the variable declarations themselves looks a bit strange to you. You will see the rest in detail in coming sections.; } 6). // my first string #include <iostream> #include <string> using namespace std; int main () { string mystring = "This is a string"; cout << mystring; return 0; }; } This is the initial string content This is a different string content For more details on C++ strings, you can have a look at the string class reference.
http://www.cplusplus.com/doc/tutorial/variables.html
crawl-001
refinedweb
189
56.63
-- TransformListComp #-} module Manatee.Toolkit.General.List where import Control.Arrow import Control.Monad import Data.List import Data.Maybe import Data.Monoid import Manatee.Toolkit.General.Basic -- | Return element of list with given index. (?!) :: [a] -> Int -> Maybe a [] ?! _ = Nothing xs ?! n | n < 0 = Nothing | n >= length xs = Nothing | otherwise = listToMaybe . drop n $ xs -- | Intersect element with list from end, don't including front or middle element. -- Return null if haven't intersection element. intersectEnd :: Ord a => [a] -> [a] -> [a] intersectEnd xs ys = reverse $ intersectFront (reverse xs) (reverse ys) -- | Intersect element with list from front, don't including end or middle element. -- Return null if haven't intersection element. intersectFront :: Ord a => [a] -> [a] -> [a] intersectFront xs ys = [x | (x,y) <- zip xs ys, then takeWhile by x == y] -- | Delay list with given start index. delay :: Int -> [a] -> [Int] delay n (_:xs) = n : delay (n + 1) xs delay _ _ = [] -- | Index of list listIndex :: [a] -> [Int] listIndex = delay 0 -- | Pair with list index. pairPred :: [a] -> [(a, Int)] pairPred xs = zip xs $ listIndex xs -- | Different two list, and two lists must have same length. -- otherwise throw a error. different :: Ord a => [a] -> [a] -> [a] different (x:xs) (y:ys) | x == y = different xs ys | otherwise = x : different xs ys different [] [] = [] different _ _ = error "different: lists not the same length!" -- | Do action when list not empty. unlessNull :: [a] -> IO () -> IO () unlessNull = unless . null -- | not . null has :: [a] -> Bool has = not . null -- | Head monad list. headM :: Monad m => m [a] -> m a headM = liftM head -- | Last monad list. lastM :: Monad m => m [a] -> m a lastM = liftM last -- | ConcatM. concatM :: Monad m => m [a] -> m [a] -> m [a] concatM = liftM2 (++) -- | Replace n'th element (count from 0) in `xs` to `x` replaceAt :: Int -> [a] -> a -> [a] replaceAt n xs x = take n xs ++ x : drop (n + 1) xs -- | Split list with given condition. splitWith :: (a -> Bool) -> [a] -> [[a]] splitWith _ [] = [] splitWith f xs = fst tuple : splitWith f (dropWhile f $ snd tuple) where tuple = break f xs -- | concatMapM. concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b] concatMapM f xs = liftM concat $ forM xs f -- | Like find, but works with monadic computation instead of pure function. -- In expression `find FUNCTION list`, if FUNCTION is "IO Bool", you can use -- `findM FUNCTION list` to instead. findM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a) findM _ [] = return Nothing findM f (x:xs) = ifM (f x) (return $ Just x) (findM f xs) -- | Apply two monad function with list. -- And return new monad tuples list. apply2M :: Monad m => [a] -> (a -> m b) -> (a -> m c) -> m [(b, c)] apply2M xs f g = forM xs (\x -> zipM' (f x) (g x)) -- | Apply two function with list. -- And return new tuples list. apply2 :: [a] -> (a -> b) -> (a -> c) -> [(b, c)] apply2 xs f g = map (f &&& g) xs -- | Partition list. partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a]) partitionM _ [] = return ([], []) partitionM f (x:xs) = liftM2 mappend (ifM (f x) (return ([x], [])) (return ([], [x]))) (partitionM f xs) -- | Like `init`, but accept empty list. init_ [] = [] init_ xs = init xs -- | Like `foldl1`, but accept empty list. foldl1_ _ [] = [] foldl1_ f xs = foldl1 f xs -- | Find next element. findNext :: (a -> Bool) -> [a] -> Maybe a findNext x = listToMaybe . drop 1 . dropWhile (not . x) -- | Find next cycle. findNextCycle :: (a -> Bool) -> [a] -> Maybe a findNextCycle _ [] = Nothing findNextCycle f list = case dropWhile (not . f) list of [] -> Nothing -- `Nothing` when element not found in list [_] -> Just $ head list -- Get head when element at last of list ls -> listToMaybe $ drop 1 ls -- Otherwise get next element in list -- | Find previous cycle. findPrevCycle :: (a -> Bool) -> [a] -> Maybe a findPrevCycle _ [] = Nothing findPrevCycle f list | length dropList == length list = Nothing -- `Nothing` when element not found in list | null dropList = Just $ last list -- Get last when element at first position of list | otherwise = Just $ last dropList -- Otherwise get previous element in list where dropList = takeWhile (not . f) list -- | Delete at. deleteAt :: Int -> [a] -> [a] deleteAt _ [] = [] deleteAt i xs | i < 0 = [] | i >= length xs = [] | otherwise = (\(a, b) -> a ++ tail b) (splitAt i xs) -- | Get last one. getLast :: [a] -> Maybe a getLast [] = Nothing getLast xs = Just $ last xs -- | Get first one. getFirst :: [a] -> Maybe a getFirst [] = Nothing getFirst xs = Just $ head xs -- | Zip with list index. zipWithIndex :: [a] -> (a -> Int -> c) -> [c] zipWithIndex xs f = zipWith f xs [0..] -- | Zip with list index. zipWithIndexM :: Monad m => [a] -> (a -> Int -> m c) -> m [c] zipWithIndexM xs f = zipWithM f xs [0..] -- | Zip with list index. zipWithIndexM_ :: Monad m => [a] -> (a -> Int -> m c) -> m () zipWithIndexM_ xs f = zipWithM_ f xs [0..] -- | Like 'concatMap', but don't concat last one. addMap :: ([a] -> [a]) -> [[a]] -> [a] addMap _ [] = [] addMap _ [x] = x addMap f xs = concatMap f (init xs) ++ last xs -- | Like 'insert' but just insert unique element. insertUnique :: Ord a => a -> [a] -> [a] insertUnique x xs | x `elem` xs = xs | otherwise = insert x xs
http://hackage.haskell.org/package/manatee-core-0.0.1/docs/src/Manatee-Toolkit-General-List.html
CC-MAIN-2015-48
refinedweb
817
73.78
11 October 2012 05:36 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The buyer was Chinese trader Unipec, they said. The cargo for loading on 29-31 October was done at a premium of $26/tonne (€20/tonne) to In its previous tender, BPCL sold two naphtha cargoes totalling 46,000 tonnes for loading in October. BPCL awarded an 11,000-tonne cargo for loading from Haldia on 10-14 October to Trafigura, at a discount of $10/tonne to The cargo contained high amount of methyl tertiary butyl ether (MTBE), which is used as an additive to boost octane levels in gasoline. The remaining 35,000-tonne cargo for loading from Mumbai on 22-24 October was awarded to Japanese trading house ITOCHU at a premium of $34
http://www.icis.com/Articles/2012/10/11/9602928/Indian-BPCL-sells-30000-tonnes-naphtha-for-end-October.html
CC-MAIN-2014-52
refinedweb
129
56.59
Le 15 avr. 04, à 18:01, jastrachan@mac.com a écrit : > ..?... Dunno about javax.sql.DataSource support, I'll have to check. ConnectionProvider does not exist yet, I just made it up with the following idea: public class ConnectionProvider { // Groovy scripts which need a Connection will use this to get // it from the Cocoon pool public Connection getConnection(String connectionName); // then, once the Groovy script has been executed, ScriptGenerator // calls this to return all connections provided by getConnection to the pool public void releaseConnections() } In this way, the Groovy script can access any Connections that are configured, and does not have to care about releasing them. It's easy to implement in case we don't have DataSource support. -Bertrand
http://mail-archives.apache.org/mod_mbox/cocoon-dev/200404.mbox/%3C397A40AC-8EF8-11D8-844A-000A95AF004E@apache.org%3E
CC-MAIN-2016-26
refinedweb
121
55.24
[] kind <required> name <required> schemas <required> server_type undef transport 'HTTP' Some string which is referring. Most server implementations show some problems. Also, servers may produce responses using their own namespaces (like for error codes). When you know which server you are talking to, the quirks of the specific server type can be loaded. Read more in the "Supported servers" in XML::Compile::SOAP.. [3.06] prefix the service name before the operation name, to make it really unique. A # is used as separator.. [3.14] You may provide a XML::Compile::Transport object as well. Its compileClient() will be called for you.. TREE to get more details about the element types mentioned in this structure. example: use Data::Dumper; $Data::Dumper::Indent = 1; $Data::Dumper::Quotekeys = 0; print Dumper $op->parsedWSDL;
http://search.cpan.org/dist/XML-Compile-SOAP/lib/XML/Compile/SOAP/Operation.pod
CC-MAIN-2018-17
refinedweb
131
68.97
Opened 8 years ago Closed 8 years ago #5658 closed bug (fixed) Strict bindings are wrongly floated out of case alternatives. Description With this program: {-# LANGUAGE MagicHash, BangPatterns #-} module Broken where import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U broken :: V.Vector (U.Vector Double) -> Int -> Int -> IO Double broken !arrs !ix !len = case ix >= len of True -> error "sorry" False -> return ((arrs `V.unsafeIndex` ix) `U.unsafeIndex` ix) Note that both indexing operations are within the 'False' branch, and the test is intended to check that the indexing is indeed safe. Sadly, the simplifier floats the inner indexing operation outside the bounds check: broken1 broken1 = \ arrs_s185 ix_s18a len_s18j eta_s18o -> let { Vector ipv_s18e _ ipv2_s18d ~ _ <- arrs_s185 } in let { I# ipv3_s18f ~ _ <- ix_s18a } in let { __DEFAULT ~ sat_s18D <- +# ipv_s18e ipv3_s18f } in let { (# x_s18p #) ~ _ <- indexArray# ipv2_s18d sat_s18D } in *** NO! *** let { I# ipv4_s18m ~ _ <- len_s18j } in case >=# ipv3_s18f ipv4_s18m of _ { False -> let { sat_s18G sat_s18G = let { Vector rb_s18v _ rb2_s18u ~ _ <- x_s18p `cast` ... } in let { __DEFAULT ~ sat_s18J <- +# rb_s18v ipv3_s18f } in let { __DEFAULT ~ sat_s18K <- indexDoubleArray# rb2_s18u sat_s18J } in D# sat_s18K } in (# eta_s18o, sat_s18G #); True -> broken2 `cast` ... } If it was a lazy binding it would have been ok to float it, but it's not. This issue is probably causing other problems in GHC, maybe #5085. This is broken in the head as well as 7.2. Change History (22) comment:1 Changed 8 years ago by comment:2 Changed 8 years ago by Adding the can_fail to all the indexing primps fixes the problem. I can push my patch when validate works on OSX again, it's broken now. comment:3 Changed 8 years ago by commit 657773c8e59917fda05ee08065ec566aebb50a5f Author: Ben Lippmeier <benl@ouroborus.net> Date: Tue Nov 29 16:38:33 2011 +1100 Fix #5658: mark all array indexing primops as can_fail If they're not marked as can_fail, then they are floated out of case expressions that check whether the indices are in-bounds, causing immense suffering. compiler/prelude/primops.txt.pp | 112 +++++++++++++++++++++++++++++++++++++- 1 files changed, 109 insertions(+), 3 deletions(-) comment:4 Changed 8 years ago by I think we only need to mark the indexBlahArray# operations with can_fail, the readBlahArray# and writeBlahArray# are already fine: they are already marked as having side effects, so they will never be evaluated when they shouldn't be. comment:5 Changed 8 years ago by Hrm. I marked them all as can_fail because it's true that they can fail, and now the function primOpCanFail :: Name -> Bool should return the correct information for each primop. If we want to say "If a primop is marked as has_side_effects then GHC won't do anything different if it's also marked as can_fail", then this is a property of the compiler rather than a property of the primop. The only place I can find the can_fail and has_side_effects flags being used is via the following function: primOpOkForSpeculation :: PrimOp -> Bool primOpOkForSpeculation op = not (primOpHasSideEffects op || primOpOutOfLine op || primOpCanFail op) From this, it looks like the can_fail flag is redundant anyway. We could replace all occurrences of can_fail in the primops.txt.pp file with has_side_effects and still get the same result. What do you want to do? comment:6 Changed 8 years ago by I think of has_side_effects as implying can_fail, but not vice versa. - A primop that is neither can_failnor has_side_effectscan be executed speculatively, any number of times - A primop that is marked can_failcannot be executed speculatively, but it can be repeated (why would you want to do that? Perhaps it might enable some eta-expansion, if you can prove that the lambda is definitely applied at least once. I guess we don't currently do that). - A primop that is marked has_side_effectscan be neither speculated nor repeated; it must be executed exactly the right number of times. This is all moot since as you point out we don't currently take advantage of can_fail && !has_side_effects. comment:7 Changed 8 years ago by commit 56a05294f3a94a6826c8eaaef6c9946d42c71eaf Author: Simon Peyton Jones <simonpj@microsoft.com> Date: Mon Dec 12 11:16:49 2011 +0000 Add comments about the meaning of can_fail and has_side_effects Taken from Trac #5658 compiler/prelude/PrimOp.lhs | 136 ++++++++++++++++++++++++-------------- compiler/prelude/primops.txt.pp | 5 +- 2 files changed, 89 insertions(+), 52 deletions(-) comment:8 Changed 8 years ago by Ben: I think this ticket is fixed, but it'd be good to have a test case if possible. Could you think about concocting one? Ideally without depending on vector. If it's hard, just close the ticket. Simon comment:9 Changed 8 years ago by comment:10 Changed 8 years ago by It turns out that this fix can decrease performance because now, index*Array# operations can't be eliminated or moved into cases. For an example of mine, we generated this code before: $weq_loop0_s1Ty = \ (ww_s1Sv :: Int#) (ww1_s1Sz :: Int#) -> case >=# ww_s1Sv ipv1_s1K9 of _ { False -> case >=# ww1_s1Sz sc1_s1VP of _ { False -> case indexIntArray# ipv2_s1Ka (+# ipv_s1K8 ww_s1Sv) of wild_a1rf { __DEFAULT -> case indexIntArray# sc2_s1VQ (+# sc_s1VO ww1_s1Sz) of wild3_X1rU { __DEFAULT -> case ==# wild_a1rf wild3_X1rU of _ { False -> False; True -> $weq_loop0_s1Ty (+# ww_s1Sv 1) (+# ww1_s1Sz 1) } } }; True -> False }; True -> >=# ww1_s1Sz sc1_s1VP }; And now we generate this: $weq_loop0_s1TF = \ (ww_s1SC :: Int#) (ww1_s1SG :: Int#) -> case >=# ww_s1SC ipv1_s1Kg of _ { False -> case indexIntArray# ipv2_s1Kh (+# ipv_s1Kf ww_s1SC) of wild_a1rg { __DEFAULT -> case >=# ww1_s1SG sc1_s1VW of _ { False -> case indexIntArray# sc2_s1VX (+# sc_s1VV ww1_s1SG) of wild3_X1rU { __DEFAULT -> case ==# wild_a1rg wild3_X1rU of _ { False -> False; True -> $weq_loop0_s1TF (+# ww_s1SC 1) (+# ww1_s1SG 1) } }; True -> False } }; True -> case >=# ww1_s1SG sc1_s1VW of _ { False -> case indexIntArray# sc2_s1VX (+# sc_s1VV ww1_s1SG) of _ { __DEFAULT -> False }; True -> True } }; I'm not sure if this is the intended semantics of can_fail. If so, we might want something weaker than can_fail for things that shouldn't be executed speculatively but are ok to not executed at all. comment:11 Changed 8 years ago by Actually, the good code looked like this (sorry, got my loops mixed up): $weq_loop0_s22g = \ (ww_s21d :: Int#) (ww1_s21h :: Int#) -> case >=# ww_s21d ipv1_s1QZ of _ { False -> case >=# ww1_s21h sc1_s24C of _ { False -> case ==# (indexIntArray# ipv2_s1R0 (+# ipv_s1QY ww_s21d)) (indexIntArray# sc2_s24D (+# sc_s24B ww1_s21h)) of _ { False -> False; True -> $weq_loop0_s22g (+# ww_s21d 1) (+# ww1_s21h 1) }; True -> False }; True -> >=# ww1_s21h sc1_s24C }; Not that it matters. comment:12 Changed 8 years ago by Incidentally, am I correct in assuming that the reason this has only shown up now is because of the fixes to #4978 which made primops appear cheaper (too cheap, it seems)? We shouldn't really float array accesses past bounds checks anyway because if we do, we will be doing unnecessary work if the check fails. If this is so, then would it make sense to revert the patch from #4978 that caused this and remove the can_fail annotations again? Note that #5623 is another bug caused by primops being too cheap. This change seems to have a lot of unintended knock-on effects. comment:13 Changed 8 years ago by To be clear, the changes in #4978 were only to GHC's perception of the code size of a primop, not its runtime cost. It was completely wrong before, charging as much for the code size of an inline primop (typically one instruction) as for a lambda (tens of instructions and an info table). If anything, we're still overcharging for inline primops. But, this is a delicate area and making any change, whether correct or not, is likely to upset heuristics elsewhere. Rather than going back to the definitely-wrong behaviour before, I suggest we find out which heuristics are now wrong and fix them. I think you're right about wanting a weaker version of can_fail, incidentally. comment:14 Changed 8 years ago by Oh, I see, I thought that the patches also affected runtime costs. But can we agree that floating array accesses (or any primops, for that matter) out of conditionals is a bug even if those accesses aren't marked as can_fail? I really don't see how this can possibly be beneficial since the only thing it can achieve is doing unnecessary work. But if array accesses can't be floated out of conditionals then there is no reason to mark them as can_fail because they will never be floated past bounds checks anyway. comment:15 Changed 8 years ago by Sounds reasonable to me, I'm not sure why cases are floated out of conditionals, we'll have to wait for Simon to comment. comment:16 Changed 8 years ago by As requested, here is a small program that demonstrated this. Note the difference between 7.2 and 7.4 when compiling with -O2. {-# LANGUAGE MagicHash, BangPatterns #-} module T where import GHC.Prim foo :: ByteArray# -> ByteArray# -> Int# -> Int# -> Bool foo xs ys m n = go 0# 0# where go i j = case i >=# m of False -> let !x = indexIntArray# xs i in case j >=# n of False -> case x ==# indexIntArray# ys j of False -> False True -> go (i +# 1#) (j +# 1#) True -> False True -> case j >=# n of False -> let !y = indexIntArray# ys i in False True -> True comment:17 Changed 8 years ago by comment:18 Changed 8 years ago by commit 3beb1a831b37f616b5e8092def2e51cd9825735f Author: Simon Peyton Jones <simonpj@microsoft.com> Date: Thu Jan 12 17:17:22 2012 +0000 Fix Trac #5658: strict bindings not floated compiler/coreSyn/CorePrep.lhs | 2 +- compiler/coreSyn/CoreUtils.lhs | 55 +++++++------ compiler/coreSyn/MkCore.lhs | 22 +++++ compiler/prelude/PrimOp.lhs | 163 ++++++++++++++++++++++----------------- compiler/simplCore/FloatIn.lhs | 123 +++++++++++++++++++----------- compiler/simplCore/FloatOut.lhs | 20 +---- compiler/simplCore/SimplEnv.lhs | 1 + compiler/simplCore/Simplify.lhs | 10 ++- 8 files changed, 237 insertions(+), 159 deletions(-) comment:19 Changed 8 years ago by Ian: I believe we should merge this to the branch. It validates ok, but I have not done performance tests. Roman, maybe you can test too? Simon comment:20 Changed 8 years ago by Test T5658b is a simple test of Roman's program. comment:21 Changed 8 years ago by comment:22 Changed 8 years ago by Merged as 55e4870d39c5267bd272423c5118527e20455b04 That is terrible. Happily the solution is simple: array indexing operations in primpops.txt.ppshould be marked Can you try that? Simon
https://trac.haskell.org/trac/ghc/ticket/5658
CC-MAIN-2020-05
refinedweb
1,675
60.65
Someone may wonder what the difference is between Debug and Release mode, and whether it is possible to mix them. Here is one example: syperk said: .”. But that is not true. There are many problems. In my opion, the most important one is that it is not a good idea to link different modules compiled with different compiler options in C++, especially when conditional compilation is involved. In fact, “Debug” & “Release” are only two sets of predefined compiler flags and macros definitions provided by the IDE (_DEBUG and NDEBUG are two representing macros). The compiler doesn’t aware of that (but it has some magic behind compile option “MD” and “MDd”). The main problem is that program compiled using “Debug” setting and the release runtime don’t share the same compiler flags, and they are highly possible to be incompatible. For example, if you change “MDd” -> “MD” in your debug configuration, and compile the following code (don’t remove the _DEBUG macro, otherwise the “Debug” version is no longer a debug version (/MDd will define this macro implicitly, and IDE will explicitly define it via compiler flag)) : #include <iostream> #include <string> using namespace std; int main() { std::string str; return 0; } You’ll find that the program function properly. If you check the generated exe, you’ll find that it refer to two dlls, one is msvcp90d.dll, the other is msvcr90.dll. Oops! You’re mixing the debug and release runtime libraries! And that hide the potential incompatibility! The magic is here (in use_ansi.h): #ifdef _DEBUG #pragma comment(lib,“msvcprtd”) #else /* _DEBUG */ #pragma comment(lib,“msvcprt”) #endif /* _DEBUG */ If you disable this trick, and link to msvcp90.dll, you’ll get unresolved symbol error, that is because the implementation of string class is different in “Debug” and “Release” mode. This is one example of the incompatibility. error LNK2019: unresolved external symbol “__declspec(dllimport) public: __thiscall std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >(struct std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >::_Has_debug_it)” (__imp_??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@U_Has_debug_it@01@@Z) referenced in function _main It’s fortunate that this is a linker error. Otherwise, you’ll waste lots of time in debugging to find out the subtle incompatibility. STL in VC9 devotes lots of efforts to prevent break like this, then you can disable macros like “_HAS_ITERATOR_DEBUGGING” as you like, and keep your code compatible with the runtime (which is compiled with the macro enabled). But it only applies when you stick to debug or stick to release. It is really tricky to guarantee that, and I think you should never rely on this. PingBack from
https://blogs.msdn.microsoft.com/xiangfan/2008/08/30/debug-vs-release/
CC-MAIN-2017-09
refinedweb
463
53.51
Git, Versioning¶ How to bump a version¶ - ACT to check everything in - OBSERVE current versioning state - Be on master of (i) a direct clone or (ii) clone-of-fork with master up-to-date with upstream (including tags!!!) and with upstream as remote. - says v1.1a1& 007a9b6 - Observe that current latest tag matches metadata scipt and git describe, that GH releases matches metadata script, that upcoming in metadata script matches current versioner version. - Note that current tag is v1.1a1. Decide on imminent tag, say v1.1rc1. - ACT to bump tag in code - Edit current & prospective tag in psi4/psi4/metadata.py. Use your decided-upon tag v1.1rc1and a speculative next tag, say v1.1rc2, and use 7 “z”s for the part you can’t predict. - OBSERVE undefined version state - Note 7-char git hash for the new commit, here “6100822”. - ACT to bump tag in git, then bump git tag in code. - Use the decided-upon tag v1.1rc1and the observed hash “6100822” to mint a new annotated tag, minding that “v”s are present here. - Use the observed hash to edit psi4/psi4/metadata.py and commit immediately. - OBSERVE current versioning state - Nothing to make note of, this is just a snapshot. - ACT to inform remote of bump - Temporarily disengage “Include administrators” on protected master branch. - Now says v1.1rc1& 6100822 How to create and remove an annotated Git tag on a remote¶ PSI4 versioning only works with annotated tags, not lightweight tags as are created with the GitHub interface Create annotated tag: Delete tag: Pull tags: What Psi4 version is running¶ Psithon / from the executable: PsiAPI / from the library: Output file header gives info like the print_header()below. Function print_header()returns a summary of citation, version, and git information about PSI4. Function version_formatter()can return version and git information in any desired format string. How to locate non-ascii characters in the codebase¶ Neither the Python interpreter nor Sphinx like non-ASCII characters one bit, though the errors may be intermittant. Output files are usually ok, so Jerome can live, for now. To aid in tracking down offenders, here’s the vi and grep search strings. In the docs, you want to use the substitutions in psi4/doc/sphinxman/source/abbr_accents.rst instead of the actual characters. How to fix “Psi4 undefined” version¶ When in a git repo, the versioner uses git describe and psi4/metadata.py to compute the version. If you don’t have all the latest tags, this mechanism can’t work. To solve, pull tags and remake. How to fix “cannot import name ‘core’ from {top-level-psi4-dir}¶ First, what’s happening? sys.path (where modules can be imported from in python) starts with ''. If you export PYTHONPATH={objdir}/stage/{prefix}/lib/{pymod_lib_dir}:$PYTHONPATH to make PsiAPI easy, that inserts starting in pos’n 1 (0-indexed), so '' still at the head of sys.path. Now, if you try to run a psiapi/python file from {top-level-psi4-dir} that contains import psi4, it will find the source tree psi4/__init__.py and fail because there’s no core.so around. That is, it’s finding what looks to be the psi4 module dir structure . when the one it wants is what you inserted into PYTHONPATH at pos’n 1. The way around this is to move the python file you’re running to any other directory. Or, within the file, do sys.path.insert(0, {objdir}/stage/{prefix}/lib/{pymod_lib_dir}.
http://psicode.org/psi4manual/master/manage_git.html
CC-MAIN-2019-09
refinedweb
582
66.64
I have following structure: utils_dir has generator.py file which has 3 defs. I have test.py in inline_dir. And I am trying to use defs from generator.py in test.py. inline_dir and utils_dir are in different folders. How can I achieve it to use defs? Tried with creating _init_.py import generator from utils import generator Dir structure Support_dir ├── dir_A │ ├── dir_aa │ └──----- main.py [Want to use a and b from generator.py] └── utils | └── generator.py | |___ def a |___ def b It sounds like you're trying to execute a .py file in a subdirectory. Assuming the following directory structure: . ├── inline │ ├── __init__.py │ └── main.py └── utils ├── __init__.py └── generator.py And your main.py containing a simple import like (the function a() being defined in generator.py): from utils.generator import a if __name__ == '__main__': a() And generator.py would look something like this: def a(): print "hi there" You won't be able to run your program using python inline/main.py because this will set the module search path to inline/ If you want to execute a file in a subdirectory while importing from your project-level, you could do the following: PYTHONPATH=. python inline/main.py UPDATE: Added example generator.py
https://codedump.io/share/b2V6pRhVItwe/1/how-to-call-def-from-another-py-in-different-folder
CC-MAIN-2017-09
refinedweb
206
55