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 |
|---|---|---|---|---|---|
BBC micro:bit
LED SHIM
Introduction
The LED SHIM is a shiny new Pimoroni accessory for the Raspberry Pi. It has 28 RGB LEDs lined up a row and is a solderless SHIM. Since it uses the IS31FL3731 LED driver that is used on the Scroll pHAT HD, I thought it would be worth a go on the micro:bit.
In the photographs, I have the SHIM on a 4tronix Bit:2:Pi.
The SHIM is designed to fit snugly over the GPIO pins to make the electrical connection. The straight line of LEDs is enough for a 24 hour binary clock or just for some nice visual effects.
Programming
When using boards based on the IS31FL3731 LED driver, you need to know the way that the LEDs have been connected to the driver. On the Adafruit 16x9 matrices that use this driver, the LEDs are connected in order, making the job pretty straightforward. On the Scroll pHAT HD and the Scroll:bit, there is a reasonably quick way to compute the values you need. With this board, you need a lookup table, which is not an issue on a Raspberry Pi, but takes up a little more space on the micro:bit.
Another decision you need to make is whether or not to use a buffer to store the values you want to write to the display. For this program, I followed the thread of the Pimoroni library for the Scroll:bit, took out the code that wasn't needed and added some procedures to control the LEDs. The test code shows how to set all of the LEDs to a colour, light them one-by-one and make a rainbow.
from microbit import * import math _b = bytearray(145) def _w(*args): if len(args) == 1: args = args[0] i2c.write(117, bytes(args)) def clear(): global _b del _b _b = bytearray(145) def show(): _w(253, 1) _b[0] = 36 _w(_b) _w(253, 11) _w(1, 1) def set_pix(n,r,g,b): tbl = [118,69,85, 117,68,101, 116,84,100, 115,83,99, 114,82,98, 113,81,97, 112,80,96, 134,21,37, 133,20,36, 132,19,35, 131,18,34, 130,17,50, 129,33,49, 128,32,48, 127,47,63, 121,41,57, 122,25,58, 123,26,42, 124,27,43, 125,28,44, 126,29,45, 15,95,111, 8,89,105, 9,90,106, 10,91,107, 11,92,108, 12,76,109, 13,77,93] x = n * 3 _b[tbl[x]+1]=r _b[tbl[x+1]+1]=g _b[tbl[x+2]+1]=b def fill(r,g,b): for x in range(28): set_pix(x,r,g,b) def hsv_to_rgb(h, s, v): if s == 0.0: return (v, v, v) i = int(h*6 mc(h): hsv = hsv_to_rgb(h,1,0.5) r,g,b = hsv return (math.floor(r*255),math.floor(g*255),math.floor(b*255)) def rainbow(): for i in range(28): r,g,b = mc(i/28) set_pix(i,r,g,b) _w(253, 11) sleep(100) _w(10, 0) sleep(100) _w(10, 1) sleep(100) _w(0, 0) _w(6, 0) for bank in [1,0]: _w(253, bank) _w([0] + [255] * 17) clear() show() # Testing fill(255,0,0) show() sleep(3000) fill(0,255,0) show() sleep(3000) fill(0,0,255) show() sleep(3000) clear() show() for i in range(28): set_pix(i,255,255,0) show() sleep(150) rainbow() show() | http://www.multiwingspan.co.uk/micro.php?page=ledshim | CC-MAIN-2019-09 | refinedweb | 590 | 72.9 |
You can subscribe to this list here.
Showing
4
results of 4?
Vance, Michael wrote:
> My example is fairly vanilla, although I'm not sure if there's a way to
> cleanly package it so I'll just show the forensics.
>
> An excerpt from my .emacs:
>
> (semantic-add-system-include "c:/usr/local/cell/target/spu/include"
> 'c++-mode)
> (semantic-add-system-include
> "c:/usr/local/cell/target/spu/include/cell/spurs" 'c++-mode)
> (semantic-add-system-include "c:/usr/local/cell/target/spu/include"
> 'c-mode)
> (semantic-add-system-include
> "c:/usr/local/cell/target/spu/include/cell/spurs" 'c-mode)
>
> ;; CEDET / EDE / Foo
> (add-to-list 'auto-mode-alist (cons "d:/foo" 'c++-mode))
> (ede-cpp-root-project "foo"
> :name "foo"
> :file "d:/foo/main/Jamfile"
> :include-path (split-string
> (shell-command-to-string "dir /b /s /ad
> \"d:\\foo\\main\\install\\ps3-gcc-dbg\"") "\n" t)
> )
Hi,
I suspect the problem is that the :file slot is pointing to
d:/foo/main/Jamfile, but that the root of the project is at d:/foo. It
should be d:/foo/SOMEFILE, where SOMEFILE could be the directory 'main'
if needed. This file is what marks the root of the project.
As such, when you find something in the include path in
foo/main/install, it isn't part of that project, and the includes cannot
be chased.
Eric
Hi,
If your include statement says:
#include "foo.cdt"
then semantic should find your haeders fine and parse them. There are
some other expressions needed for ctags, ebrowse, or GNU global you need
to configure if you use one of those tools. There can also be confusion
between C and C++ if you have mixed modes between those files.
Eric
Jan silajoin wrote:
> Hi,
> I have a question about how to make semantic parse c language files
> which don't have .c suffix. Our project make us must use other suffix
> like cin, cdt for C header etc. I can open these files using c-mode with
> following sentence: (add-to-list 'auto-mode-alist '("\\.cin\\'" . c-mode)).
> But how to make semantic parse these files and let it work in auto
> complete?
>
> Looking forward to your kind reply.
>
> Brs,
> Silajoin
Hello,
For the linux kernel, there is already an EDE project that can
recognize it, and will set itself up. Since I personally don't hack on
the Linux kernel, it would be great if someone who did could use it and
recommend changes or provide patches. You can validate that EDE is
active with the command semantic-c-describe-environment which will tell
you a bout the ede project used to setup things like the CPP (C
preprocessor) map.
For the purposes of getting everything parsed ahead of time, you can
use GNU Global as a sort of primitive raw back-end. Semantic will use
it to find locations while looking stuff up the first time, then it will
use it's own tables once it has looked up that file once. Use M-x
semanticdb-enable-gnu-global-databases to get that started after
creating the first database using global.
Alternately, if you have files open in a particular directory,
Semantic will start parsing them in idle time. A side effect is you
can't open Emacs in a new area and just start navigating. You can force
it with semantic-debug-idle-work-function which no one has converted to
a more utilitarian use as you describe below.
As for just looking for "function details", as long as the include
path is setup correctly, this should happen automatically with no extra
setup. It will get the info from header files which it will scan
on-demand by interpreting your #include statements. It is only the
'jump to implementation' that doesn't work that way.
Good Luck
Eric
Aneesh Kumar wrote:
>@...
>
> | http://sourceforge.net/p/cedet/mailman/cedet-semantic/?viewmonth=200912&viewday=19 | CC-MAIN-2014-49 | refinedweb | 644 | 61.67 |
Java, J2EE & SOA Certification Training
- 32k Enrolled Learners
- Weekend
- Live Class
Most of the developers start off their career with Java as their base language. Well, this is because Java provides various intriguing features such as servlets, frameworks, etc. which helps in establishing a stronghold on the programming concepts. One such feature is applets in Java. A Java Applet is a small software program which can be transferred over HTTP. In this Java Applet Tutorial, I will be giving you a complete insight into Java Applets along with examples.
Below are the topics which I will be covering in this Java Applet Tutorial:
Applets in Java are small and dynamic internet-based programs. A Java Applet can be only executed within the applet framework of Java. For an easy execution of applets, a restricted ‘sandbox’ is provided by the applet framework. Generally, the applet code is embedded within an HTML page. The applet codes are executed when the HTML pages get loaded into the Java-compatible web browsers. Applets are mainly downloaded on remote machines and used on the client side.
A Java applet can be a fully functional Java application as well since it can utilize a complete Java API at its own accord. But still, there is a thin line between an applet and an application in Java.
In the next section of this article on Applets in Java, I will be listing down the differences between a Java Applet and a Java application.
Now that you know, how a Java applet differs from a Java application, let me show you how to create a basic applet in Java through the next section of this Java Applets Tutorial.
As displayed above, the Java Applet class which is a class of applet package extends the Panel class of awt package. The Panel class is a subclass of the Container class of the same package. The Container class is an extension of Component class belonging to the same package. The Component class is an abstract class and derives several useful classes for the components such as Checkbox, List, buttons, etc.
Now that you know about the complete hierarchy of the Java Applet class, let’s now try creating a simple Java Applet.
Below I have written a simple Java applet program which will simply display the welcome message.
EduApplet.java
import java.applet.Applet; import java.awt.Graphics; //Extending the Applet class public class EduApplet extends Applet{ public void paint(Graphics g){ g.drawString("Welcome To Edureka's Applet Tutorial",150,150); } }
By now you are familiar with applets and know how to create them. In the next section of this Java Applet Tutorial, I will be showing how to execute an applet in Java.
By now I have demonstrated how to create an applet, but how do you execute them? Well, unlike Java programs, executing applets is a bit different process. Since applets are net based applications they need a special environment to execute. Java provides two standard way to execute an applet:
If you are trying to execute your Applet in this way, first you need to compile your Java Applet file. Once done, you have to create a separate HTML file and add the applet code within it with the reference to your .class file within it. Now you can click the HTML file to launch the applet in the browser. Below I have given the code required to create the HTML file:
appletDemo.html
<html> <body> <applet code="EduApplet.class" width="300" height="300"> </applet> </body> </html>
In order to execute a Java Applet in this way, all you need to do is, instead of creating a separate file for HTML code, you can directly add comment at the beginning of your Java source code file indicating the presence of APPLET tag within. This helps in documenting your Java code with a prototype of the necessary HTML statements. This been done, now you can execute your applet just by starting the Java Applet Viewer which comes by default with JRE. When using this way of execution, your source code should look like below:
EduApplet.java
import java.applet.Applet; import java.awt.Graphics; /* <applet code="EduApplet" width=200 height=60> </applet> */ public class EduApplet extends Applet{ public void paint(Graphics g){ g.drawString("Welcome To Edureka's Applet Tutorial",150,150); } }
Note: You can also install any IDE such as Eclipse, and execute your codes directly from there itself.
Now that you know what is Java Applet and how it is executed, let’s dive deeper into Java Applets Tutorial and get familiar with the lifecycle of the Java Applets in the next section of this Java Applet Tutorial.
Every Java Applet needs to go through a series of phases from initialization to destruction in order to complete its execution. For that, the very first step is to inherit the java.applet.Applet class. This class aids with various methods which help in holding up a basic framework for the Java Applets. The various methods involved in the life cycle of Java Applet has been depicted by the below diagram.
As you can see, there are 4 main methods which are mandatory for any Java Applet to override. Let me brief you about each of these methods one by one.
One more method that is mostly used along with the above four is paint().
Below is the basic skeleton of a Java Applet with all the life cycle methods.
AppletLifeCycle.java
import java.applet.*; public class AppletLifeCycle extends Applet{ public void init(){ System.out.println("Applet is Initialized"); } public void start(){ System.out.println("Applet is being Executed"); } public void stop() { System.out.println("Applet execution has Stopped"); } public void paint(Graphics g) { System.out.println("Painting the Applet..."); } public void destroy() { System.out.println("Applet has been Destroyed"); } }
Let’s now put whatever we have learned in this tutorial together and try to create an applet which can respond to user actions.
Below I have included a small and simple Java Applet program where you will see how event handling works while an applet courses through its life cycle.
AppletEventHandling.java
import java.awt.event.MouseListener; import java.awt.event.MouseEvent; import java.applet.Applet; import java.awt.Graphics; import java.awt.Color; import java.awt.Font; public class AppletEventHandling extends Applet implements MouseListener { StringBuffer strBuf; public void init() { addMouseListener(this); strBuf = new StringBuffer(); addItem(" Initializing the applet"); addItem(" Welcome to the Edureka's Applet Tutorial"); } public void start() { addItem(" Starting the applet "); } public void stop() { addItem(" Stopping the applet "); } public void destroy() { addItem(" Destroying the applet"); addItem(" Good Bye!!"); } void addItem(String word) { System.out.println(word); strBuf.append(word); repaint(); } public void paint(Graphics g) { g.drawString(strBuf.toString(), 10, 20); setForeground(Color.white); setBackground(Color.black); } public void mouseEntered(MouseEvent event) { } public void mouseExited(MouseEvent event) { } public void mousePressed(MouseEvent event) { } public void mouseReleased(MouseEvent event) { } public void mouseClicked(MouseEvent event) { addItem(" Mouse is Clicked!!"); } }
Next step is to compile the above .java file into .class file. Once done, now you need to create an HTML file and add the reference of the .class file in the applet tag. Below I have demonstrated how to write the code for this HTML file.
eventHandling.html
<html> <title>Event Handling</title> <applet code = "AppletEventHandling.class" width = "300" height = "300"> </applet> </html>
When you execute this code, your applet should look like the below-shown screenshot.
data-src=Now, to check whether your applet is working perfect or not, you can check in your terminal. There you can see, all the phases your aplet is going through with your every action. Below I have attached a screenshot for the same.
data-src=With this, we come to an end of this article on Java Applet Tutorial. I hope now you have a clear picture of what exactly is a Java Applet, why do we need them and how they are created. If you wish to learn Java in more detail you can refer to our other Java articles as well.
Now that you have understood basics of Java Applet, Applet Tutorial” and we will get back to you as soon as possible. | https://www.edureka.co/blog/java-applet-tutorial/ | CC-MAIN-2019-39 | refinedweb | 1,367 | 56.66 |
In this Java Tutorial section, you will learn how to find the sum of multidigit number. For this purpose, we have allowed the user to enter multidigit number. User can enter any digit number but cannot exceed to 9 digit. Following code calculates the sum of digits:
while (n > 0) { int p = n % 10; sum = sum + p; n = n / 10; }
Here is the code for Sum of Digits in Java:
import java.util.*; class SumOfDigits { public static void main(String args[]) { int sum = 0; System.out.println("Enter multi digit number:"); Scanner input = new Scanner(System.in); int n = input.nextInt(); int t = n; while (n > 0) { int p = n % 10; sum = sum + p; n = n / 10; } System.out.println("sum of the digits in " + t + " is " + sum); } }
Output
Enter multi digit number: 123456789 sum of digits in 123456789 is 45 | http://www.roseindia.net/tutorial/java/core/sumofdigits.html | CC-MAIN-2017-09 | refinedweb | 141 | 65.32 |
Description.
This creates an instance of
Ndb, which represents a
connection to the MySQL Cluster. All NDB API applications
should begin with the creation of at least one
Ndb object. This requires the
creation of at least one instance of
Ndb_cluster_connection, which
serves as a container for a cluster connection string.
Signature.
Ndb ( Ndb_cluster_connection*
ndb_cluster_connection, const char*
catalogName= "", const char*
schemaName= "def" )
Parameters.
The
Ndb class constructor can
take up to 3 parameters, of which only the first is required:
ndb_cluster_connection is an
instance of
Ndb_cluster_connection,
which represents a cluster connection string. (See
Section 2.3.17, “The Ndb_cluster_connection Class”.)
Prior to MySQL Cluster 7.3.8 and MySQL Cluster NDB 7.4.3, it
was possible to delete the
Ndb_cluster_connection used to create a
given instance of
Ndb without first
deleting the dependent
Ndb object. (Bug
#19999242)
catalogName is an optional
parameter providing a namespace for the tables and indexes
created in any connection from the
Ndb object.
This is equivalent to what mysqld considers “the database”.
The default value for this parameter is an empty string.
The optional
schemaName provides
an additional namespace for the tables and indexes created
in a given catalog.
The default value for this parameter is the string “def”.
Return value.
An
Ndb object.
~Ndb() (Class Destructor).
The destructor for the
Ndb
class should be called in order to terminate an instance of
Ndb. It requires no
arguments, nor any special handling.
Description.
This is one of two NDB API methods provided for closing a
transaction (the other being
NdbTransaction::close()). You
must call one of these two methods to close the transaction
once it has been completed, whether or not the transaction
succeeded.
If the transaction has not yet been committed, it is aborted when this method is called. See Section 2.3.16.1.34, “Ndb::startTransaction()”.
Signature.
void closeTransaction ( NdbTransaction *
transaction)
Parameters.
This method takes a single argument, a pointer to the
NdbTransaction to be closed.
Return value. N/A.
Description. This method can be used to compute a distribution hash value, given a table and its keys.
Signature.
static int computeHash ( Uint32*
hashvalueptr, const NdbDictionary::Table*
table, const struct Key_part_ptr*
keyData, void*
xfrmbuf= 0, Uint32
xfrmbuflen= 0 )
Parameters. This method takes the following parameters:
If the method call is successful,
hashvalueptr is set to the
computed hash value.
A pointer to a
table (see
Section 2.3.37, “The Table Class”).
keyData is a null-terminated
array of pointers to the key parts that are part of the
table's distribution key. The length of each key part
is read from metadata and checked against the passed value
(see Section 2.3.15, “The Key_part_ptr Structure”).
xfrmbuf is a pointer to temporary
buffer used to calculate the hash value.
xfrmbuflen is the length of this
buffer.
If
xfrmbuf is
NULL (the default), then a call to
malloc() or
free()
is made automatically, as appropriate.
computeHash() fails if
xfrmbuf is not
NULL
and
xfrmbuflen is too small.
Previously, it was assumed that the memory returned by the
malloc() call would always be suitably
aligned, which is not always the case. Beginning with
MySQL Cluster NDB versions 7.1.27, 7.2.13, and 7.3.2, when
malloc() provides a buffer to this
method, the buffer is explicitly aligned after it is
allocated, and before it is actually used. (Bug #16484617)
Return value.
0 on success, an error code on failure. (If the method call
succeeds, the computed hash value is made available via
hashvalueptr.)
Description. This method creates a subscription to a database event.
NDB API event subscriptions do not persist after a MySQL”.
Description.
This method drops a subscription to a database event
represented by an
NdbEventOperation object..
Description.
This method is used to obtain an object for retrieving or
manipulating database schema information. This
Dictionary object contains
meta-information about all tables in the cluster.
The dictionary returned by this method operates independently of any transaction. See Section 2.3.4, “The Dictionary Class”, for more information.
Signature.
NdbDictionary::Dictionary* getDictionary ( void ) const
Parameters. None.
Return value.
An instance of the
Dictionary
class.
Description. This method can be used to obtain the name of the current database.
Signature.
const char* getDatabaseName ( void )
Parameters. None.
Return value. The name of the current database.
Description. This method can be used to obtain the current database schema name.
Signature.
const char* getDatabaseSchemaName ( void )
Parameters. None.
Return value. The name of the current database schema.
Description.
Iterates over distinct event operations which are part of the
current GCI, becoming valid after calling
nextEvent(). You can use
this method to obtain summary information for the epoch (such
as a list of all tables) before processing the event data.
This method is deprecated in MySQL Cluster NDB 7.4.3, and is
subject to removal in a future release. In MySQL Cluster NDB
7.4.3 and later, you should use
getNextEventOpInEpoch2()
instead.
Signature.
const NdbEventOperation* getGCIEventOperations ( Uint32*
iter, Uint32*
event_types)
Parameters.
An iterator and a mask of event types. Set
* to
start.
iter=0
Return value.
The next event operation; returns
NULL when
there are no more event operations. If
event_types is not
NULL, then after calling the method it
contains a bitmask of the event types received. .
Description.
Gets the maximum memory, in bytes, that can be used for the
event buffer. This is the same as reading the value of the
ndb_eventbuffer_max_alloc
system variable in the MySQL Server.
This method was added in MySQL Cluster NDB 7.1.29, MySQL Cluster NDB 7.2.14, and MySQL Cluster NDB 7.3.3.
Signature.
unsigned get_eventbuf_max_alloc ( void )
Parameters. None.
Return value. The mamximum memory available for the event buffer, in bytes.
Description.
Gets
ndb_eventbuffer_free_percent—that
is, the percentage of event buffer memory that should be
available before buffering resumes, once
ndb_eventbuffer_max_alloc has
been reached. This value is calculated as
used * 100 /
ndb_eventbuffer_max_alloc,
where
used is the amount of event
buffer memory actually used, in bytes.
This method was added in MySQL Cluster NDB 7.4.3.
Signature.
unsigned get_eventbuffer_free_percent ( void )
Parameters.
The percentage (
pct) of event
buffer memory that must be present. Valid range is 1 to 99
inclusive.
Return value. None.
Description.
Gets event buffer usage as a percentage of
ndb_eventbuffer_max_alloc.
Unlike
get_eventbuffer_free_percent(),
this method makes complete usage information available in the
form of an
EventBufferMemoryUsage data
structure.
This method was added in MySQL Cluster NDB 7.4.3.
Signature.
void get_event_buffer_memory_usage ( EventBufferMemoryUsage& )
Parameters.
A reference to an
EventBufferMemoryUsage
structure, which receives the usage data.
Return value. None.
Description.
Added in MySQL Cluster NDB 7.4.3, this method supersedes
getLatestGCI(), which is
now deprecated and subject to removal in a future MySQL
Cluster release.
Prior to MySQL Cluster NDB 7.4.7, this method returned the
highest epoch number in the event queue. In MySQL Cluster NDB
7.4.7 and later, it returns the highest epoch number found after
calling
pollEvents2() (Bug
#20700220).
Signature.
Uint64 getHighestQueuedEpoch ( void )
Parameters. None.
Return value. The most recent epoch number, an integer.
Description. Gets the index for the most recent global checkpoint.
This method is deprecated in MySQL Cluster NDB 7.4.3, and is
subject to removal in a future release. In MySQL Cluster NDB
7.4.3 and later, you should use
getHighestQueuedEpoch()
instead.
Signature.
Uint64 getLatestGCI ( void )
Parameters. None.
Return value. The most recent GCI, an integer.
Description.
This method provides you with two different ways to obtain an
NdbError object representing
an error condition. For more detailed information about error
handling in the NDB API, see Chapter 7, MySQL 7.2, “NDB API Errors and Error Handling”.
Return value.
An
NdbError object containing
information about the error, including its type and, where
applicable, contextual information as to how the error arose.
See Section 2.3.20, “The NdbError Structure”, for details.
Description.
This method provides an easy and safe way to access any extra
information about an error. Rather than reading these extra
details from the
NdbError
object's
details property (now now
deprecated in favor of
getNdbErrorDetail()‐see Bug #48851).
This method enables storage of such details in a user-supplied
buffer, returning a pointer to the beginning of this buffer.
In the event that the string containing the details exceeds
the length of the buffer, it is truncated to fit.
getErrorDetail() provides the source of an
error in the form of a string. In the case of a unique
constraint violation (error 893), this string supplies the fully
qualified name of the index where the problem originated, in the
format
database-name/
schema-name/
table-name/
index-name,
(
NdbError.details, on the other hand,
supplies only an index ID, and it is often not readily apparent
to which table this index belongs.) Regardless of the type of
error and details concerning this error, the string retrieved by
getErrorDetail() is always null-terminated.
Signature.
The
getNdbErrorDetail() method has the
following signature:
const char* getNdbErrorDetail ( const NdbError&
error, char*
buffer, Uint32
bufferLength) const
Parameters.
To obtain detailed information about an error, call
getNdbErrorDetail() with a reference to the
corresponding
NdbError
object, a
buffer, and the length of
this buffer (expressed as an unsigned 32-bit integer).
Return value.
When extra details about the
error
are available, this method returns a pointer to the beginning
of the
buffer supplied. As stated
previously, if the string containing the details is longer
than
bufferLength, the string is
truncated to fit. In the event that no addition details are
available,
getNdbErrorDetail() returns
NULL.
Description.
If a name was set for the
Ndb object prior
to its initialization, you can retrieve it using this method.
Used for debugging.
Signature.
const char* getNdbObjectName ( void ) const
Parameters. None.
Return value.
The
Ndb object name, if one has been set
using
setNdbObjectName().
Otherwise, this method returns 0.
This method was added in MySQL Cluster NDB 7.1.32, MySQL Cluster NDB 7.2.17, and MySQL Cluster NDB 7.3.6. (Bug #18419907)
Description.
Iterates over individual event operations making up the
current global checkpoint. Use following
nextEvent2() to obtain
summary information for the epoch, such as a listing of all
tables, before processing event data.
Exceptional epochs do not have any event operations associated with them.
Signature.
const NdbEventOperation* getNextEventOpInEpoch2 ( Uint32*
iter, Uint32*
event_types)
Parameters.
Set
iter to 0 initially; this is
NULL when there are no more events
within this epoch. If
event_types
is not
NULL, it holds a bitmask of
the event types received.
Return value.
A pointer to the next
NdbEventOperation, if there
is one.
Description.
This method can be used to obtain a reference to a given
Ndb object. This is the same
value that is returned for a given operation corresponding to
this object in the output of
DUMP
2350. (See
Section 8.2.38, “DUMP 2350”, for an
example.)
Signature.
Uint32 getReference ( void )
Parameters. None.
Return value. A 32-bit unsigned integer.
Description.
This method is used to initialize an
Ndb object.
Signature.
int init ( int
maxNoOfTransactions= 4 )
Parameters.
The
init() method takes a single parameter
maxNoOfTransactions of type
integer. This parameter specifies the maximum number of
parallel
NdbTransaction
objects that can be handled by this instance of
Ndb. The maximum permitted
value for
maxNoOfTransactions is
1024; if not specified, it defaults to 4.
Each scan or index operation uses an extra
NdbTransaction object.
Return value.
This method returns an
int, which can be
either of the following two values:
Description. Check if all events are consistent. If a node failure occurs when resources are exhausted, events may be lost and the delivered event data might thus be incomplete. This method makes it possible to determine if this is the case. ( Uint64&
gci)
Parameters. A reference to a global checkpoint index. This is the first inconsistent GCI found, if any.
Return value.
true if all events are consistent.
Description. If a node failure occurs when resources are exhausted, events may be lost and the delivered event data might thus be incomplete. This method makes it possible to determine if this is the case by checking whether all events in a given GCI are consistent.GCI ( Uint64
gci)
Parameters. A global checkpoint index.
Return value.
true if this GCI is consistent;
false indicates that the GCI may be
possibly inconsistent.
Description.
Check whether higher queued epochs have been seen by the last
invocation of
Ndb::pollEvents2(), or
whether a TE_CLUSTER_FAILURE event was
found.
It is possible, after a cluster failure has been detected, for
the highest queued epoch returned by
pollEvents2() not to be
increasing any longer. In this case, rather than poll for more
events, you should instead consume events with
nextEvent() until it
detects a TE_CLUSTER_FAILURE is detected,
then reconnect to the cluster when it becomes available again.
This method was added in MySQL Cluster NDB 7.2.21, MySQL Cluster NDB 7.3.10, and MySQL Cluster NDB 7.4.7 (Bug #18753887).
Signature.
bool isExpectingHigherQueuedEpochs ( void )
Parameters. None.
Return value.
True if queued epochs were seen by the last
pollEvents2() call or, in
the event of cluster failure.
Description. Returns the next event operation having data from a subscription queue.
This method is deprecated in MySQL Cluster NDB 7.4.3, and is
subject to removal in a future release. In MySQL Cluster NDB
7.4.3 and later, you should use
nextEvent2() instead.
Signature.
NdbEventOperation* nextEvent ( void )
Parameters. None.
Return value.
This method returns an
NdbEventOperation object
representing the next event in a subscription queue, if there
is such an event. If there is no event in the queue, it
returns
NULL instead.
Beginning with MySQL Cluster NDB 7.1.32, MySQL Cluster NDB
7.2.17, and MySQL Cluster NDB 7.3.6, this method clears
inconsistent data events from the event queue when processing
them. In order to able to clear all such events in these and
later versions, applications must call this method even in cases
when
pollEvents() has
already returned 0. (Bug #18716991)
Description.
Returns the event operation associated with the data dequeued
from the event queue. This should be called repeatedly after
pollEvents2() populates
the queue, until the event queue is empty.
Added in MySQL Cluster NDB 7.4.3, this method supersedes
nextEvent(), which is now
deprecated and subject to removal in a future MySQL Cluster
release.
After calling this method, use
NdbEventOperation::getEpoch()
to determine the epoch, then check the type of the returned
event data using
NdbEventOperation::getEventType2().
Handling must be provided for all exceptional
TableEvent types,
including
TE_EMPTY,
TE_INCONSISTENT, and
TE_OUT_OF_MEMORY (also introduced in MySQL
Cluster NDB 7.4.3). No other
NdbEventOperation methods than
the two named here should be called for an exceptional epoch.
Returning empty epochs (
TE_EMPTY) may flood
applications when data nodes are idle. If this is not desirable,
applications should filter out any empty epochs.
Signature.
NdbEventOperation* nextEvent2 ( void )
Parameters. None.
Return value.
This method returns an
NdbEventOperation object
representing the next event in an event queue, if there is
such an event. If there is no event in the queue, it returns
NULL instead.
Description. This method waits for a GCP to complete. It is used to determine whether any events are available in the subscription queue.
This method waits for the next epoch, rather than the next GCP. See Section 2.3.21, “The NdbEventOperation Class”, for more information.
In MySQL Cluster NDB 7.4.3 and later, you can (and should) use
pollEvents2() instead of
this method.
Prior to MySQL Cluster NDB 7.4.7,
pollEvents() was not compatible with the
exceptional
TableEvent
types added in MySQL Cluster NDB 7.4.3 (Bug #20646496); in MySQL
Cluster 7.4.7 and later,
pollEvents() is
compatible with these event types, as described later in this
section.
Signature.
int pollEvents ( int
maxTimeToWait, Uint64*
latestGCI= 0 )
Parameters. This method takes the two parameters listed here:
The maximum time to wait, in milliseconds, before
“giving up” and reporting that no events were
available (that is, before the method automatically returns
0).
A negative value causes the wait to be indefinite and never
time out. This is not recommended (and is not supported by
the successor method
pollEvents2()).
The index of the most recent global checkpoint. Normally,
this may safely be permitted to assume its default value,
which is
0.
Return value.
pollEvents() returns a value of type
int, which may be interpreted as follows:
> 0: There are events available in the
queue.
0: There are no events available.
In MySQL Cluster NDB 7.4.7 and later, a negative value
indicates failure and NDB_FAILURE_GCI
(
~(Uint64)0) indicates cluster failure
(Bug #18753887); 1 is returned when encountering an
exceptional event, except when only
TE_EMPTY events are found, as described
later in this section.
In MySQL Cluster NDB 7.4.7 and later, when
pollEvents() finds an exceptional event at
the head of the event queue, the method returns 1 and otherwise
behaves as follows:
Empty events (
TE_EMPTY) are removed from
the event queue head until an event containing data is
found. When this results in the entire queue being processed
without encountering any data, the method returns 0 (no
events available) rather than 1. This behavior makes this
event type transparent to an application using
pollEvents().
After encountering an event containing inconsistent data
(
TE_INCONSISTENT) due to data node buffer
overflow, the next call to
nextEvent() call
removes the inconsistent data event data from the event
queue, and returns
NULL. You should check
the inconsistency by calling
isConsistent()
immediately thereafter.
Important: Although the inconsistent
event data is removed from the event queue by calling
nextEvent(), information about the
inconsistency is removed only by another
nextEvent() call following this, that
actually finds an event containing data.
When
pollEvents() finds a data buffer
overflow event (
TE_OUT_OF_MEMORY), the
event data is added to the event queue whenever event buffer
usage exceeds
ndb_eventbuffer_max_alloc.
In this case, the next call to
nextEvent() exits the process.
Description. Waits for an event to occur. Returns as soon as any event data is available. This method also moves an epoch's complete event data to the event queue.
Added in MySQL Cluster NDB 7.4.3, this method supersedes
pollEvents(), which is now
deprecated and subject to removal in a future MySQL MySQL Cluster).
Description. This method is used to set the name of the current database.
Signature.
void setDatabaseName ( const char *
databaseName)
Parameters.
setDatabaseName() takes a single, required
parameter, the name of the new database to be set as the
current database.
Return value. N/A.
Description. This method sets the name of the current database schema.
Signature.
void setDatabaseSchemaName ( const char *
databaseSchemaName)
Parameters. The name of the database schema.
Return value. N/A.
Description. Queuing of empty epochs is disabled by default. This method can be used to enable such queuing, in which case any new, empty epochs entering the event buffer following the method call are queued.
When queuing of empty epochs is enabled,
nextEvent() associates an
empty epoch to one and only one of the subscriptions (event
operations) connected to the subscribing
Ndb
object. This means that there can be no more than one empty
epoch per subscription, even though the user may have many
subscriptions associated with the same
Ndb
object.
Signature.
void setEventBufferQueueEmptyEpoch ( bool
queue_empty_epoch)
Parameters.
This method takes a single input parameter, a boolean.
Invoking the method with
true enables
queuing of empty events; passing
false to
the method disables such queuing.
Return value. None.
setEventBufferQueueEmptyEpoch() has no
associated getter method. This is intentional, and is due to
the fact this setter applies to queuing
new epochs, whereas the queue itself may
still reflect the state of affairs that existed prior to
invoking the setter. Thus, during a transition period, an
empty epoch might be found in the queue even if queuing is
turned off.
setEventBufferQueueEmptyEpoch() was added in
MySQL Cluster NDB 7.4.11 and MySQL Cluster NDB 7.5.2.
Description.
Sets the maximum memory, in bytes, that can be used for the
event buffer. This has the same effect as setting the value of
the
ndb_eventbuffer_max_alloc
system variable in the MySQL Server.
This method was added in MySQL Cluster NDB 7.1.29, MySQL Cluster NDB 7.2.14, and MySQL Cluster NDB 7.3.3.
Signature.
void set_eventbuf_max_alloc ( unsigned
size)
Parameters.
The desired maximum
size for the
event buffer, in bytes.
Return value. None.
Description.
Sets
ndb_eventbuffer_free_percent—that
is, the percentage of event buffer memory that should be
available before buffering resumes, once
ndb_eventbuffer_max_alloc has
been reached.
This method was added in MySQL Cluster NDB 7.4.3.
Signature.
int set_eventbuffer_free_percent ( unsigned
pct)
Parameters.
The percentage (
pct) of event
buffer memory that must be present. Valid range is 1 to 99
inclusive.
Return value. The value that was set.
Description.
Starting with MySQL Cluster NDB 7.1.32, MySQL Cluster NDB
7.2.17, and MySQL Cluster.
Description..1.2, “Ndb::closeTransaction()”, and Section 2.3.30.2.1, “NdbTransaction::close()”, for more information.
Signature.
NdbTransaction* startTransaction ( const NdbDictionary::Table*
table= 0, const char*
keyData= 0, Uint32*
keyLen= 0 )
Parameters. This method takes the following three parameters:
table: A pointer to a
Table object. This is used
to determine on which node the transaction coordinator
should run.
keyData: A pointer to a partition
key corresponding to
table.
keyLen: The length of the
partition key, expressed in bytes. object) used for
deciding which node should act as the transaction
coordinator.
A null-terminated array of pointers to the values of the distribution key columns. The length of the key part is read from metadata and checked against the passed value.
A
Key_part_ptr. | http://docs.oracle.com/cd/E17952_01/ndbapi-en/ndb-ndb-methods.html | CC-MAIN-2016-40 | refinedweb | 3,589 | 58.99 |
lseek - move the read/write file offset
#include <sys/types.h> #include <unistd.h> off_t lseek(int fildes, off_t offset, int whence);
The lseek() function will set the file offset for the open file description associated with the file descriptor fildes, as follows:
- If whence is SEEK_SET the file offset is set to offset bytes.
- If whence is SEEK_CUR the file offset is set to its current location plus offset.
- If whence is SEEK_END the file offset is set to the size of the file plus offset.
The symbolic constants SEEK_SET, SEEK_CUR and SEEK_END are defined in the header <unistd.h>.
The behaviour of lseek() on devices which are incapable of seeking is implementation-dependent. The value of the file offset associated with such a device is undefined..
The lseek() function will not, by itself, extend the size of a file.
If fildes refers to a shared memory object, the result of the lseek() function is unspecified.
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, is returned. Otherwise, (off_t)-1 is returned, errno is set to indicate the error and the file offset will remain unchanged.
The lseek() function will fail if:
- [EBADF]
- The fildes argument is not an open file descriptor.
- [EINVAL]
- The whence argument is not a proper value, or the resulting file offset would be invalid.
- [EOVERFLOW]
- The resulting file offset would be a value which cannot be represented correctly in an object of type off_t.
- [ESPIPE]
- The fildes argument is associated with a pipe or FIFO.
None.
None.
None.
open(), <sys/types.h>, <unistd.h>.
Derived from Issue 1 of the SVID. | http://pubs.opengroup.org/onlinepubs/7990989775/xsh/lseek.html | CC-MAIN-2014-42 | refinedweb | 274 | 64.2 |
int a = 2; int b = 3; int c = a + b; // c becomes 5.with the "overloaded" meaning:
string a = "Operator"; string b = "Overloading"; string c = a + b; // c becomes "OperatorOverloading"A trait of CeePlusPlus, SmalltalkLanguage, RubyLanguage, DylanLanguage, and AplLanguage, among others. OperatorOverloading and Polymorphism in general are mechanisms to allow one syntax to mean many things based on context. In this case, the context is the types of the parameters, though it is also useful to allow for context to include the type of the result. Operator overloading does not casually allow for the following: (a) altering operator precedence based on the types of the operators, (b) new operators. These require the ability to describe new syntax.
class Foo { private: int x; public: // insert appropriate ctor, dtor here bool operator == (const Foo &rhs) const { return x != rhs.x; // !!!; == is BACKWARDS } bool operator != (const Foo &rhs) const { return *this == rhs; // !!! != same as == } };Great way to confuse people.... engineer_scotty (Scott Johnson) I used to argue with people against operator overloading using arguments like these. They will claim operator overloading is bad, because you can't prevent people overloading the + operator to really do a subtract operation. My respond was: So what? How do you prevent people writing an add() function that really do a subtract? Anyway, I used to like operator overloading, but no longer, because couple with C++'s autocasting rules, it is a really difficult to see if a, say '=', is really doing a normal C++ operator thing or go called to an overloader operator method. -- OliverChung Agreed. It's possible to name your variable foo, bar, and baz, or define a function named "printObject" that really deletes the hard disk, or eliminate all whitespace and indentation from the program. We don't suggest getting rid of variables, functions, and whitespace-neutral languages. I'd much rather have programming language features that let me do things I should do than prevent me from doing things I shouldn't. -- JonathanTang Programmers that wish to intentionally obfuscate their code will -always- be able to find a means to do so. Something like the above depends on WorseThanFailure, and it'd be a good reason to send a programmer (or the maintainer who comes after) to a psychotherapist, but it still isn't a good reason to take away the power to modify syntax and operators for the domain. If you want to avoid that sort of mess, use conventions and code-reviews.
class Fixed { Fixed sin() { Fixed x = this; if (x.compareTo(0) < 0) { return x.negated().sin().negated(); } if (x.compareTo(PI_DIV2) > 0) { return PI.minus(x).sin(); } Fixed x2 = x.multiply(x); Fixed x3 = x.multiply(x2); Fixed x5 = x3.multiply(x2); Fixed x7 = x5.multiply(x2); return x.minus(x3.divide(6)).add(x5.divide(120)).minus(x7.divide(5040)); } }Or do you think that this is better?
class Fixed { Fixed sin() { Fixed x = this; if (x < 0) { return -(-x.sin()); } if (x > PI_DIV2) { return (PI - x).sin(); } Fixed x2 = x * x; Fixed x3 = x * x2; Fixed x5 = x3 * x2; Fixed x7 = x5 * x2; return x - (x3 / 6) + (x5 / 120) - (x7 / 5040); } }The operators could be confused with the mathematical ones and... Hey, wait a minute, I'm doing math here. Thankfully I wasn't using some language whose designers know better than me which numeric types I'll ever need. -- DanielYokomiso I'm much better at spelling out functions and using prefix notation than keeping track of what an operator means in a given statement. The above example is trivially easy to understand because it deals with only one class. Add a few more classes with their own overloaded operators and let the code sit for 6 months. Then try to remember which implementation of each operator will be used in each instance, what will autocast, etc. -- EricHodges The above example trivially easy to understand is the specification for sine function from IcfpProgrammingContest 2003. As a JavaLanguage professional programmer I find it difficult to keep track of which method will be called in a given context, which will get automatic conversion, etc. in most of code I see other people write. If you have bad programmers they'll write 'fred = 'a.foo.bar.baz(); barney = fred.baz().cddar().car(); and you'll have no idea where the sql insert is being executed, without understanding the classes involved. People complain about operator overloading because CeePlusPlus programmers tend to find bizarre ways to use them (e.g. in >> x >> y;''? Of course it's a good idea!) but we never see SmallTalk or Haskell programmers complaining. If we are expressing math, we should be able to use math symbols (I would argue for |x| for abs and true sqrt symbols...), or else write code difficult to verify later. Don't cripple the language because of bad programmers. -- DanielYokomiso But I can click Refactor>Rename on a, foo, bar, baz, cddar and car once I figure out what they mean and give everyone else a hint. I'd probably do the same if I found some overloaded operators (assuming my IDE supported that.) -- EricHodges ASCTo do what it does, Criteria overloads methods such as "<", ">", and "&". It's definitely useful to some; in the (currently small) Ruby community there are a lot of people who do it. But when you do this in a language that isn't Smalltalk or Lisp you slam into the limitations pretty quickly. I tried doing something similar with my object-relational library, but found that you can't make code that looks like
query = get_query( Product ) { |product| product.name != 'Sofa' } puts query.to_sql # => "select * from products where (product.name != 'Sofa' )"Because you can override "<", but you can't override "==", and "!=" is just the unary negation of "==" and you certainly don't get to override unary negation in Ruby. Ah, well. -- francis You can do this in Ruby, at least in 1.8, but you have to do some (ugly?) tricks if you want to preserve operator symmetry:
Class query def == (rhs) ... comparison code end end Class String def == (rhs) if (rhs.class == query) return (rhs == self) else return super(rhs) end end endBut it's not a totally unreasonable way to do it. Could be more elegant in a more strongly typed language, but then it wouldn't be Ruby. --dga
class foo { /* ... */ public: template <typename Function> void Operate(Function &func) { doThings(); func( mSomeVar ); } };This obviously achieves extremely loose (watery? prolapse?) coupling while providing type safety and most importantly the ability to use both actual functions and FunctorObjects. | http://c2.com/cgi-bin/wiki?OperatorOverloading | CC-MAIN-2014-15 | refinedweb | 1,092 | 65.62 |
Shellsort is an in-place comparison sort, also known as Shell sort or Shell’s method. It’s mainly variation of insertion sort or bubble sort . There was one drawback with insertion sort, we move elements only one position ahead but when an elements are too far then lots of movements are involved. To reduce these movements Shell sort come with idea of allow exchange of far items.
Shell Sort Steps
- Pick some far location h and make sorted array for values index[h…n-1] by insertion sort.
- Reduce the value of h until it becomes 1.
- Repeat the steps 1 and 2
- Finally you will get sorted items list.
Points to Remember
- Data structure: Array
- Worst-case performance: O(n2) (worst known worst case gap sequence) O(n log2n) (best known worst case gap sequence)
- Best-case performance: O(n log n) (most gap sequences) O(n log2n) (best known worst case gap sequence)
- Average performance: depends on gap sequence
- Worst-case space complexity : О(n) total, O(1) auxiliary
Sell Sort Java Program
public class ShellSort { public static void main(String[] args) { int[] items = { 2, 6, 3, 8, 4, 1, 5, 0 }; System.out.println("Before Shell Sorting :"); printArray(items); //Perform shell sort shellsort(items); System.out.println("After Shell Sorting :"); printArray(items); } static void shellsort(int items[]) { int n = items.length; // Start with a big gap, then reduce the gap until 1 for (int gap = n/2; gap > 0; gap /= 2) { //perform insertion sort for these gap size //The first gap elements a[0..gap-1] are already //in gapped order keep adding one more element //until the entire array is gap sorted for (int i = gap; i = gap && items[j - gap] > temp; j -= gap) items[j] = items[j - gap]; // put temp in its correct location items[j] = temp; } } } static void printArray(int items[]) { for (int item:items) { System.out.print(item + " "); } System.out.println(); } }
Output
Before Shell Sorting : 2 6 3 8 4 1 5 0 After Shell Sorting : 0 1 2 3 4 5 6 8 | https://facingissuesonit.com/2019/07/26/shell-sort-program-and-complexity-big-o/ | CC-MAIN-2021-17 | refinedweb | 342 | 56.49 |
Constrained optimization with Lagrange multipliers and autograd
Posted November 03, 2018 at 09:39 AM | categories: optimization, autograd | tags: | View Comments
Constrained optimization is common in engineering problems solving. A prototypical example (from Greenberg, Advanced Engineering Mathematics, Ch 13.7) is to find the point on a plane that is closest to the origin. The plane is defined by the equation \(2x - y + z = 3\), and we seek to minimize \(x^2 + y^2 + z^2\) subject to the equality constraint defined by the plane.
scipy.optimize.minimize provides a pretty convenient interface to solve a problem like this, ans shown here.
import numpy as np from scipy.optimize import minimize def objective(X): x, y, z = X return x**2 + y**2 + z**2 def eq(X): x, y, z = X return 2 * x - y + z - 3 sol = minimize(objective, [1, -0.5, 0.5], constraints={'type': 'eq', 'fun': eq}) sol
fun: 1.5 jac: array([ 2.00000001, -0.99999999, 1.00000001]) message: 'Optimization terminated successfully.' nfev: 5 nit: 1 njev: 1 status: 0 success: True x: array([ 1. , -0.5, 0.5])
I like the minimize function a lot, although I am not crazy for how the constraints are provided. The alternative used to be that there was an argument for equality constraints and another for inequality constraints. Analogous to
scipy.integrate.solve_ivp event functions, they could have also used function attributes.
Sometimes, it might be desirable to go back to basics though, especially if you are unaware of the
minimize function or perhaps suspect it is not working right and want an independent answer. Next we look at how to construct this constrained optimization problem using Lagrange multipliers. This converts the problem into an augmented unconstrained optimization problem we can use
fsolve on. The gist of this method is we formulate a new problem:
\(F(X) = f(X) - \lambda g(X)\)
and then solve the simultaneous resulting equations:
\(F_x(X) = F_y(X) = F_z(X) = g(X) = 0\) where \(F_x\) is the derivative of \(f*\) with respect to \(x\), and \(g(X)\) is the equality constraint written so it is equal to zero. Since we end up with four equations that equal zero, we can simply use fsolve to get the solution. Many years ago I used a finite difference approximation to the derivatives. Today we use autograd to get the desired derivatives. Here it is.
import autograd.numpy as np from autograd import grad def F(L): 'Augmented Lagrange function' x, y, z, _lambda = L return objective([x, y, z]) - _lambda * eq([x, y, z]) # Gradients of the Lagrange function dfdL = grad(F, 0) # Find L that returns all zeros in this function. def obj(L): x, y, z, _lambda = L dFdx, dFdy, dFdz, dFdlam = dfdL(L) return [dFdx, dFdy, dFdz, eq([x, y, z])] from scipy.optimize import fsolve x, y, z, _lam = fsolve(obj, [0.0, 0.0, 0.0, 1.0]) print(f'The answer is at {x, y, z}')
The answer is at (1.0, -0.5, 0.5)
That is the same answer as before. Note we have still relied on some black box solver inside of fsolve (instead of inside minimize), but it might be more clear what problem we are solving (e.g. finding zeros). It takes a bit more work to set this up, since we have to construct the augmented function, but autograd makes it pretty convenient to set up the final objective function we want to solve.
How do we know we are at a minimum? We can check that the Hessian is positive definite in the original function we wanted to minimize. You can see here the array is positive definite, e.g. all the eigenvalues are positive. autograd makes this easy too.
from autograd import hessian h = hessian(objective, 0) h(np.array([x, y, z]))
array([[ 2., 0., 0.], [ 0., 2., 0.], [ 0., 0., 2.]])
In case it isn't evident from that structure that the eigenvalues are all positive, here we compute them:
np.linalg.eig(h(np.array([x, y, z])))[0]
array([ 2., 2., 2.])
In summary, autograd continues to enable advanced engineering problems to be solved.
Copyright (C) 2018 by John Kitchin. See the License for information about copying.
Org-mode version = 9.1.14 | http://kitchingroup.cheme.cmu.edu/blog/category/optimization/ | CC-MAIN-2020-05 | refinedweb | 715 | 64.71 |
A User Interface Library / GUI-Framework to
develop Progressive Web Apps (PWA) in Dart.
Homepage | PUB | Facebook | Kitchen Sink | GitHub | GibtHub WebSite + Samples
I switch from the old, unsupported DI-Package to Dice
It's awesome - check it out.
Google switched from MaterialDesignLite to Material Components for web
The Dart-Version makes the same move. I'm working on "Material Components for Dart"
Stay tuned - I'll make the move for you as smooth as possible..
MDL/Dart is also on Facebook
Material Design Lite lets you add a Material Design look and feel to your dynamic websites and web app. It doesn't rely on any JavaScript frameworks or libraries. Optimised for cross-device use, gracefully degrades in older browsers, and offers an experience that is accessible from the get-go.
Since v1.18 MDL/Dart is STRONG_MODE compliant!
If you use material.css from cdn.rawgit.com - don't forget to specify your MDL-Dart version in for your css-link
<link id="theme" rel="stylesheet" href="<latest mdl-dart version>/red-pink/material.min.css"> <!-- Something like this: --> <link id="theme" rel="stylesheet" href="">
More on themes:
All mdl-js-xxx CSS-classes are gone! It's not necessary anymore to define e.g. mdl-button and! mdl-js-button for a MDL-Widget. The Widget-class is enough.
<!-- NEW --> <button class="mdl-button mdl-button--colored mdl-ripple-effect">Flat</button> <!-- OLD --> <button class="mdl-button mdl-js-button mdl-button--colored mdl-ripple-effect">Flat</button>
Here is a short guide to help you setting up your MDL/Dart page
Visit the website for a "Quick start" or check out the Kitchen Sink
Download all the samples as TGZ from here
(REACT-like Actions, ActionBus, Dispatcher and DataStore)
MDLFlux in action: ToDO-Sample (Source)
All samples-sources are now on GH dart-material-design-lite-site
Please file feature requests and bugs at the issue tracker.
Material Design Lite for Dart
This CHANGELOG.md was generated with Changelog for Dart
Add this to your package's pubspec.yaml file:
dependencies: mdl: ^2.2.2
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:mdl/mdl. | https://pub.dev/packages/mdl | CC-MAIN-2019-30 | refinedweb | 389 | 57.47 |
There are primarily two ways to connect to servers for data exchange:
In practice, socket programming is commonly associated with TCP/IP and UDP/IP communications. TCP is a connection-oriented network protocol that guarantees reliable and in-order delivery of packets (through acknowledgements). Coupled with IP, TCP is adopted as a popular networking protocol by applications such as web browsers and email clients. In contrast, UDP is a connection-less network protocol that sends packets from one point to another, with one exceptionit does not provide reliable and guaranteed delivery.
Sockets programming using TCP/IP is straight-forwardone party listens for incoming data and the other party sends the data (both parties can listen for data and send data at the same time). When using sockets, you send the data in raw directly without needing to encapsulate the data using a messaging medium (such as XML), and because of this socket is an efficient way to exchange data between a device and a server (or another client). The downside to using sockets is that it is relatively more complex and requires the programmer to write the code for the server and the client.
To use sockets in your .NET CF application, import the following namespace:
using System.Net.Sockets;
Receiving Data
You can listen for incoming data using the TcpListener class's AcceptTcpClient() method (if you recall the code for infrared communication the concept is similar). However, like the infrared example, the AcceptTcpClient() method is a blocking call, which means that the method will block until a client is connected. While this is alright for infrared communication (you only communicate with one device at a time), this is not really practical for sockets communication. For sockets communication, it is likely that you have multiple clients connected to your server at any one time and hence you need to do some extra work to ensure that your server supports multi-users.
To do so, create a class called Client and code it as shown in Listing 3.
Here, the constructor takes in a TcpClient object and starts to read from it asynchronously using the receiveMessage() method. Once the incoming data is read, it continues to wait for more data.
To ensure that the server supports multi-user, you use a TcpListener class to listen for incoming client connections and then use an infinite loop to accept new connections. Once a client is connected, you create a new instance of the Client object and continue waiting for the next client. This is shown in the code below:
const string SERVER_IP = "192.168.1.1";
const int PORT_NO = 500;
IPAddress localAddress = IPAddress.Parse(SERVER_IP);
//---listen at the specified address---
TcpListener listener = new TcpListener(localAddress, PORT_NO);
//---start listening---
listener.Start();
while (true)
{
Client user = new Client(listener.AcceptTcpClient());
}
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
WebSite
Subject
(Maximum characters: 1200). You have 1200 characters left. | http://www.devx.com/wireless/Article/38030/0/page/3 | CC-MAIN-2015-22 | refinedweb | 495 | 53 |
Projects
Here is an up-to-date list of finished tickets that were worked on at this Sage Days workshop and Sage Days 35.5 (I don't know how to search for sd35 only).
Here is an up-to-date list of tickets that were worked on at this Sage Days workshop and that are still being worked on (and those for Sage Days 35.5, see above).
Contents
- Projects
- Put flint2 into Sage
- Switch some of the /eclib/mwrank code to use flint2, and upgrade the eclib spkg in Sage
- Help the Singular developers make better use of flint2
- --(Linear algebra mod p, for log_2 p = 64)--
- Linear algebra mod p^n, for log_2 p small-ish
- BKZ 2.0
- Improve polynomial factoring mod p in flint2
- Modular forms code in Sage
- Open MP and FLINT
- Miscellaneous Sage Algebra and Number Theory patches
- Simon and ComputeL GP scripts
- Elliptic curve isogenies
- Mestre's algorithm for constructing hyperelliptic curves from their invariants
- Tate's Algorithm over function fields
- Fix some memory leak that was found using elliptic curves
- Implement finite algebras
- Things related to PARI/GP
Put flint2 into Sage
- People: Bill H., Mike H., Fredrik J., Andy N., Sebastian P.
- Building flint2 in Sage
Update MPFR to 3.1.0 - (Mike Hansen)
Update MPFI to 1.5.0 -
Reinstall
- Install flint2 spkg (beware, this will break Sage)
- touch SAGE_ROOT/devel/sage/sage/combinat/partitions.*
- Run "sage -b"
Switch some of the /eclib/mwrank code to use flint2, and upgrade the eclib spkg in Sage
- People: John C., David H., Martin R., Maarten D., Flint developers
Sage has a rather old version of eclib in it. It should be easy to upgrade the spkg. DONE: is ready for review -- in fact has just received a positive review!
Help the Singular developers make better use of flint2
- People: Martin L., Simon K., Burcin E., Flint developers
Updated my (mlee) experimental interface from Flint2 to Singular, to make use of the new polynomial factorization over Z/p. This sped up some of Singular's tests by a factor of 2 (compared to the regular Singular which uses NTL). However there are still some issues related to maybe mpir and/or the lack of a half gcd in Flint2 which need to be investaged.
You can have a look at the Singular FLINT interface here:. And hopefully this will be extended soon (use FLINT multiplication, division etc. during multivariate polynomial factorization)
In the near future it would be great if FLINT supported:
- asymptotically fast GCD for Z[x]
- build system improvements
- version number in header file (to help auto* decide if we have the right version)
To replace NTL completely, we need:
- factorization over Z[x]
- factorization over GF(p^k)[x]
- LLL
--(Linear algebra mod p, for log_2 p = 64)--
- People: Martin A.
Flint2 has an implementation for asymptotically fast linear algebra mod p for p up to 2^64. I (malb) am curious whether it can be improved using ideas inspired by M4RIE, i.e., replace multiplications by additions using pre-computation tables. Whether this is beneficial will depend on how much slower multiplication is than additions.
Update (2011-12-15 10:57): It seems the difference between scalar multiplication and addition is too small for these tricks to make sense.
Update (2011-12-20 11:10): Okay, project cancelled, none of the tricks I could think of make sense.
#include <flint.h> #include <nmod_mat.h> #include <profiler.h> #include <stdio.h> #include "cpucycles-20060326/cpucycles.h" int main(int argc, char *argv[]) { nmod_mat_t A,B,C; flint_rand_t state; unsigned long long cc0 = 0, cc1 = 0; unsigned long i,j; unsigned long long p = 4294967311ULL; flint_randinit(state); nmod_mat_init(A, 2000, 2000, p); nmod_mat_init(C, 2000, 2000, p); nmod_mat_randfull(A, state); cc0 = cpucycles(); nmod_mat_scalar_mul(C, A, 14234); cc0 = cpucycles() - cc0; printf("scalar multiplication: %llu\n",cc0); cc1 = cpucycles(); for (i = 0; i < A->r; i++) { for (j = 0; j < A->c; j++) { C->rows[i][j] = A->rows[i][j] + A->rows[i][j]; } } cc1 = cpucycles() - cc1; printf("addition: %llu\n",cc1); printf("ratio: %lf\n",((double)cc0)/(double)cc1); nmod_mat_clear(A); nmod_mat_clear(C); flint_randclear(state); return 0; }
Gives a ratio of about 4.5. But then, some of it is due to load/store times, so it might still make sense to try.
Linear algebra mod p^n, for log_2 p small-ish
- People: Martin A., Simon K., Johan B., Burcin E.
Linear algebra over GF(pk) can be reduced to linear algebra over GF(p) and for GF(2k) the performance is very nice. Hence, it would be a good project to develop some somewhat generic infrastructure for dense matrices over GF(p^k), or even *any* extension field? The natural place to put this would be LinBox but perhaps we can start stand-alone and then integrate it with LinBox if LinBox is too scary to start with. Some references (concerning prime slicing) are given at trac ticket #12177
#12177 contains an experimental patch implementing templated matrix classes with the polynomial with matrix coefficients representation. The patch also implements naive and toom multiplication of matrices over GF(p^k) using FFLAS.
Some timings:
p = 17, n = 2000 k magma naive toom 2 2.620 4.51 4.39 3 17.900 10.25 7.32 4 54.320 19.35 10.11 5 33.480 28.80 13.07 6 50.120 44.75 15.93 7 46.860 56.35 19.12 8 71.590 81.65 22.04 9 79.580 - magma timings are on a different machine with similar performance
BKZ 2.0
- People: Martin A., Andy N.
At AsiaCrypt 2011 Chen and Nguyen presented their new BKZ implementation which is much much more efficient than that in NTL. As far as I understand, the main improvements are due to "extreme pruning" as presented in a paper at EuroCrypt 2010 and perhaps careful parameter choice. As far as I understand, they do not plan to make their code available. I don't know how much work it would be, but perhaps it would be a nice idea to patch NTL's BKZ to include extreme pruning and/or to port it to Flint2?
Improve polynomial factoring mod p in flint2
- People: Fredrik J., Andy N., David H.
The Cantor-Zassenhaus implementation in the flint2 nmod_poly module could be optimized:
- Make exponentiation faster by precomputing a Newton inverse of the modulus
- Use sliding window exponentiation
- Use the von zur Gathen / Shoup algorithm (adapt the fast power series composition code for modular composition)
Modular forms code in Sage
- People: David L., John C., Jan V., Frithjof, Johan B., Maarten D., Martin R., Simon K.
- review patches
#5048: Johan B. has done this one. (reviewed positivly)
#11601: depends on #5048; now rebased; Johan working on this. Done. (reviewed positively)
#10546: depends on #11601; Jan V to take a look (reviewed positively)
#12043: DL to work on this (needs work)
#10658: Martin R and Frithjof will have a look at this (reviewed positively)
#12124: Martin R and Frithjof will have a look at this (reviewed positively)
Start working towards putting Edixhoven's algorithm into Sage. The meta-ticket for this is #12132.
Open MP and FLINT
- People: David H., Fredrik J., Bogdan B., Julian R.,
Miscellaneous Sage Algebra and Number Theory patches
- People: Francis C., Monique v B., Florian B., Sam S., Michiel K, Bogdan B., Colton, Jan, Marco S., Paul Z., Johan B., Daniel B.
- Patches with positive review or closed tickets:
#11235 Make the ipython edit magic command edit the right file and show both files when doing "??"
#11319 Cannot create homomorphism from prime residue field to finite field
#11417 binomial of polynomial is not polynomial
#11673 is_unit not properly implemented for algebraic integers
#11838 Multivariate factorization over non-prime finite fields hangs
#12156 Pretty print LatexExpr directly
#12176 Compute Minkowski bound for relative number fields
#12182 Calculate the trace dual of an order in a number field
#12183 Absolute and relative norm functions for number field elements
#12185 Bug in norm for orders of relative number fields
#12191 is_squarefree for integer polynomials
#12196 Improve latex for quadratic fields
#12210 GF(p) constructor should check primality of p only once
#12218 Content of general polynomial
- Patches needing review:
- Patches needing work or info:
Simon and ComputeL GP scripts
- People: John C., Martin R.
Revive work of March Sage Days: see
Elliptic curve isogenies
People: Kimi T., John C., François Morain., Monique v B., Özge Ç., Marco S.
- Sage has a fast implementation of l-isogenies for l=2,3,5,7,13 (for which X_0(l) has genus zero). Kimi has a similarly fast algorithm for those l for which X_0(l) is hyperelliptic (l up to 71), implemented in Sage, which need to be made into a patch for Sage.
Mestre's algorithm for constructing hyperelliptic curves from their invariants
- People: Florian B., Marco S., Lassina D.
- Trac tickets:
#6341 (needs work) contains Florian's code for
- Mestre's algorithm
- The covariant z_0
- SL2(ZZ)-reduction
#12199 (new) case of curves with automorphisms
#12200 (new) case of characteristic two (and three, and five)
#12204 (needs work, depends on #6341) reducing the defining polynomial of hyperelliptic curves
no ticket yet: no code yet for covariant z, reference for the invariant:
- no ticket yet: SL2(number field)-reduction
- case of real quadratic fields of class number one: bad code that works surprisingly well (Marco, not on trac), to be finished later
Tate's Algorithm over function fields
- People: Frithjof S, John C., Julian R.
There is a Magma implementation based on John's number field implementation here.
Fix some memory leak that was found using elliptic curves
- People: Simon K., Jean-Pierre F., Paul Z.
The solution is to use weak references for caching homsets. Little problem: Up to now, it was possible to have category objects that are no instances of CategoryObject and thus do not support weak references. But people seem to agree that this should be strongly deprecated. #11521 needs review!
The topic is also related with #715, which proposes to use weak references for the coerce map cache. The problem is that the cache uses a special hand-made dictionary (for efficiency), and so we have no simple drop-in replacement such as WeakKeyDictionary.
Implement finite algebras
- People: Johan B., Michiel K.
The trac ticket for this is 12141.
Things related to PARI/GP
- People: Jeroen D.
#12203: Implement is_PariGpElement
#12158: Segfault in PARI's err_init() during pari_init_opts(): closed (fixed)
#9948: Conversion between p-adics and PARI/GP | https://wiki.sagemath.org/SageFlintDays/projects?action=print | CC-MAIN-2018-09 | refinedweb | 1,764 | 60.65 |
Table Of Content
Python exception handling Tutorial
1- What is Exception?
- First, let's see the following illustration example:
In this example, there is an part of error code which results from the division by 0. The division by 0 causes the exception: ZeroDivisionError
- helloExceptionExample.py
print ("Three") # This division no problem. value = 10 / 2 print ("Two") # This division no problem. value = 10 / 1 print ("One") d = 0 # This division has problem, divided by 0. # An error has occurred here. value = 10 / d; # And the following code will not be executed. print ( (6).
- In step (7), the program divided by 0. Program ends.
- And step (8), code has not been executed.
We will modify code of above example.
- helloCatchException.py
print ("Three") value = 10 / 2 print ("Two") value = 10 / 1 print ("One") d = 0 try : # This division has problem, divided by 0. # An error has occurred here (ZeroDivisionError). value = 10 / d; print ("value = ", value) except ZeroDivisionError as e : print ("Error: ", str(e) ) print ("Ignore to continue ...") print ("Let's go!");
- And the results of running the example:
- We will explain the flow of the program by the following illustration images.
- Steps (1) to (6) are completely normal.
- Exception occurs in step (7), the problem divided by zero.
- Immediately it jumps in executing the command in catch block, step (8) is skipped.
- Step (9), (10) is executed.
- Step (11) is executed.
2- Exception Hierarchy
- This is the model of hierarchical map of Exception in Python.
- The highest class is BaseException
- Two direct subclasses is Exception and KeyboardInterrupt.
- The Exception which is builtin of CSharp is usually derived from BaseException. Meanwhile, the programmers' Exception should inherit from Exception or its subclasses.
3- Handling exception with try-except
- We write a class that inherits from Exception.
- See more:
- The checkAge function to check the age, if the age is less than 18 or greater than 40, an exception will be thrown.
- ageexception.py
# Python 3.x class AgeException(Exception): def __init__(self, msg, age ): super().__init__(msg) self.age = age class TooYoungException(AgeException): def __init__(self, msg, age): super().__init__(msg, age) class TooOldException(AgeException): def __init__(self, msg, age): super().__init__(msg, age) # Function to check age, it may raise exception. def checkAge(age): if (age < 18) : # If age is less than 18, an exception will be thrown # This function ends here. raise TooYoungException("Age " + str(age) + " too young", age) elif (age > 40) : # If age greater than 40, an exception will be thrown. # This function ends here. raise TooOldException("Age " + str(age) + " too old", age); # If age is between 18-40. # This code will be execute. print ("Age " + str(age) + " OK!");
- Example:
- tryExceptDemo1.py
import ageexception from ageexception import AgeException from ageexception import TooYoungException from ageexception import TooOldException print ("Start Recruiting ...") age = 11 print ("Check your Age ", age) try : ageexception.checkAge(age) print ("You pass!") except TooYoungException as e : print("You are too young, not pass!") print("Cause message: ", str(e) ) print("Invalid age: ", e.age) except TooOldException as e : print ("You are too old, not pass!") print ("Cause message: ", str(e) ) print("Invalid age: ", e.age)
- Run the example:
- In the following example, we will catch exceptions through parent exceptions.
- tryExceptDemo2.py
import ageexception from ageexception import AgeException from ageexception import TooYoungException from ageexception import TooOldException print ("Start Recruiting ...") age = 51 print ("Check your Age ", age) try : ageexception.checkAge(age) print ("You pass!") except AgeException as e : print("You are not pass!") print("type(e): ", type(e) ) print("Cause message: ", str(e) ) print("Invalid age: ", e.age)
- Running the example:
4- try-except-finally
- We have got accustomed with catching error through try-except block. try-except-finally is used to fully handle exception. The finally block is always executed, regardless of whether the exception occurs in the try block or not.
- try - except - finally
try : # Do something here except Exception1 as e : # Do something here except Exception2 as e : # Do something here finally : # Finally block is always executed # Do something here
- Example:
- tryExceptFinallyDemo.py
def toInteger(text) : try : print ("-- Begin parse text: ", text) # An Exception can throw here (ValueError). value = int(text) return value except ValueError as e : # In the case of 'text' is not a number. # This 'except' block will be executed. print ("ValueError message: ", str(e)) print ("type(e): ", type(e)) # Returns 0 if ValueError occurs return 0 finally : print ("-- End parse text: " + text) text = "001234A2" value = toInteger(text) print ("Value= ", value)
- Running the example:
- This is the flow of the program. Finally block is always executed.
pass Statement
- If you do not want to process anything in the 'except' or 'finally' block you can use the 'pass' statement. The pass statement does not do anything, it's like a null statement.
- passStatementExample.py
print ("Three") try : value = 10 / 0; except Exception as e: pass print ("Two") print ("One") print ("Let's go")
5- Re-throw exception
- While handling the exception, you can catch that exception and handle it or you can re-throw it.
- reRaiseExceptionDemo1.py
def checkScore(score) : if score < 0 or score > 100: raise Exception("Invalid Score " + str(score) ) def checkPlayer(name, score): try : checkScore(score) except Exception as e : print ("Something invalid with player: ",name, ' >> ', str(e) ) # re throw exception. raise # ------------------------------------------ checkPlayer("Tran", 101)
- For example, catch an exception and throw an other exception.
- reRaiseExceptionDemo2.py
def checkScore(score) : if score < 0 or score > 100: raise Exception("Invalid Score " + str(score) ) def checkPlayer(name, score): try : checkScore(score) except Exception as e : print ("Something invalid with player: ",name, ' >> ', str(e) ) # throw new exception. raise Exception("Something invalid with player: "+ name + " >> "+ str(e)) # ------------------------------------------ checkPlayer("Tran", 101)
6- Exception Wrapping
- Python allows catching exceptions, and throws a new exception. New exceptions can store information of the original exception, which you can access through the __cause__ attribute.
try : # Do Something ... except Exception as e : raise OtherException("Message...") from e
- See full example:
- wrapExceptionDemo.py
# Python 3.x: # Gender exception class GenderException(Exception): def __init__(self, msg): super().__init__(msg) # Language exception class LanguageException(Exception): def __init__(self, msg): super().__init__(msg) class PersonException(Exception): def __init__(self, msg): super().__init__(msg) # This function may throw GenderException def checkGender(gender): if gender != 'Female' : raise GenderException("Accept female only") # This function may throw LanguageException def checkLanguage(language): if language != 'English' : raise LanguageException("Accept english language only") def checkPerson(name, gender, language): try : # May throw GenderException checkGender(gender) # May throw LanguageException checkLanguage(language) except Exception as e: # Catch exception and raise other exception. # New exception has __cause__ = e. raise PersonException(name + " does not pass") from e # -------------------------------------------------------- try : checkPerson("Nguyen", "Female", "Vietnamese") except PersonException as e: print ("Error message: ", str(e) ) # GenderException or LanguageException cause = e.__cause__ print ('e.__cause__: ', repr(cause)) print ("type(cause): " , type(cause) ) print (" ------------------ ") if type(cause) is GenderException : print ("Gender exception: ", cause) elif type(cause) is LanguageException: print ("Language exception: ", cause) | http://o7planning.org/en/11421/python-exception-handling-tutorial | CC-MAIN-2017-30 | refinedweb | 1,135 | 50.43 |
go to bug id or search bugs for
Description:
------------
In a certain condition, a call to the class method offsetGet() via $instance['literalString'] is turned into $instance[anotherLiteral] when OPcache is enabled.
Steps to reproduce:
1. On Windows x64, extract php-7.3.0-nts-Win32-VC15-x64.zip into the current directory
2. Save test script as test.php
3. Make sure no PHP built-in server is running (as shared memory matters?)
4. Launch PHP built-in server by running a command:
php -c php.ini-development -d extension_dir=ext -d zend_extension=php_opcache.dll -S 127.0.0.1:8000
5. Open browser and go to
The output is: string(1) "a"
6. Touch test.php to update the modification time, and wait 3 seconds (opcache.revalidate_freq)
7. Reload the browser and confirm the output
Test script:
---------------
<?php
namespace Foo;
class Bar { public function get() {} }
class Record implements \ArrayAccess {
public function offsetSet($offset, $value) { throw new \Exception; }
public function offsetGet($offset) { var_dump($offset); }
public function offsetExists($offset) { throw new \Exception; }
public function offsetUnset($offset) { throw new \Exception; }
}
class Baz {
public function run() {
$a = pow(1, 2);
$b = new Bar();
$c = new Bar();
$d = new Bar();
$id = $b->get('a', 'b', 'c');
$rec = new Record();
$id = $rec['a'];
}
}
(new Baz())->run();
Expected result:
----------------
The output is: string(1) "a"
Actual result:
--------------
The output is: string(1) "b"
Add a Patch
Add a Pull Request
Can't repro on Ubuntu, though the issue is certainly plausible. At a guess the second literal for the the offset lookup is not being preserved and being overwritten.
Can reproduce under valgrind:
==23813== Conditional jump or move depends on uninitialised value(s)
==23813== at 0x91B2F8: ZEND_FETCH_DIM_R_SPEC_CV_CONST_HANDLER (zend_vm_execute.h:39179)
==23813== by 0x93A255: execute_ex (zend_vm_execute.h:59027)
==23813== by 0x93B63D: zend_execute (zend_vm_execute.h:60215)
==23813== by 0x84E2D7: zend_execute_scripts (zend.c:1615)
==23813== by 0x789D5C: php_execute_script (main.c:2641)
==23813== by 0x93E6BA: do_cli (php_cli.c:997)
==23813== by 0x93FB05: main (php_cli.c:1389)
We have been looking into this issue in our own code as of last week while trying to ensure PHP compatibility with our application.
I can tell you, if it helps, that the issue does not exist in 7.3 RC3, so it was introduced some time after that.
The problem is that we're merging a Z_EXTRA=0 literal with a Z_EXTRA=undefined literal. This is basically the same as bug #76711, but that one only fixed the case of integer literals, while here it's a string :/
Automatic comment on behalf of nikita.ppv@gmail.com
Revision:;a=commit;h=93aabf1533bd3af673bb59cf283e6599ced3ab9a
Log: Fixed bug #77275
I think we have been running into this problem (or the integer version of it) on a busy custom website (no framework) with FPM and opcache, that was experiencing sudden crashes and termination of all processes (leading to 502 errors).
We set in php.ini:
opcache.optimization_level=0x7FFFBBFF
The second 'B' represents the removal of 0x400, or ZEND_OPTIMIZER_PASS_11 (1<<10) /* Merge equal constants */
So far the issue has not reoccurred.
Related To: Bug #76937 | https://bugs.php.net/bug.php?id=77275 | CC-MAIN-2021-10 | refinedweb | 508 | 56.66 |
Original text by MICHAŁ BENTKOWSKI
In this blogpost I’ll explain my recent bypass in DOMPurify – the popular HTML sanitizer library. In a nutshell, DOMPurify’s job is to take an untrusted HTML snippet, supposedly coming from an end-user, and remove all elements and attributes that can lead to Cross-Site Scripting (XSS).
This is the bypass:
Believe me that there’s not a single element in this snippet that is superfluous 🙂
To understand why this particular code worked, I need to give you a ride through some interesting features of HTML specification that I used to make the bypass work.
Usage of DOMPurify
Let’s begin with the basics, and explain how DOMPurify is usually used. Assuming that we have an untrusted HTML in
htmlMarkup and we want to assign it to a certain
div, we use the following code to sanitize it using DOMPurify and assign to the
div:
In terms of parsing and serializing HTML as well as operations on the DOM tree, the following operations happen in the short snippet above:
htmlMarkupis parsed into the DOM Tree.
- DOMPurify sanitizes the DOM Tree (in a nutshell, the process is about walking through all elements and attributes in the DOM tree, and deleting all nodes that are not in the allow-list).
- The DOM tree is serialized back into the HTML markup.
- After assignment to
innerHTML, the browser parses the HTML markup again.
- The parsed DOM tree is appended into the DOM tree of the document.
Let’s see that on a simple example. Assume that our initial markup is
A<img src=1 onerror=alert(1)>B. In the first step it is parsed into the following tree:
Then, DOMPurify sanitizes it, leaving the following DOM tree:
Then it is serialized to:
And this is what
DOMPurify.sanitize returns. Then the markup is parsed again by the browser on assignment to innerHTML:
The DOM tree is identical to the one that DOMPurify worked on, and it is then appended to the document.
So to put it shortly, we have the following order of operations: parsing ➡️ serialization ➡️ parsing. The intuition may be that serializing a DOM tree and parsing it again should always return the initial DOM tree. But this is not true at all. There’s even a warning in the HTML spec in a section about serializing HTML fragments:
It is possible that the output of this algorithm [serializing HTML], if parsed with an HTML parser, will not return the original tree structure. Tree structures that do not roundtrip a serialize and reparse step can also be produced by the HTML parser itself, although such cases are typically non-conforming.
The important take-away is that serialize-parse roundtrip is not guaranteed to return the original DOM tree (this is also a root cause of a type of XSS known as mutation XSS). While usually these situations are a result of some kind of parser/serializer error, there are at least two cases of spec-compliant mutations.
Nesting FORM element
One of these cases is related to the FORM element. It is quite special element in the HTML because it cannot be nested in itself. The specification is explicit that it cannot have any descendant that is also a FORM:
This can be confirmed in any browser, with the following markup:
Which would yield the following DOM tree:
The second
form is completely omitted in the DOM tree just as it wasn’t ever there.
Now comes the interesting part. If we keep reading the HTML specification, it actually gives an example that with a slightly broken markup with mis-nested tags, it is possible to create nested forms. Here it comes (taken directly from the spec):
It yields the following DOM tree, which contains a nested form element:
This is not a bug in any particular browser; it results directly from the HTML spec, and is described in the algorithm of parsing HTML. Here’s the general idea:
- When you open a
<form>tag, the parser needs to keep record of the fact that it was opened with a form element pointer (that’s how it’s called in the spec). If the pointer is not
null, then
formelement cannot be created.
- When you end a
<form>tag, the form element pointer is always set to
null.
Thus, going back to the snippet:
In the beginning, the form element pointer is set to the one with
id="outer". Then, a
div is being started, and the
</form> end tag set the form element pointer to
null. Because it’s
null, the next form with
id="inner" can be created; and because we’re currently within
div, we effectively have a
form nested in
form.
Now, if we try to serialize the resulting DOM tree, we’ll get the following markup:
Note that this markup no longer has any mis-nested tags. And when the markup is parsed again, the following DOM tree is created:
So this is a proof that serialize-reparse roundtrip is not guaranteed to return the original DOM tree. And even more interestingly, this is basically a spec-compliant mutation.
Since the very moment I was made aware of this quirk, I’ve been pretty sure that it must be possible to somehow abuse it to bypass HTML sanitizers. And after a long time of not getting any ideas of how to make use of it, I finally stumbled upon another quirk in HTML specification. But before going into the specific quirk itself, let’s talk about my favorite Pandora’s box of the HTML specification: foreign content.
Foreign content
Foreign content is a like a Swiss Army knife for breaking parsers and sanitizers. I used it in my previous DOMPurify bypass as well as in bypass of Ruby sanitize library.
The HTML parser can create a DOM tree with elements of three namespaces:
- HTML namespace ()
- SVG namespace ()
- MathML namespace ()
By default, all elements are in HTML namespace; however if the parser encounters
<svg> or
<math> element, then it “switches” to SVG and MathML namespace respectively. And both these namespaces make foreign content.
In foreign content markup is parsed differently than in ordinary HTML. This can be most clearly shown on parsing of
<style> element. In HTML namespace,
<style> can only contain text; no descendants, and HTML entities are not decoded. The same is not true in foreign content: foreign content’s
<style> can have child elements, and entities are decoded.
Consider the following markup:
It is parsed into the following DOM tree
Note: from now on, all elements in the DOM tree in this blogpost will contain a namespace. So
html style means that it is a
<style> element in HTML namespace, while
svg style means that it is a
<style> element in SVG namespace.
The resulting DOM tree proves my point:
html style has only text content, while
svg style is parsed just like an ordinary element.
Moving on, it may be tempting to make a certain observation. That is: if we are inside
<svg> or
<math> then all elements are also in non-HTML namespace. But this is not true. There are certain elements in HTML specification called MathML text integration points and HTML integration point. And the children of these elements have HTML namespace (with certain exceptions I’m listing below).
Consider the following example:
It is parsed into the following DOM tree:
Note how the
style element that is a direct child of
math is in MathML namespace, while the
style element in
mtext is in HTML namespace. And this is because
mtext is MathML text integration points and makes the parser switch namespaces.
MathML text integration points are:
math mi
math mo
math mn
math ms
HTML integration points are:
math annotation-xmlif it has an attribute called
encodingwhose value is equal to either
text/htmlor
application/xhtml+xml
svg foreignObject
svg desc
svg title
I always assumed that all children of MathML text integration points or HTML integration points have HTML namespace by default. How wrong was I! The HTML specification says that children of MathML text integration points are by default in HTML namespace with two exceptions:
mglyph and
malignmark. And this only happens if they are a direct child of MathML text integration points.
Let’s check that with the following markup:
Notice that
mglyph that is a direct child of
mtext is in MathML namespace, while the one that is a child of
html a element is in HTML namespace.
Assume that we have a “current element”, and we’d like determine its namespace. I’ve compiled some rules of thumb:
- Current element is in the namespace of its parent unless conditions from the points below are met.
- If current element is
<svg>or
<math>and parent is in HTML namespace, then current element is in SVG or MathML namespace respectively.
- If parent of current element is an HTML integration point, then current element is in HTML namespace unless it’s
<svg>or
<math>.
- If parent of current element is an MathML integration point, then current element is in HTML namespace unless it’s
<svg>,
<math>,
<mglyph>or
<malignmark>.
- If current element is one of
<b>, <big>, <blockquote>, <body>, <br>, <center>, <code>, <dd>, <div>, <dl>, <dt>, <em>, <embed>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <head>, <hr>, <i>, <img>, <li>, <listing>, <menu>, <meta>, <nobr>, <ol>, <p>, <pre>, <ruby>, <s>, <small>, <span>, <strong>, <strike>, <sub>, <sup>, <table>, <tt>, <u>, <ul>, <var>or
<font>with
color,
faceor
sizeattributes defined, then all elements on the stack are closed until a MathML text integration point, HTML integration point or element in HTML namespace is seen. Then, the current element is also in HTML namespace.
When I found this gem about
mglyph in HTML spec, I immediately knew that it was what I’d been looking for in terms of abusing
html form mutation to bypass sanitizer.
DOMPurify bypass
So let’s get back to the payload that bypasses DOMPurify:
The payload makes use of the mis-nested
html form elements, and also contains
mglyph element. It produces the following DOM tree:
This DOM tree is harmless. All elements are in the allow-list of DOMPurify. Note that
mglyph is in HTML namespace. And the snippet that looks like XSS payload is just a text within
html style. Because there’s a nested
html form, we can be pretty sure that this DOM tree is going to be mutated on reparsing.
So DOMPurify has nothing to do here, and returns a serialized HTML:
This snippet has nested
form tags. So when it is assigned to
innerHTML, it is parsed into the following DOM tree:
So now the second
html form is not created and
mglyph is now a direct child of
mtext, meaning it is in MathML namespace. Because of that,
style is also in MathML namespace, hence its content is not treated as a text. Then
</math> closes the
<math> element, and now
img is created in HTML namespace, leading to XSS.
Summary
To summarize, this bypass was possible because of a few factors:
- The typical usage of DOMPurify makes the HTML markup to be parsed twice.
- HTML specification has a quirk, making it possible to create nested
formelements. However, on reparsing, the second
formwill be gone.
mglyphand
malignmarkare special elements in the HTML spec in a way that they are in MathML namespace if they are a direct child of MathML text integration point even though all other tags are in HTML namespace by default.
- Using all of the above, we can create a markup that has two
formelements and
mglyphelement that is initially in HTML namespace, but on reparsing it is in MathML namespace, making the subsequent
styletag to be parsed differently and leading to XSS.
After Cure53 pushed update to my bypass, another one was found:
I leave it as an exercise for the reader to figure it out why this payload worked. Hint: the root cause is the same as in the bug I found.
The bypass also made me realize that the pattern of
Is prone to mutation XSS-es by design and it’s just a matter of time to find another instances. I strongly suggest that you pass
RETURN_DOM or
RETURN_DOM_FRAGMENT options to DOMPurify, so that the serialize-parse roundtrip is not executed.
As a final note, I found the DOMPurify bypass when preparing materials for my upcoming remote training called XSS Academy. While it hasn’t been officially announced yet, details (including agenda) will be published within two weeks. I will teach about interesting XSS tricks with lots of emphasis on breaking parsers and sanitizers. If you already know that you’re interested, please contact us on training@securitum.com and we’ll have your seat booked! | https://movaxbx.ru/2020/10/08/mutation-xss-via-namespace-confusion-dompurify-2-0-17-bypass/ | CC-MAIN-2021-04 | refinedweb | 2,129 | 57.4 |
Here’s an interesting question I got the other day:
We are writing code to translate old mainframe business report generation code written in a BASIC-like language to C#. The original language allows “goto” branching from outside of a loop to the interior of a loop, but C# only allows branching the other way, from the interior to the exterior. How can we branch to the inside of a loop in C#?
I can think of a number of ways to do that.
First, don’t do it. Write your translator so that it detects such situations and brings them to the attention of a human who can analyze the meaning of the code and figure out what was meant by the author of this bad programming practice. Branching into the interior of a loop is illegal in C# because doing so would skip all of the code that is necessary to ensure the correct behaviour of the loop. Odds are good that this pattern indicates a bug or at least some bad smelling code that should be looked at by an expert.
Second, this pattern is not legal in C# or VB.NET, but perhaps it is legal in another useful modern language. You could write your translator to translate to some other language instead of C#.
Third, if you want to do this automatically and you need to use C#, the trick is to change how you generate your loops. Remember, loops are nothing more than a more pleasant way to write a “goto”. Suppose your original code looks something like this pseudo-basic fragment:
10 J = 2
20 IF FOO THEN GOTO 50
30 FOR J = 1 TO 10
40 PRINT J
50 PRINT “—“
60 NEXT
70 PRINT “DONE”
The “obvious” way to translate this program fragment into C# doesn’t work:
int J = 2;
if (FOO) goto L50;
for(J = 1 ; J <= 10; J = J + 1)
{
PRINT (J);
L50: PRINT (“—“);
}
PRINT (“Done”);
because there’s a branch into a block. But you can eliminate the block by recognizing that a “for” loop is just a sugar for “goto”. If you translate the loop as:
int J = 2;
if (FOO) goto L50;
J = 1;
L30: if (!(J <= 10)) goto L70;
PRINT (j);
L50: PRINT (“—“);
J = J + 1;
goto L30;
L70: PRINT (“done”);
and now, no problem. There’s no block to branch into, so there’s no problem with the goto. This code is hard to read so you probably want to detect the situation of branching into a loop and only do the “unsugared” loop when you need to.
It is difficult to do a similar process that allows arbitrary branching in a world with try-finally and other advanced control flow structures, but hopefully you do not need to. Old mainframe languages seldom have complex control flow structures like “try-finally”.
> Branching into the interior of a loop is illegal in C# because doing so would skip all of the code that is necessary to ensure the correct behaviour of the loop.
Can you elaborate? Do you mean the loop condition for while-loops, and also the initializer for for-loops (in which case goto silently breaks the semantics of the loop – but this seemingly doesn’t apply to do-while), or some other code that the compiler generates undercover?
It’s more general than loops. In C# it is illegal to branch into the middle of any block from outside the block. With loops, one wants to be able to reason about the invariants of a loop without having to understand how control could have entered the loop. More generally, one should be able to reason about the control flow within a given block solely by looking at that block. You should not have to look at the whole method to understand how a given block in it could be used.
Another way to look at this is to think of the name of the label as being scoped to the block, just like the name of a local declared in the block is scoped to the block. Just as you cannot refer to a local by name outside of its scope, you cannot refer to a label by name outside of its scope.
— Eric
In a previous life, I had to do just such a beast and wound up doing exactly what you suggested. However I could do some static analysis and only write the IF/GOTO loop if there were a /targeted/ label inside of the original FOR loop. Otherwise, I’d write the more natural corresponding FOR loop.
If I did have to write the IF/GOTO loop I would insert a comment block that indicated what it read originally (FOR) and where the reference to the inner label came from. This facilitated hand-massaging the code later into something more manageable.
Thank goodness there were no COME FROM constructs! 🙂
You can’t do Duff’s Device in C#?! Jeez.
Gotos are fun. I wrote a (lexer) state machine once with no loop. It just bounced around with gotos until it bounced into an endpoint.
It’s weird, but good, that we’ve reached a point when gotos are an exotic construct that you never think about.
Simple suggestion, unroll the part of the loop that is being jumped to, outside of the loop, and insert that part at the jump location … This could get a little complicated if the jump traverses many branches of code, but otherwise I think it could be an option …
When you say this is legal in VB, you mean VB6, right – not VB.Net?
Bizarre. The customer who asked me about this issue said that it worked in VB.Net, but I have just checked the documentation and clearly it does not. Thanks for noticing that. — Eric
So how would you translate this into oh, FORTH, or Python, for example, neither of which has labels.. You need to figure out what the program REALLY needs to do and do it without spaghetti (even flying spaghetti monster) code.
Personally if I was going to manually refactor that code then I’d ditch the GOTOs altogether and just do something like:
IF (FOO) THEN
PRINT "—"
FOR J = 3 TO 10
PRINT J
PRINT "—"
ELSE
FOR J = 1 TO 10
PRINT J
PRINT "—"
ENDIF
PRINT "DONE"
Sure it’s a lot more verbose, but I find it a lot easier to read than the translated block with the looping GOTOs in it.
When people realize today’s if-else are also gotos, there’s gonna be rioting in the streets! 😉
Cleaner would be:
INTEGER JBASE
IF (FOO) THEN
PRINT "—"
JBASE = 3
ELSE
JBASE = 1
END IF
FOR J = JBASE TO 10
PRINT J
PRINT "—"
PRINT "DONE"
Suppose you have something like this:
int i = 0;
if( j < 5 ) goto inside;
for( ; i < 10 ; ++i )
{
do_something( );
inside:
do_more( );
}
Then why can’t you translate it like this?
int i = 0;
if( j < 5 ) do_something( );
for( ++i ; i < 10 ; ++i )
{
do_something( );
inside:
do_more( );
}
This is exactly what Pop Catalin suggested. It will vary on case by case basis, but it is easier to do and more easier to understand.
@Malcolm Fitzsimmons:
Agreed. I would probably pick between that style or my style depending on a few factors, such as how big the actual loop body was, how big the body of the FOO clause was and how often I expected FOO to be true.
Read "Structured Programming with go to Statements". That goto breaks invariant reasoning techniques was established to be wrong.
<Quote> Remember, loops are nothing more than a more pleasant way to write a "goto". </Quote>
Your momma’s a "goto."
On Error Goto Hell
Hell:
MsgBox "Before advanced control flow structures like try-finally, there were gotos."
My favorite "goto loop" pattern:
do { // you think that’s a loop? ha!
…
if (something) break; // look, no goto!
…
} while (false); // look, no label either!
Yeah, I worked with a guy who really liked that one.
Back in highschool, in my first programing class (Qbasic) our instructor forbade us from using goto’s… if your assignment had one goto in it…. he would trash it… THANK GOD! 8 years later MCAD certified, working for an awesome company… and i would have never gotten this far if I would have been allowed to think that goto was a good thing…
Eliminating goto was supposed to be the panacea for spaghetti code, and yet it continues to plague what could otherwise be fabulous code… Curious…
Guys, goto is not by itself a bad thing in any way. Its evilness is that it is very easy to misuse it, but by itself it is a useful tool in any imperative programming languages. Did you never have to break out of a nested loop? Or a switch nested inside a loop? And if you’re coding in C (not C++), goto is essentially the only robust way to do proper error handling, when you have to check for error (and potentially clean up) after every single function call.
The extreme argument against goto ("Goto is always evil. Always!") is also the argument against break and return, and, to some extent, throw. If you are truly willing to go to these lengths, then you should go all the way, and claim that nothing less than the purity of Haskell is desirable. Which would at least be a consistent position, even though not a very pragmatic one.
But, so long as you stick to an imperative language, some form of goto is necessary and desirable.
By the way you can do a Duff’s device in c#
static void DuffsDevice<T>(T[] from, T[] to)
{
int count = from.Length;
int position = 0;
switch (count % 8)
{
case 0:
to[position] = from[position++];
goto case 7;
case 7:
to[position] = from[position++];
goto case 6;
case 6:
to[position] = from[position++];
goto case 5;
case 5:
to[position] = from[position++];
goto case 4;
case 4:
to[position] = from[position++];
goto case 3;
case 3:
to[position] = from[position++];
goto case 2;
case 2:
to[position] = from[position++];
goto case 1;
case 1:
to[position] = from[position++];
if ((count -= 8) > 0) goto case 0; else break;
}
@pminaev:
An example of combined error-handling in C without using goto:
bool got_error = FALSE;
got_error = do_func_1();
got_error = got_error && do_func_2();
got_error = got_error && do_func_3();
got_error = got_error && do_func_4();
if (got_error) {
// combined error handling
}
Oops, wrong logic (it’s early) but you get the idea.
That’s assuming your functions return bool to indicate error – what about an int error code (note that in that case, && cannot be used, as it will coerce any non-0 "truth" value to 1)?
In practice, most C code I’ve seen uses "if … goto error" and so on. Probably also because it’s far clearer than this trick, too. As I’ve said earlier, sometimes goto is the right way to solve the problem, and working around it only makes things more complicated, all for the sake of "not saying the dreaded word".
We constantly use gotos in all forms except for jumping into a loop or back to the top of a function.
This is our way of drastically reducing the nesting level of if then else/for loops/etc. This point is lost when must younger developers trust the framework to clean up their own objects/allocation and ignore the longer term support cost for a particular block of code.
We’ve been burned with offshore written code that has 15+ levels of nesting in 500+ line functions because the developers refused to use gotos, returns and apparently got paid more for each line of code.
Common code we’ve seen
if (file open is ok)
{
500+ lines of code
}
else
{
do some error handling
}
This would be nested inside of a loop or multiple levels down inside of an if/then else block.
Another example would be multiple nested try/catch statements each to handle a resource allocation/connection failure instead the commonly used block:
if allocate 1 fails goto cleanup_one
if allocate 2 fails goto cleanup_two
if allocate 3 fails goto cleanup_three
body of function (or better a function call to the body to make it easier to see that the allocate and cleanup operations are done in the correct order)
cleanup_three: do cleanup of object 3
cleanup_two: do cleanup of object 2
cleanup_one: do cleanup of object 1
return
@pminaev: int error code can easily be handled in the same way by ANDing got_error with the result of comparing the function to the known good value e.g. if a negativereturn vale indicates error then:
got_error = !got_error && (func1() < 0);
If you dislike the "trick" with the logic short-circuiting then you can use a more explicit version:
bool got_error = FALSE;
got_error = do_func_1();
if (!got_error)
got_error = do_func_2();
if (!got_error)
got_error = (do_func_3() < 0);
if (got_error) {
// combined error handling
}
Either way, the only advantage to the goto approach is that it saves a couple of clock cycles. On most platforms, including most embedded system I’ve worked on, a few clock cycles in neglible.
> Either way, the only advantage to the goto approach is that it saves a couple of clock cycles.
You still miss my point. The advantage of the goto error handling approach is that it is usually more readable than any other workaround. Workarounds for the sake of them are not a good idea.
I always used to think that the GOTO statement was a bad thing, and programming should only use loops and other "prettier" flow techniques.
Over the last few weeks I was playing around writing an MSIL disassembler to look deeper into the code I write… and the first thing I noticed was that compiler translate loops into a seried of GOTO blocks. Typically a for loop would look something equivalent to:
(Initialise looping variable)
goto LABEL1;
LABEL2: (Whatever instructions are inside the block)
(Increment or decrement looping variable as required)
LABEL1: if (Check for loop to be run) goto LABEL 2;
So a trivial loop:
for (int ix = 0; ix < 10; ix++)
{
do_something();
}
do_loop_finished();
gets translated to:
int ix = 0;
goto LABEL1;
LABEL2: do_something();
ix++;
LABEL1: if (ix < 10) goto LABEL 2;
do_loop_finished();
So I am now wondering why we are always told to you loops rather than gotos, when they are just converted back to gotos, thus adding an additional level of translation (and hence sub-optimal code)!
I agree that gotos can be VERY evil…
BUT, they are very useful. I had to write a parser for fiels that could reach up to 20 gigs. Their content was never known until they were read. I came up with a 400 line optimised function, each of the other programmers came up with 700+ line functions.
They had similar flow patterns, except I used goto statements.
<quote>
Common code we’ve seen
if (file open is ok)
{
500+ lines of code
}
else
{
do some error handling
}
</quote>
solution…
if (!FileOpenIsOk)
{
error handling
}
function continues
@pminaev:
I agree that avoiding "goto" purely out of superstition is a bad idea. But I disagree that a goto version of that code is actually any more readable.
@Russell Anscomb:
Of course. And this is true of most languages. Loops are all just syntactic sugar for various Branch and Jump assembly instructions. Languages themselves are just abstractions of machine code. If you want absolute speed at all cost then why are you using a high-level language at all? You need to write directly in assembler (and you also need to be a genius to outperform most modern compilers).
However the rest of us see the benefit of readable and maintainable high-level code over absolute performance.
It’s probably also worth pointing out that in a modern language, like C#, most error handling will be done by exceptions – which in many ways offer all the same benefits as gotos in this scenario, with the added advantage of carrying information about why they were raised.
Of course ALL flow control becomes "goto" (possibly conditional) at the machine level. Anyone who does not understand that, needs to just hang up their had.
Much more dangerous than "goto" is the infamous "come from" instruction. When
using this, you can cause an arbitrary transfer from any point in the code:
10 x = 1
20 y = 1
30 x = 2
40 Print x,y,z
5000 Come From 20
5001 y = 99
5002 GoBack
(Sorry for posting this 14 days before it’s 35th original publication)
So you cant jump to a goto label within a loop from outside the loop? I didnt know this. But whats that piece of code that Reflector happens to show when decompiling a yield return statemachine?
private bool MoveNext()
{
try
{
switch (this.<>1__state)
{
case 0:
this.<>1__state = -1;
this.<>7__wrap4 = this.<>4__this.GetNodes().GetEnumerator();
this.<>1__state = 1;
while (this.<>7__wrap4.MoveNext())
{
this.<node>5__3 = this.<>7__wrap4.Current;
this.<>4__this.m_alreadyReturnedNodes.Add(this.<node>5__3);
this.<>2__current = this.<node>5__3;
this.<>1__state = 2;
return true;
Label_008C:
this.<>1__state = 1;
}
this.<>m__Finally5();
break;
case 2:
goto Label_008C;
}
return false;
}
fault
{
this.System.IDisposable.Dispose();
}
}
Is it just Reflector making up a while statement while the original il statements just are gotos?
Regards Florian
The discussion is moving a litle away from the first remark about automated migrated code.
Yes excessive and wrong use of Goto is very bad. But looking manual at 10.000.000 lines to remove them is a huge task. Analyzing and refactoring code solves a number of them but still not all.
The IL itself does allow it so why not the compiler. Let the programmer be the judge to use it or not.
In vb.net indead the goto into a for is not allowed but a goto into an if is. And possible other code levels?
Dim j As Integer
j = 1
GoTo l50 ‘ <—- allowed
If (1 = 1) Then
j = 2
l50:
j = 3
End If
GoTo l60 ‘<———– not allowed
For j = 1 To 5
l60:
I’m suprised that people can be so ‘religious’ in their renouncing of gotos. I thought kind of singlemindedness was a Java guy’s thing.
Yes, most of the time the higher level control flows are better, but there are exeptions.
Take the example of a controlflow schema from Visio. When you want to implement that with functions, you have a problem because after the call ends, you end up where you called the function. That’s not what you want, you wanted to go to another Process or Decision. (note the use of the words ‘go’ and ‘to’ 😉 In those cases program with Gotos is much more readable than trying to do that with functions.
Also, every function call is a push to the stack, they are not cheap. If you need really fast execution of your code, gotos can actually help you squeeze out that last bit of speed, although this can be at the expense of readabiliy, i’ll agree there.
Regards Gert-Jan
> The IL itself does allow it so why not the compiler. Let the programmer be the judge to use it or not.
Because the compiler must enforce a semantic level of meaning on the code so that it can effectively generate IL code that does what you wrote in the higher level language.
Consider the difference between for loops and if-else statements. There is quite a bit of difference in the amount of setup required to make each work.
if-else: No setup required, beyond performing the test condition and branching to the else part. Since there’s no setup, it’s no problem to goto into either the if-body or else-body.
for loop: At minimum, initializing the loop index and check that it meets the test condition. (foreach is even worse… find the appropriate enumerator, get that all setup, etc., etc…) With all this setup, how do you reasonably do a goto into the body of a for loop AND get provably correct code for EVERY case? Not too likely. (On the other hand, you can goto out of a for loop, because that amounts to little more than a break.)
I meant flowchart from Visio to be precise.
Nothing like stepping on a setjmp / longjump landmine. I’ve seen some pretty clever exception-like handling built around this construct using C/C++. It drove me nuts till I figured it out. Another developer had called setjmp from main, then whenever his deep library code encountered an error he’d call longjump. The longjump would set the instruction pointer back to the beginning of the program.
What would people say at goto’s funeral?
goto’s wife: "Oh my sweet goto, I can’t loop without you"
goto’s kids: "we want our goto back"
goto’s 3rd cousins’ brother in-laws’ 5th pets’ owner: "He was pure evil, evil I tell you!"
I would suggest converting the code to MSIL, then decompiling the MSIL into C#. That way you get C# code, but it will still have loops where ever possible.
This code
10 J = 2
20 IF FOO THEN GOTO 50
30 FOR J = 1 TO 10
40 PRINT J
50 PRINT "—"
60 NEXT
70 PRINT "DONE"
can write on C# using new bool variable:
j = 2;
bool foo1 = foo;
if (!foo)
j = 1;
for (; j <= 10; j ++)
{
if (!foo1)
print (j);
foo1 = false;
print ("—");
}
print ("DONE");
Any code do not repeates twice!
You can use foo instead foo1, when this variable do not required in other code part.
I don’t think anyone here fails to realize that all flow-of-control structures end up as GOTO’s at a machine level. The point is that the machine can manage the GOTO’s, but for humans its like reading a story, telling someone to jump two pages ahead, then jump three pages back. Yeah, you can do it, but geez, does that make it a good idea? Heavens – the computer can count to a zillion in binary, but that doesn’t mean its a good idea for human consumption.
That aside, my personal beef isn’t with "goto’s" per se, but when they are being used in obviously lazy situations when just a few minutes’ effort would have created a more streamlined control flow structure. In *most* cases, a GOTO is a hack, an amputation of logic where a few stitches of design and discretion would have avoided an ugly and usually unnecessary scar. I’ve rarely seen a structure made *more* elegant with a blunt GOTO. But that’s just me…
GOTO is all about sequence in the context of state. Code in this form is inimical to parallelisation.
This is easy to automate with functional programming languages, where dependencies on evaluation sequence are necessarily explicit. It is damn near impossible to automate in procedural languages where many dependencies are not only implicit but often indirectly implicit (due to side effects).
When a language requires explicit declaration of dependencies, laziness inhibits their spurious creation. Better quality code results, and it is incidentally more amenable to optimisation for multiple CPUs.
As in life, time is the great enemy.
I think people are confusing GOTO with branching.
GOTO is a programming statement which allows unstructured branching. Other programming statements (if-then, for, while, throw) only allow branching within a particular context or programming structure. Unstructured branching allows you to write incomprehensible code *very* easily. For example (using pseudo-basic)
10 x = 110
20 if ( x is even ) goto 40
30 x = 3 * x + 1
40 x = x / 2
50 if ( x > 10 ) goto 20
60 print x
I mean, never mind what x might be at the end, can we even be sure this will finish for different start values of x?
(Please don’t get caught up on this being a mathematical example, BTW. Statements 20 to 50 could be totally non maths related – as long as they interfere with each other you are going to get a problem).
It’s very easy with unstructured branching to start getting this sort of effect. Of course, you could use GOTO to duplicate structured branching (like duplicating a while loop), but why do it? It is far nicer when you come to look at your code to know there are *no* GOTOs in it rather than have to analyse whether each individual GOTO is sensible or not.
As to the oft quoted example of error handling in a sequence of method calls, I believe this indicates bad design. First of all I think you need to carefully consider what *is* an error, then isolate your error handling in one group of methods or classes or whatever, so that the rest of your code isn’t burdened with constantly having to check whether things are happening ok. i.e., it is better to write:
method_a()
{
method_a_1();
method_a_2();
etc
}
– than:
method_a()
{
if ( method_a_1() == ok )
{
if ( method_a_2() == ok )
{
etc
}}}}}}}}}}}}}}}.
– or some equivalent using gotos.
Where you simply are unable to pre-check for an error (like that nuclear refinery you were monitoring has just gone off-line), you should probably use an excepion and exit (gracefully) until somebody fixes the problem.
Richard
for(J = FOO ? 3 : 1; J <= 10; J++)
PRINT (string.Format("{0}rn—",J));
PRINT ("Done");
What I was trying to say is that the code should be refactored properly. Using Goto is ugly and difficult to read. Simply check what the code is trying to achieve and find the best way to replicate that functionality.
Which you will note was my first suggestion, yes. But what if you have five hundred thousand lines of goto-ridden mainframe code to translate? “Ugly and difficult to read” is better than “not working”, and cheaper and more accurate than “translate five hundred thousand lines of code by hand”. — Eric
Just because the original code uses a Goto, that doesn’t mean our new code has to use any at all. We could similarly do this:
int j = FOO ? 3 : 1;
while (j<=10)
PRINT (string.Format(“{0}rn—“,J++));
PRINT (“Done”);
Using your human intelligence to create a goto-free program that matches the semantics of one particular code fragment is easy. Writing a program that does that to any arbitrary fragment is rather more difficult, I assure you. — Eric
(with a lower case j in line 3, obviously)
Your point about the difficulty in understanding convoluted code is well taken. In fact some of the coded solutions produced wrong results. In the case where FOO is true they fail to start and end the list with "—".
Actually, your example and solution point out the fundamental translation problem and solution. Antique BASIC treated for a FOR loop index as a global variable and the loop condition was checked in the NEXT statement (Always on iteration was executed). The best way to handle the translation problem is to break the FOR loops into initialization, Value adjustment, and conditional jumps, much like you did ( I would check end conditions at the NEXT statement ).
There are also wonderful dialect specific factors like what is the value of j after the loop? Is it 10 or 11? That would depend on the specific implementation and is unfortunately something that may matter for the code that followed. After all it was often possible to jump out of FOR loops before termination.
if (StatusOK) {
if (DataAvailable) {
ImportantVariable = x;
goto MID_LOOP;
}
} else {
ImportantVariable = GetSomeValue();
MID_LOOP:
//Lots of code
}
I’m disappointed that no-one has mentioned Steve McConnell yet.
Eric:
If you have 500,000 lines of working code which is riddled with GOTO statements, and you then replicate it on a line-by-line (or fragment-by-fragment if you prefer) basis, there’s no guarantee that it’s going to work in the target environment. There are other factors such as that pointed out by bmann: The value of J upon exit may be different, which means the code could fail catastrophically at its first run, or even at some later point when FOO eventually does equal True, and then you’d be left with the serious headache of having to debug it. If you untangled it properly, it would make that debugging much more simple and the code would be readable to anyone else who came to look at it.
Aside from that, if it’s working, why would you move it to another language?
bmann: Good point… but with our new refactored code we should be able to see exactly where the problem is and what the problem is at aa glance 🙂
Seriously, we have methods now…… If you need to jump to something inside a loop, then it should probably be in a separate method.
With regard to Duff’s device (see comments from A.C.Hynes and Matthew Whited above) here is another C# version which is closer to the original. C# is surprisingly expressive at times:
namespace DuffsDevice
{
using System;
class Program
{
static void Main(string[] args)
{
unsafe
{
short[] data = new short[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
short register = -1;
fixed (short* dataPtr = &data[0])
{
DuffsDevice(®ister, dataPtr, data.Length);
}
Console.WriteLine(register);
}
}
/// <summary>
/// C# approximation to Duff’s device.
///
///);
/// }
/// }
/// </summary>
/// <param name="to"></param>
/// <param name="from"></param>
unsafe static void DuffsDevice(short* to, short* from, int count)
{
int n = (count + 7) / 8;
switch (count % 8)
{
case 0:
*to = *from++;
goto case 7;
case 7:
*to = *from++;
goto case 6;
case 6:
*to = *from++;
goto case 5;
case 5:
*to = *from++;
goto case 4;
case 4:
*to = *from++;
goto case 3;
case 3:
*to = *from++;
goto case 2;
case 2:
*to = *from++;
goto case 1;
case 1:
*to = *from++;
if (–n > 0) goto case 0; else break;
}
}
}
}
re: Duff’s Device… Hand-rolled optimization in C#? You guys are funny.
Turns out that a simple loop to iterate through a safe array can be a bit faster than my version of Duff’s Device in .NET. A loop to iterate through allocated stack space (using stackalloc) using an unsafe pointer is much faster. So, ‘Duff’s device’ in C# is sub-optimal. A case of hand-rolled de-optimization! Full marks to C# for being so expressive, but don’t use the technique!
this is funny stuff.
We are being guided to the old, frustrating, spider webs of looping with GOTOs.
this shouldnt practically be an approach in professional development using C#.
One time long ago I inherited a program written in C-tran. The author knew and thought in FORTRAN but had to code the app in C, and a veritable mess of code resulted that contained over 400 GO TO stetements. We stumbled along maintiaing it, never given the time to rewrite what was "working" but always allowed the time to analyze the mess of spaghetti for unintended consequences of the changes we were planning to make (and deal with the ones we did not foresee).
We recruited a bright guy from the customer support team to come into the product development team and his soel condition for accepting the position was they he be allowed to rewrite that app. It was accepted and the final product after3 months was easier to understand, easier to maintain and easier to extend.
GOTO is just a tool – but it is VERY dangerous in the hands of those who do not fear it.
Bad code is bad code. One needs to understand what branching into a FOR statement in their compiler means. I have used languages where there is only the goto. I have also see bad FOR statements.
10 FOR i = 1 TO 10
20 PRINT i
30 NEXT i
40 LET i = i * 2
50 PRINT i
What is the value of i? 20 or 22. This depends on the BASIC version.
Of course we should not use i outside to loop.
Reading most of this thread, I was amazed to discover how interesting it is to look at GOTO from 20 or 30 different points of view.
Getting back to the question that started this thread: the reason she/he wants to convert the old BASIC code to C# is (presumably) so that it will use the .NET CLR and interoperate with other .NET code. The problem is a kind of "impedance mismatch" meaning that BASIC is so dumb, and C# is so smart, that conversion is impractical. What we need is a cruder version of C# (call it "C-dumb") that is closer to the BASIC code. Has anyone considered FORTRAN?
Seriously, I once had to write a state machine once to handle Asterisk telephone events and it was a heck of a lot easier to write, read and modify using a few GOTOs versus keeping it "pure" with strange WHILEs.
The argument that MSIL uses GOTO so we should use them too is suspect. Consider writing a specification for a steel screw. Yes, it is made of molecules but when you order a certain screw do you really want to describe how all the molecules relate to one another? It is the wrong level of abstraction.
Maybe God Almighty will write the answer with fiery letters in the sky: "GOTO IS/IS NOT HARMFUL!"
How much knowlege is available about how the original program works, or (more importantly) what it is supposed to be doing?
A lot of old code can be reduced (in lines of codes) by 20 to 80%, purely on the basis that much of it was cut/pasted from other code that did the same thing on a different instance of data. This is why classes/objects/interfaces/etc came about to begin with.
I agree it is painful to take in hand thousands of lines of code and re-design and re-write it, but it many cases it is well worth it, and would take a lot less time than one might think (there is a certain moment of inertia that begins to build once you get familiar with a coding style no matter how ugly it might seem).
For the love of god!!
Why would you do a direct translation of the code? Just use a loop and some if conditions in it to skip sections.
DO NOT USE GOTO!
Why? Well, suppose you have a million lines of code to translate. Your choices are (1) spend 10 hours writing a literal translator that generates ugly code, (2) spend 10 hours writing a literal translator and then 90 hours rewriting all the code that involves gotos, or (3) spend 10000 hours rewriting the whole system from scratch. The costs of those three choices are $1000, $10000 and $1000000, respectively. Suppose you have to pay for it. Which would you choose? How much are you willing to spend on beautifying code that already works just fine? — Eric | https://blogs.msdn.microsoft.com/ericlippert/2009/03/10/loops-are-gotos/ | CC-MAIN-2016-36 | refinedweb | 5,821 | 68.5 |
Hi, I’ve created this Python 3 cheat sheet to help beginners to learn python. I’ll be adding new content over the next few days.
Download Python cheat sheet as PDF
Basics
The print() function displays the given message on the screen.
print("Hello World") # Hello World print(20+5) # 25 print(f'10 + 5 is {10+5}') # 10 + 5 is 15 print("python" * 2) # python python a, b, c = 1, 2, 3
Variables
In programming, a variable is a value that can be changed. All variables will have a storage location and a name. The variable name is usually used to refer to the value that is stored in a variable.
In Python, a variable is declared when you set a value to the variable. Unlike some other programming languages, Python does not have special keywords for declaring a variable.
Read more about Python variables.
a = 10 # int b = 10.5 # float c = "Python" # string d = 'p' # string e = 10j # complex f = True # bool
Type conversion
We perform type conversions to convert a variable from one data type to another.
Generally, there are two types of type conversions.
- Implicit conversions – This conversion is type-safe and requires no special code. It is performed by the compiler and no data loss occurs.
- Explicit conversions – These conversions require a cast operator. Explicit conversion cannot be made without the risk of losing information. A cast is a way of informing the compiler that you wish to make a conversion and you are aware of the possible data loss.
i = int("5") # 5 i = float(1) # 1.0 i = bool(10) # True i = bool(0) # False i = str(10) # 10
Conditional statements
These statements are used to make decisions based on one or more conditions. If the condition specified in a conditional statement is found true, then a set of instructions will be executed and otherwise, something else will be executed.
if a == 0: print('a = 0') elif a == 1: print('a = 1') else: print('a')
a, b, c = 1, 2, 3 # if a>b>c: if a>b and a>c: print('A is largest') elif b>c: print('B is largest') else: print('C is largest')
Ternary operator
It is a special conditional operator that compares two values and determines the third value based on the comparison.
a = 20 x = True if a >= 1 else False # x = False
print('Yes') if 11 > 10 else print("No") # Yes a, b = 10, 11 r = 'Yes' if a >= b else 'No' print(r) # No
Loops
With the help of a loop or looping statements, you can execute a statement or a set of statements until an expression is evaluated to false.
# For loop # for i in range(5) for i in range(0, 5): print(i) for i in range(4, -1, -1): print(i) # While loop i=0 while i <= 2: print(i) i+=1
Functions
A function contains a set of statements that creates output based on the given input or parameters.
# Empty function def myfun(): pass def myfun1(): print("hi") myfun() # No output myfun1() # hi
def add(a, b): return a + b add(1, 2) # 3 def calc(a, b): return a+b, a-b res = calc(5, 2) print("After addition", res[0]) # After addition 7 print("After subtraction", res[1]) # After subtraction 3
def msg(name="John Doe"): print("Hi", name) msg() # Hi John Doe msg("Jane") # Hi Jane def fnvar(*data): print(data[0]) fnvar(1, 2, 3) # 1 def fnkwargs(**data): print(data['name']) fnkwargs(name='John Doe', age=20) # John Doe
List
In Python, a list is an ordered collection of items of different data types. The items of a list are enclosed in [ ] brackets. Each list item is separated by a comma (,).
Create a list
# Creating a list lst = [0, 1, 2] print(lst[0]) # 0 print(lst[0:2]) # [0, 1] lst = ['1'] * 3 print(lst) # ['1', '1', '1']
Add elements
lst = [1, 2, 3] lst.append('last') # [1, 2, 3, 'last'] lst.insert(0, 'first') # ['first', 1, 2, 3, 'last'] lst.insert(20, 'New element') # ['first', 1, 2, 3, 'last', 'New element']
Remove elements
lst = [1, 2, 3, 4, 5, 2, 8, 9] print(lst.pop()) # Removes and returns the last element print(lst.pop(0)) # Removes and returns element at index 0 lst.remove(2) # Removes the first occurrence of 2 (Remove by value) del lst[0] # Removes element at index 0 del lst # Deletes the list
Modify elements
lst = [1, 2, 3] lst[0] = 5 # [5, 2, 3]
Sorting
# Sort lst = [0, 5, 3, 2, 4, 1] lst.sort() # [0, 1, 2, 3, 4, 5] lst.sort(reverse=True) # [5, 4, 3, 2, 1, 0] # Custom sorting ages = [ ["John", 20], ["Jane", 22], ["Janet", 21] ] # Sorts based on age ages.sort(key=lambda age: age[1]) print(ages) # [['John', 20], ['Janet', 21], ['Jane', 22]]
Tuple
A list is an ordered collection of items of various data types. The items of a tuple are enclosed in () brackets. Each list item is separated by a comma (,). Unlike a list, the elements of a tuple cannot be modified.
tpl = (1, 2, 3) print(tpl[0]) # 1 print(len(tpl)) # 3 print(tpl[0:2]) # (1, 2)
Dictionary
A dictionary is a collection of data as key-value pairs. Each item of a dictionary is contained in {} brackets.
Create a dictionary
d = {"name": 'python', "version": 3.7, 0: 1} print(d['name']) # python print(d[0]) # 1 print(len(d)) # 3
Add elements
d = {"name": 'python'} d['version'] = '3.7' # Add element d.update({"type": "dynamic", "oop": "yes"}) # Add multiple elements
Remove elements
d = {"name": "python", "type": "dynamic", "year": 1991} print(d.pop("year")) # Removes and returns the item del d["type"] # Removes the item print(d) # {'name': 'python'} d.clear() # Removes all the elements
Sets
Similar to a dictionary, the elements of a set are contained in {} brackets. The main difference between sets and other datatypes like list, tuple, and dictionary is that sets do not have an index.
Create a set
s = {5, 2, 1, 4} print(s) # {1, 2, 4, 5}
Add / remove items
s = {5, 2, 1, 4} s.add(55) print(s) # {1, 2, 4, 5, 55} print(s.pop()) # 1
Comprehension
Comprehensions in Python provide us with a short and succinct way to create new lists, set, or dictionary using iterable objects that have been already defined. Python supports the following comprehensions:
- List Comprehensions
- Dictionary Comprehensions
- Set Comprehensions
# List comprehension lst = [x for x in range(1, 6)] # [1, 2, 3, 4, 5] # Set comprehension st = {x for x in range(1, 6)} # {1, 2, 3, 4, 5} # Dictionary comprehension dict = {x: x*2 for x in range(1, 6)} # {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
Generator expression
Similar to comprehensions, generator expressions are also a convenient way to create iterable objects.
res = (x for x in range(6)) print(res) # <generator object <genexpr> at 0x000001E65CD5BE08> print(res[0]) # Error print(len(res)) # Error lst = list(res) # Converts to list
Unpacking
Unpacking is a method by which we extract the values of an iterable object to separate variables.
a = [1, 2, 3] b = [4, 5, 6] c = [*a, *b, "unpacked"] print(c) # [1, 2, 3, 4, 5, 6, 'unpacked'] x = {"x": 1} y = {"y": 2} z = {**x, **y} print(z) # {'x': 1, 'y': 2}
a = [1, 2, 3] def myfun(a, b, c): print(a+b+c) # myfun(a) # Error myfun(*a)
Lambda
A lambda expression is a special syntax to create functions without names.
x = lambda a, b, c: a + b + c print(x(5, 6, 2)) # 13
def myfunc(b): return lambda a: a * b dbl = myfunc(2) print(dbl(11)) # => 22
Datetime module
Python DateTime module comes with everything you need to access date and time.
import datetime a=datetime.date.today() print(a.strftime("%B/%A/%Y/%D")) # August/Friday/2019/08/23/19
Exception handling
Exception handling is the mechanism by which errors in the application are captured and handled. It is one of the most important features of a programming language.
In Python, Exception handling is done with the help of the following keywords:
- try
- except
- finally
- raise
try: a = 1/0 except: print('Division by zero is not possible')
try: print(a) except NameError: print('Variable is not declared')
try: 10/0 except ArithmeticError: print('An arithmetic error has occurred') finally: print('I will be executed even if there is no error')
try: raise Exception("An error occurred") finally: print("Error occured") try: raise ArithmeticError("An error has occurred") except Exception as e: print(e)
try: 10/0 except Exception as e: print(type(e).__name__)
try: a = int(input("Enter a positive number")) if a < 0: raise ValueError("Number is not valid") if a == 0: raise ArithmeticError("Division by zero error") except (ValueError , ArithmeticError): print("A value error or arithmetic error has occurred")
Class
A class is a blueprint of an object. An object in the real world will have properties like shape, color, weight, etc. Likewise, in object-oriented programming, a class defines certain properties, events, and functionalities that an object can have.
# Class class MyClass: name = "Hi from the class" # Constructor def __init__(self): self.age = 22 gender = 'Male' # Method def show_data(self): print(self.name) print(self.age) # print(gender) # Error # Creating object obj = MyClass() obj.show_data()
Single inheritance
Single inheritance enables a derived class to inherit properties and behavior from a single parent class.
class A: def fun1(self): print('Function 1') class B (A): def fun2(self): print('Function 2') obj = B() obj.fun1() obj.fun2()
Multiple inheritance
Single inheritance enables a derived class to inherit properties and behavior from multiple classes.
class A: __m = 'Private' def __init__(self): self.msg = 'Class 1' def fun1(self): print('Function 1') def same(self): print('Same A') class B: def fun2(self): print('Function 2') def same(self): print('Same B') class C (A, B): def fun3(self): self.fun1() self.fun2() self.same() # print(self.__m) # Cannot access private members # def same(self): # If uncommented, this method will be executed # print("override") obj = C() obj.fun3()
Multilevel inheritance
Multiple inheritance means that a class is inheriting the properties of a derived class.
class A: __m = 'Private' def __init__(self): self.msg = 'Class 1' def fun1(self): print('Function 1') class B (A): def fun2(self): print('Function 2') class C (B): def fun3(self): self.fun1() self.fun2() # print(self.__m) obj = C() obj.fun3()
Abstract classes
Generally, an abstract class is a class that contains abstract methods and cannot be instantiated. It serves as a blueprint for other classes expecting its child classes to implement its abstract methods.
Python by default does not provide abstract classes. But it has a module named ABC which provides the base for defining Abstract Base classes(ABC).
from abc import ABC, abstractmethod class Class1 (ABC): @abstractmethod def showmessage(self): print('From base class') @abstractmethod def logic(self): print('Logic in the derived class') @abstractmethod def errorchecking(self): print('You should implement logic in the child class') class Class2(Class1): def showmessage(self): super().showmessage() def logic(self): print('Custom logic') def errorchecking(self): print('Try commenting this method') obj = Class2() obj.showmessage() obj.logic() obj.errorchecking()
Attribute methods
These methods allow you to get or check the properties of an object.
class MyClass: def __init__(self, name, age): self.name = name self.age = age def showdata(self): print(f'Name: {self.name}, Age: {self.age}') cls = MyClass('John Doe', 25) print(getattr(cls, 'name')) setattr(cls, 'age', 22) print(getattr(cls, 'age')) print(hasattr(cls, 'name')) delattr(cls, 'age') print(hasattr(cls, 'age'))
Class methods
Class methods are not specific to any instances. So, they can be accessed without creating an object. It can access and modify the state of a class.
class MyClass: @classmethod def fun1(self): print('Hello World') MyClass.fun1() # THE METHOD CAN BE CALLED WITHOUT CREATING AN OBJECT
Class methods can access and modify the state of an instance.
class MyClass: a = 20 @classmethod def fun1(self): self.a = 21 def show_data(self): print(self.a) obj = MyClass() obj.show_data() # 20 MyClass.fun1() obj.show_data() # 21
Static methods
Like class methods, static methods can also be called without creating an object. But it cannot access or modify the state of a class. Also, it does not accept the class parameter and is created only once.
class MyClass: a = 'Static method will print this' @staticmethod def my_static_method(): print('Hi from static method') print(MyClass.a) def my_method(self): self.a = 'Instance method' print(f'Hi from {self.a}') cls = MyClass() cls.my_method() MyClass.my_static_method() # Hi from Instance method # Hi from static method # Static method will print this
Private methods
Private methods are methods that cannot be accessed outside the class and by child classes using inheritance.
class SeeMee: def youcanseeme(self): return 'you can see me'()) | https://www.geekinsta.com/python-3-cheat-sheet/ | CC-MAIN-2021-31 | refinedweb | 2,153 | 61.77 |
12.3) Consider a measurement of a three-component vector x, with x1 and x2 being drawn independently from a Gaussian distribution with 0 mean and unit variance, and x3 = x1 + x2.
a) Analytically calculate the covariance matrix of x
b) What are the eigenvalues?
C) Numerically verify these results by drawing a data set from the distribution and computing the covariance matrix and eigenvalues.
import numpy as np n = 100000 x1 = np.random.normal(0,1,n) x2 = np.random.normal(0,1,n) x3 = x1+x2 X = [x1,x2,x3] c = np.cov(X) print(c) # Covariance matrix: # [[ 1.00552305 -0.00540942 1.00011363] # [-0.00540942 1.00327819 0.99786877] # [ 1.00011363 0.99786877 1.9979824 ]] e = np.linalg.eig(c) print(e[0]) # Eigenvalues: # [ 2.99277382e+00 1.00136031e+00 1.76529821e-15]
D) Numerically find the eigenvectors of the covariance matrix, and use them to construct a transformation to a new set of variables y that have a diagonal covariance matrix with no zero eigenvalues. Verify this on the data set.
Continuing the excerpt of pca.py above:
print(e[1])
# Eigenvectors (col major):
# [[-0.40445603 0.70928273 0.57735027]
# [-0.41202885 -0.70491056 0.57735027]
# [-0.81648487 0.00437217 -0.57735027]]
# Cov(y) = M * Cov(x) * M^T
cy = np.dot(np.dot(e[1].T,c), e[1].T)
print(cy)
#
# [[ 2.61908171 0.80509741 -0.50471862]
# [ 0.80509741 0.98241759 0.30643185]
# [-0.50471862 0.30643185 0.38716296]]
12.4) Generate pairs of uniform random variables {s1,s2} with each component contained in [0,1].
a) Plot these data.
import numpy as np
import matplotlib.pyplot as plt
n = 100
s1 = np.random.uniform(0,1,n)
s2 = np.random.uniform(0,1,n)
plt.scatter(s1,s2)
plt.show()
b) Mix them (x = A*s) with a square matrix A = [[1 2] [3 1]] and plot.
Continuing from ica.py...
S = np.column_stack([s1, s2])
A = [[1,2],[3,1]]
mix = np.dot(S,A)
plt.scatter(mix[:,0], mix[:,1])
plt.show()
c) Make x zero mean, diagonalize with unit variance, and plot | http://fab.cba.mit.edu/classes/864.14/students/Borenstein_Greg/transforms/ | CC-MAIN-2018-34 | refinedweb | 352 | 61.43 |
- ChatterFeed
- 1Best Answers
- 0Likes Received
- 0Likes Given
- 0Questions
- 30Replies
Building Report
Hi,
Need to create a report which comprise of 3 objects.
2 objects are in Master detail relationship, while the other is having a lookup with one of those 2 .
for eg.
Objects P and Q are in a master-detail relationship, while R is having a lookup with P.
Test Code Failing at 90%
Basically, I have a VF page which is for a survey object that I am creating. The goal is to automatically send out a URL after a client has completed certain milestones. The URL will be part of an email template that will send a link to the site.com hosted version of the VF page with the clients account ID in the URL.. The client will complete the survey and upon clicking save, the survey will be inserted into the clients object by the extension which will draw the account ID from the URL....It all works fine in sandbox, testing just fails as I do not know how to test for AccountID when it gets it from the URL. These are my three codes:
VF page:
<apex:page
<apex:includeScript
<apex:includeScript
<apex:stylesheet
<apex:form
<apex:pageBlock
<apex:pageBlockSection
<apex:pageBlockSection
<apex:inputField
<div id="slider" style="length:50"/>
<apex:inputField
<apex:inputField
</apex:pageBlockSection>
</apex:pageBlock>
<apex:commandButton
</apex:form>
<script>
function getCleanName(theName)
{
return '#' + theName.replace(/:/gi,"\\:");
}
var valueField = getCleanName( '{!$Component.theForm.theBlock.theSection.value}' );
$j = jQuery.noConflict();
$j( "#slider" ).slider( {enable: true, min: 0, max: 10, orientation: "horizontal", value: 0} );
$j( "#slider" ).on( "slidechange",
function( event, ui )
{
var value = $j( "#slider" ).slider( "option", "value" );
$j( valueField ).val( value );
}
);
</script>
</apex:page>
This is my Extension:
public class extDestinySurvey
{
public Destiny_Survey__c Dess {get;set;}
private Id AccountId
{
get
{
if ( AccountId == null )
{
String acctParam = ApexPages.currentPage().getParameters().get( 'acct' );
try
{
if ( !String.isBlank( acctParam ) ) AccountId = Id.valueOf( acctParam );
}
catch ( Exception e ) {}
}
return AccountId;
}
private set;
}
public extDestinySurvey(ApexPages.StandardController controller)
{
Dess = (Destiny_Survey__c)controller.getRecord();
}
public PageReference saveDestinySurvey()
{
Dess.Account__c = AccountId;
upsert Dess;
// Send the user to the detail page for the new account.
return new PageReference('/apex/DestinyAccount?id=' + AccountId + '&Sfdc.override=1');
}
}
This is my Test that fails at 90%:
@isTest
private class TestExtDestinySurvey {
static testMethod void TestExtDestinySurvey(){
//Testing Survey extension
// create a test account that will be use to reference the Destiny Survey Record
Account acc = new Account(Name = 'Test Account');
insert acc;
//Now lets create Fact Finder record that will be reference for the Standard Account
Destiny_Survey__c DessTest = new Destiny_Survey__c(Account__c = acc.id, Explain_why_you_gave_your_rating__c = 'Because', How_likely_are_you_to_refer_Destiny__c = 8);
//call the apepages stad controller
Apexpages.Standardcontroller stdDess = new Apexpages.Standardcontroller(DessTest);
//now call the class and reference the standardcontroller in the class.
extDestinySurvey ext = new extDestinySurvey(stdDess);
//call the pageReference in the class.
ext.saveDestinySurvey();
}
}
Regarding related lists
hi i have three custom objects bills customers and products and what I am trying to do is that when we create a bill it should be populated on the customers related list.. And the bill should contain the related products on the .. there can be multiple products and it won't be possible to create a new product on every bill we should be able to select multiple products for a bill . how can we achieve this...
Why do we not have the Evaluation criteria of "When the record is only updated " in Workflow
Hi,
Why cany be have a Evaluation criteria of only on 'Update of a record '?
How is this gonna impact ?
Please let me know.
Thanks,
SQL query for salesforce objects
Hi,
I have a Contact and Opportunity(Donations) objects.
Opportunity is child obj for Contact.
In our case, for one contact there may be several opportunity( donation) records.
Close date and Amount are two fields in opportunity.
How to query for a condition in sql, most recent close date and most recent amount ? for a given date range and given amount range.
select name,max(date),amount
from donations
where closedate> '2011-3-4' and closedate < '2012-2-4' and amount>10 and amount<100
group by name
but it throws me an error on amount field as it is not in aggregate function.
how to modify this query such that for each contact record, it pulls donation's recent close date and recent amount. ( Consider for 1 contact we have 10 donations. so we need to pull 10th donation details.)
NOT EQUAL operator IN SOQL for picklist values
How to use not qual to operator in SOQL
In sql, fieldname !='%xyz%'
how about soql?
here am trying to check for the picklist values.
Thanks in advance
Workflow Condition Not Working
Hi,
I made a email alter when work flow condition is set as mentioned below.
In Lead there is a Column called Lead Status When lead status is changed to MQL or SQL it must trigger email to User.
I tried with Operator Contains(MQL, SQL) its not working, But when i mention equal to MQL or SQL it is working.
Please suggest me how to add this condition.
Thanks
Sudhir
Need to send email to multiple users (case owner, case creator)whenever case is closed
HI,
i need to send email to case owner and case creator whenever case is closed. i wrote after update trigger for this. but its not working. can anyone help me out from this.
Thanks & Regards
Ram
Trigger - i want reserve items
Hi im newbiee
I have problem i write :
trigger createReservation on Rezerwacja__c (before insert, before update) {
Set<id> rezSet = new Set<id>();
for (Rezerwacja__c rez : trigger.new){
rezSet.add(rez.Item__c);
}
List<Rezerwacja__c> rezList = [SELECT Rental_Date__c, Date_of_return__c, Status__c
FROM Rezerwacja__c
where id in :trigger.new];
List <Item__c> itList = [SELECT id, name FROM Item__c WHERE Item__c.Rezerwacja__c IN : rezList];
Map<Id, List<Rezerwacja__c>> rezMap = new Map<Id, List<Rezerwacja__c>>()
i wants the item was not available in a given period of time
Can somebody help me ??
Trigger Update event - how to "Save and Send updates" via the trigger
Simply updating the event does not send out the invites. Is there a way via apex to send updates to attendees when an event is updated?
Looping through multi-select picklist values
Could I get simple example of how to loop through a multi-select picklist field?
Thanks! | https://developer.salesforce.com/forums/ForumsProfile?userId=005F0000003Fl4bIAC&communityId=09aF00000004HMGIA2 | CC-MAIN-2020-16 | refinedweb | 1,048 | 56.45 |
The previous chapter was devoted to setting up a Hadoop cluster. In this chapter, we look at the procedures to keep a cluster running smoothly.
As an administrator, it is invaluable to have a basic understanding of how the components of HDFS—the namenode, the secondary namenode, and the datanodes—organize their persistent data on disk. Knowing which files are which can help you diagnose problems or spot that something is awry.
A running namenode has a directory structure like this:
${dfs.namenode.name.dir}/ ├── current │ ├── VERSION │ ├── edits_0000000000000000001-0000000000000000019 │ ├── edits_inprogress_0000000000000000020 │ ├── fsimage_0000000000000000000 │ ├── fsimage_0000000000000000000.md5 │ ├── fsimage_0000000000000000019 │ ├── fsimage_0000000000000000019.md5 │ └── seen_txid └── in_use.lock
Recall from Chapter 10 that the
dfs.namenode.name.dir property is a list of
directories, with the same contents mirrored in each directory. This
mechanism provides resilience, particularly if one of the directories
is an NFS mount, as is recommended.
The VERSION file is a Java properties file that contains information about the version of HDFS that is running. Here are the contents of a typical file:
#Mon Sep 29 09:54:36 BST 2014 namespaceID=1342387246 clusterID=CID-01b5c398-959c-4ea8-aae6-1e0d9bd8b142 cTime=0 storageType=NAME_NODE blockpoolID=BP-526805057-127.0.0.1-1411980876842 layoutVersion=-57 ...
No credit card required | https://www.safaribooksonline.com/library/view/hadoop-the-definitive/9781491901687/ch11.html | CC-MAIN-2017-17 | refinedweb | 202 | 50.63 |
On Wed, 14 Apr 1999, Vlad Harchev wrote: > IMO it would be good if the 'include' command had the list of settings that > can be specified in included file. So admins can specify > 'include:~/.lynx/colors:COLOR' > 'include:~/.lynx/keymap:KEYMAP' > 'include:~/.lynx/viewers:VIEWER' > > safely - and be sure that no critical options were altered by those files. > The suggested syntax is > include:<filename>[:[<OPTNAME>* ] ] > more samples: > include:~/.lynx/rc:COLOR KEYMAP VIEWER SUFFIX > include:/usr/local/lib/lynx-cfg.part: #all settings can be changed > > More brave approach: > Make ~/.lynxrc to be included by lynx.cfg (it's syntax must be changed to one > of lynx.cfg), with a list of options it can contain in the 'include' line. As > I understand, with LP's patch lynx.cfg can be edited at runtime and reloaded > in the same session - such feature as editing options specified in .lynxrc > at runtime is not the major privelege (or feature) of .lynxrc. So, a huge > section of code ~32KB can be removed when using this approach. > In present state, users with paranoid sysadm were to live with colors s/he Here is a patch that implements this functionality (except brave approach). It works as described. Features: ( ie if the list of allowed options is not specified, then the included file can use the same set of options, as the file that contained that 'include' command). * A funny and may be powerful feature - if you wish to allow included file to include others, you must specify 'include' in the list of allowed options. Sample: include:~/.lynx/suffixes:INCLUDE SUFFIX so thet NOTE: May be it will be good if the new lynx distributions will use directory ~/.lynx as the place for .lynxrc (so it can be called simply 'rc' - ie ~/.lynx/rc) and all bookmarks, cookies are also placed in this dir. Also we can provide as set of preconfigured keymaps (emacs,pc,etc), and add commented lines that contain 'include' of each of such file - so sysadm have only to uncomment the line s/he wishes (or the user have to copy the piece s/he likes in the ~/.lynx under general name). Or we can insert the following lines in lynx.cfg: #the following line includes user keymap. To users: put the keymap #(one of the distribution's keymap - emacs-keymap, vi-keymap, foo-keymap, or # composed by yourself) to the ~/.lynx/keymap include:~/.lynx/keymap:KEYMAP INCLUDE Midnight Commander also uses approach of putting all cfg files and caches in '~/.mc' . Here is a 'ls ~/.mc': history hotlist ini tree PS: It will be good if someone documented the 'include' command. As I remember, even the description of the plain 'include' is absent in the docs. PS2: I checked this patch with original dev22 with 'enable' and 'disable' of config-info. Best regards, -Vlad diff -ruP dev22-orig/src/LYReadCFG.c lynx-2.8.2dev22-fixed/src/LYReadCFG.c --- lynx-2.8.2dev22-orig/src/LYReadCFG.c Tue Apr 13 15:01:15 1999 +++ lynx-2.8.2dev22-fixed/src/LYReadCFG.c Thu Apr 15 00:15:27 1999 @@ -443,7 +443,7 @@ } #endif /* USE_COLOR_TABLE */ -#define MAX_LINE_BUFFER_LEN 501 +#define MAX_LINE_BUFFER_LEN 1501 typedef int (*ParseFunc) PARAMS((char *)); @@ -1214,14 +1214,32 @@ } } +#define NOPTS_ ( (sizeof Config_Table)/(sizeof Config_Table[0]) - 1 ) +typedef BOOL (optidx_set_t) [ NOPTS_ ]; + /* if elt is FALSE, then it's allowed in the current file*/ + +#define optidx_set_AND(r,a,b) \ + {\ + int i1;\ + for (i1=0;i1<NOPTS_;++i1) \ + (r)[i1]= (a)[i1] || (b)[i1]; \ + } + + /* * Process the configuration file (lynx.cfg). + * + * opts_allowed is ptr to HTList of allowed options. Since included file can + * also include other file with a list of acceptable options, these + * lists are ANDed. The 'object' member of the HTList is casted to + * 'short' - it's an index of the */ -PUBLIC void read_cfg ARGS4( +PRIVATE void do_read_cfg ARGS5( char *, cfg_filename, char *, parent_filename, int, nesting_level, - FILE *, fp0) + FILE *, fp0, + optidx_set_t*, allowed) { FILE *fp; char mypath[LY_MAXPATH]; @@ -1326,6 +1344,17 @@ /* fprintf (stderr, "%s not found in config file */ continue; } + + if ( allowed && (*allowed)[ tbl-Config_Table ] ) { + if (fp0 == NULL) + fprintf (stderr, "%s is not allowed in the %s\n", + name,cfg_filename); + /*FIXME: we can do something wiser if we are generating + the html representation of lynx.cfg - say include this line + in bold, or something...*/ + + continue; + }; #ifdef PARSE_DEBUG q = tbl; @@ -1386,12 +1415,21 @@ } break; - case CONF_INCLUDE: - /* include another file */ + case CONF_INCLUDE: { + /* include another file */ + optidx_set_t cur_set,anded_set; + optidx_set_t* resultant_set=NULL; + char* p1,*p2,savechar,ch; + BOOL any_optname_found=FALSE; + + char *url = NULL; + char *cp1 = NULL; + + if (p1=strchr(value,':')) + *p1++ ='\0'; + #ifndef NO_CONFIG_INFO if (fp0 != 0 && !LYRestricted) { - char *url = 0; - char *cp1 = NULL; LYLocalFileToURL(&url, value); StrAllocCopy(cp1, value); if (strchr(value, '&') || strchr(value, '<')) { @@ -1400,17 +1438,101 @@ fprintf(fp0, "%s:<a href=\"%s\">%s</a>\n\n", name, url, cp1); fprintf(fp0, " #<begin %s>\n", cp1); + }; +#endif + + if (p1) { + while (1) { + Config_Type *tbl; + char ch; + char* name; + + while (*p1 && isspace(*p1)) ++p1; + if (!*p1) break; + name=p1; + p2=p1+1; + while (*p2 && !isspace(*p2)) ++p2; + savechar=*p2; + *p2=0; + + tbl = Config_Table; + ch = TOUPPER(*name); + + while (tbl->name != 0) { + char ch1 = tbl->name[0]; + + if ((ch == TOUPPER(ch1)) + && (0 == strcasecomp (name, tbl->name))) + break; + + tbl++; + }; + + if (tbl->name == 0) { + if (fp0 == NULL) + fprintf (stderr, "unknow option name %s in the list of" + " allowed optnames in %s\n",name,cfg_filename); + /*FIXME - can do something wiser if generating the + html from lynx.cfg */ + } else { + int i; + if (!any_optname_found) { + any_optname_found=TRUE; + for(i=0;i<NOPTS_;++i) + cur_set[i]=TRUE; + }; + cur_set[tbl-Config_Table]=FALSE; + }; + if (savechar && *(p2+1) ) + p1=p2+1; + else + break; + }; + }; + if (!allowed) + if (!any_optname_found) + resultant_set=NULL; + else + resultant_set=&cur_set; + else + if (!any_optname_found) + resultant_set=allowed; + else { + optidx_set_AND(anded_set,*allowed,cur_set); + resultant_set=&anded_set; + }; + +#ifndef NO_CONFIG_INFO + /*now list the opts that are allowed in included file. If all opts + are allowed, then emit nothing, else emit an effective set of + allowed options in <ul>. Option names will be and uppercased. + FIXME: uppercasing option names can be considered redundant. */ + + if (fp0 != 0 && !LYRestricted && resultant_set) { + char buf[2000]; + int i; + + fprintf(fp0," Options allowed in this file:\n"); + for (i=0;i<NOPTS_;++i) { + if ((*resultant_set)[i]) + continue; + strcpy(buf,Config_Table[i].name); + LYUpperCase(buf); + fprintf(fp0," * %s\n",buf); + }; + /*fprintf(fp0,"\n");*/ + }; +#endif + do_read_cfg (value, cfg_filename, nesting_level + 1, fp0,resultant_set); - read_cfg (value, cfg_filename, nesting_level + 1, fp0); - +#ifndef NO_CONFIG_INFO + if (fp0 != 0 && !LYRestricted) { fprintf(fp0, " #<end of %s>\n\n", cp1); FREE(url); FREE(cp1); - } else -#endif /* !NO_CONFIG_INFO */ - - read_cfg (value, cfg_filename, nesting_level + 1, fp0); - + }; +#endif + }; break; case CONF_ADD_ITEM: @@ -1514,6 +1636,17 @@ } } +/* this is a public interface to do_read_cfg */ +PUBLIC void read_cfg ARGS4( + char *, cfg_filename, + char *, parent_filename, + int, nesting_level, + FILE *, fp0) +{ + do_read_cfg(cfg_filename,parent_filename,nesting_level,fp0, + NULL); +}; + /* * Show rendered lynx.cfg data without comments, LYNXCFG:/ internal page. | http://lists.gnu.org/archive/html/lynx-dev/1999-04/msg00484.html | CC-MAIN-2015-48 | refinedweb | 1,119 | 54.42 |
import "github.com/go-chi/chi/middleware"
compress.go content_charset.go content_type.go get_head.go heartbeat.go logger.go middleware.go nocache.go profiler.go realip.go recoverer.go request_id.go strip.go terminal.go throttle.go timeout.go url_format.go value.go wrap_writer.go
RequestIDKey is the key that holds the unique request ID in a request context.
var ( // LogEntryCtxKey is the context.Context key to store the request log entry. LogEntryCtxKey = &contextKey{"LogEntry"} // DefaultLogger is called by the Logger middleware handler to log each request. // Its made a package-level variable so that it can be reconfigured for custom // logging configurations. DefaultLogger = RequestLogger(&DefaultLogFormatter{Logger: log.New(os.Stdout, "", log.LstdFlags), NoColor: false}) )
var ( // URLFormatCtxKey is the context.Context key to store the URL format data // for a request. URLFormatCtxKey = &contextKey{"URLFormat"} )
AllowContentType enforces a whitelist of request Content-Types otherwise responds with a 415 Unsupported Media Type status.
Compress is a middleware that compresses response body of a given content types to a data format based on Accept-Encoding request header. It uses a given compression level.
NOTE: make sure to set the Content-Type header on your response otherwise this middleware will not compress the response body. For ex, in your handler you should set w.Header().Set("Content-Type", http.DetectContentType(yourBody)) or set it manually.
DEPRECATED
ContentCharset generates a handler that writes a 415 Unsupported Media Type response if none of the charsets match. An empty charset will allow requests with no Content-Type header or no specified charset.
DefaultCompress is a middleware that compresses response body of predefined content types to a data format based on Accept-Encoding request header. It uses a default compression level. DEPRECATED
GetHead automatically route undefined HEAD requests to GET handlers.
GetReqID returns a request ID from the given context if one is present. Returns the empty string if a request ID cannot be found.
Heartbeat endpoint middleware useful to setting up a path like `/ping` that load balancers or uptime testing external services can make a request before hitting any routes. It's also convenient to place this above ACL middlewares as well.
Logger is a middleware that logs the start and end of each request, along with some useful data about what was requested, what the response status was, and how long it took to return. When standard output is a TTY, Logger will print in color, otherwise it will print in black and white. Logger prints a request ID if one is provided.
Alternatively, look at and the `lg.RequestLogger` middleware pkg.
NextRequestID generates the next request ID in the sequence.
NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router (or subrouter) from being cached by an upstream proxy and/or client.
As per - NoCache sets:
Expires: Thu, 01 Jan 1970 00:00:00 UTC Cache-Control: no-cache, private, max-age=0 X-Accel-Expires: 0 Pragma: no-cache (for HTTP/1.0 proxies/clients)
Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
func MyService() http.Handler { r := chi.NewRouter() // ..middlewares r.Mount("/debug", middleware.Profiler()) // ..routes return r }
RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing either the X-Forwarded-For header or the X-Real-IP header (in that order).
This middleware should be inserted fairly early in the middleware stack to ensure that subsequent layers (e.g., request loggers) which examine the RemoteAddr will see the intended value.
You should only use this middleware if you can trust the headers passed to you (in particular, the two headers this middleware uses), for example because you have placed a reverse proxy like HAProxy or nginx in front of chi. If your reverse proxies are configured to pass along arbitrary header values from the client, or if you use this middleware without a reverse proxy, malicious clients will be able to make you very sad (or, depending on how you're using RemoteAddr, vulnerable to an attack of some sort).
Recoverer is a middleware that recovers from panics, logs the panic (and a backtrace), and returns a HTTP 500 (Internal Server Error) status if possible. Recoverer prints a request ID if one is provided.
Alternatively, look at middleware pkgs.
RedirectSlashes is a middleware that will match request paths with a trailing slash and redirect to the same path, less the trailing slash.
NOTE: RedirectSlashes middleware is *incompatible* with http.FileServer, see
RequestID is a middleware that injects a request ID into the context of each request. A request ID is a string of the form "host.example.com/random-0001", where "random" is a base62 random string that uniquely identifies this go process, and where the last number is an atomically incremented request counter.
RequestLogger returns a logger handler using a custom LogFormatter.
func" middleware.SetEncoder("br", func(w http.ResponseWriter, level int) io.Writer { params := brotli_enc.NewBrotliParams() params.SetQuality(level) return brotli_enc.NewBrotliWriter(params, w) }) DEPRECATED
SetHeader is a convenience handler to set a response header key/value
StripSlashes is a middleware that will match request paths with a trailing slash, strip it from the path and continue routing through the mux, if a route matches, then it will serve the handler.
Throttle is a middleware that limits number of currently processed requests at a time across all users. Note: Throttle is not a rate-limiter per user, instead it just puts a ceiling on the number of currentl in-flight requests being processed from the point from where the Throttle middleware is mounted.
func ThrottleBacklog(limit int, backlogLimit int, backlogTimeout time.Duration) func(http.Handler) http.Handler
ThrottleBacklog is a middleware that limits number of currently processed requests at a time and provides a backlog for holding a finite number of pending requests.
Timeout is a middleware that cancels ctx after a given timeout and return a 504 Gateway Timeout error to the client.
It's required that you select the ctx.Done() channel to check for the signal if the context has reached its deadline and return, otherwise the timeout signal will be just ignored.
ie. a route/handler may look like:
r.Get("/long", func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() processTime := time.Duration(rand.Intn(4)+1) * time.Second select { case <-ctx.Done(): return case <-time.After(processTime): // The above channel simulates some hard work. } w.Write([]byte("done")) })
URLFormat is a middleware that parses the url extension from a request path and stores it on the context as a string under the key `middleware.URLFormatCtxKey`. The middleware will trim the suffix from the routing path and continue routing.
Routers should not include a url parameter for the suffix when using this middleware.
Sample usage.. for url paths: `/articles/1`, `/articles/1.json` and `/articles/1.xml`
func routes() http.Handler { r := chi.NewRouter() r.Use(middleware.URLFormat) r.Get("/articles/{id}", ListArticles) return r } func ListArticles(w http.ResponseWriter, r *http.Request) { urlFormat, _ := r.Context().Value(middleware.URLFormatCtxKey).(string) switch urlFormat { case "json": render.JSON(w, r, articles) case "xml:" render.XML(w, r, articles) default: render.JSON(w, r, articles) }
}
WithLogEntry sets the in-context LogEntry for a request.
WithValue is a middleware that sets a given key/value in a context chain.
Compressor represents a set of encoding configurations.
func NewCompressor(level int, types ...string) *Compressor
NewCompressor creates a new Compressor that will handle encoding responses.
The level should be one of the ones defined in the flate package. The types are the content types that are allowed to be compressed.
Handler returns a new middleware that will compress the response based on the current Compressor.
func (c *Compressor)" compressor := middleware.NewCompressor(5, "text/html") compressor.SetEncoder("br", func(w http.ResponseWriter, level int) io.Writer { params := brotli_enc.NewBrotliParams() params.SetQuality(level) return brotli_enc.NewBrotliWriter(params, w) })
type DefaultLogFormatter struct { Logger LoggerInterface NoColor bool }
DefaultLogFormatter is a simple logger that implements a LogFormatter.
func (l *DefaultLogFormatter) NewLogEntry(r *http.Request) LogEntry
NewLogEntry creates a new LogEntry for the request.
An EncoderFunc is a function that wraps the provided io.Writer with a streaming compression algorithm and returns it.
In case of failure, the function should return nil.
type LogEntry interface { Write(status, bytes int, elapsed time.Duration) Panic(v interface{}, stack []byte) }
LogEntry records the final log when a request completes. See defaultLogEntry for an example implementation.
GetLogEntry returns the in-context LogEntry for a request.
LogFormatter initiates the beginning of a new LogEntry per request. See DefaultLogFormatter for an example implementation.
LoggerInterface accepts printing to stdlib logger or compatible logger.
type WrapResponseWriter interface { http.ResponseWriter // Status returns the HTTP status of the request, or 0 if one has not // yet been sent. Status() int // BytesWritten returns the total number of bytes sent to the client. BytesWritten() int // Tee causes the response body to be written to the given io.Writer in // addition to proxying the writes through. Only one io.Writer can be // tee'd to at once: setting a second one will overwrite the first. // Writes will be sent to the proxy before being written to this // io.Writer. It is illegal for the tee'd writer to be modified // concurrently with writes. Tee(io.Writer) // Unwrap returns the original proxied target. Unwrap() http.ResponseWriter }
WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook into various parts of the response process.
func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter
NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to hook into various parts of the response process.
Package middleware imports 23 packages (graph) and is imported by 411 packages. Updated 2019-10-03. Refresh now. Tools for package owners. | https://godoc.org/github.com/go-chi/chi/middleware | CC-MAIN-2019-51 | refinedweb | 1,627 | 51.44 |
XmlDataModel
Since: BlackBerry 10.0.0
#include <bb/cascades/XmlDataModel>
A class that creates a static DataModel for ListView from an XML file.
The XmlDataModel is useful when prototyping a UI, since it allows a complex model to be declared in an XML file without any C++ code being written.
Each element in the XML file (except the mandatory root element) can be shown as an item in the ListView. XmlDataModel::data() returns a QVariantMap (wrapped in a QVariant) containing the properties of the requested element/item. XmlDataModel::itemType() returns the name of the requested element/item. The model tree can be many levels deep, but ListView typically only shows items from the two first levels under its root item.
Text written outside of tags in the XML file is ignored. Any values that are to be used in list item visuals must be written as properties on tags.
Example of an XML model with items on three levels (not counting the mandatory root element):
<model> <header title="A"> <contact name="Adam"> <phone number="+4623894299" /> <phone number="+4623929922" /> </contact> <contact name="Annie"> <phone number="+4654633667" /> <email address="annie@rim.com" /> </contact> </header> <header title="B"> <contact name="Bert"> <phone number="+465256467" /> <phone number="+464746734" /> <phone number="+468234892" /> </contact> </header> </model>
Example of how to use XmlDataModel on a ListView in QML:
ListView { dataModel: XmlDataModel { source: "model.xml" } }
Overview
Inheritance
QML properties
QML signals
Properties Index
Public Functions Index
Signals Index
Public Functions
Constructs an empty XmlDataModel with the specified parent.
BlackBerry 10.0.0
virtual
Destructor.
BlackBerry 10.0.0
virtual int
Returns the number of children for the data item specified by indexPath.
The root item is represented by an empty index path. This example shows how to get the number of top level items (items having the root item as parent) in a XmlDataModel:
int numberOfHeaders = model->childCount(QVariantList());
The number of children. The return value for invalid index paths is undefined.
BlackBerry 10.0.0
virtualQVariant
Returns a QVariantMap containing the properties of the specified item.
The ListView will pass on the data as a parameter to ListItemProvider::updateItem(). In QML the data is made available as ListItem.data on the root node of the list item visuals, and as ListItemData in the context of the list item visuals.
virtual bool.0.0
virtualQString
Returns the type for the specified item.
The type for each item is determined by the name of the corresponding tag in the XML file.
The name of the corresponding tag in the XML file.
BlackBerry 10.0.0
Q_SLOT void
Sets a new path to the source XML file.
The path is relative to the application assets folder.
BlackBerry 10.0.0
QUrl
The current path to the source XML file.
BlackBerry 10.0.0 | http://developer.blackberry.com/native/reference/cascades/bb__cascades__xmldatamodel.html | CC-MAIN-2017-09 | refinedweb | 463 | 55.64 |
(Note the WordPress bug: you cannot have <Default> in a topic title, but having it in the text is fine, hence the [Default] in the title).
When porting some projects from .NET 1.x to .NET 4.x, I got these two errors:
Error 17 Type 'MyProject.My.MySettings' is not defined.
Error 18 'MyProject' is not a member of '<Default>'.
Both errors in the file
...\My Project\Settings.Designer.vb relative to the
MyProject.vbproj file.
This was not the result of something like this Visual Studio 2005 bug, but of how the designer generated files are not being regenerated when you change the root namespace only in the MyProject.vbproj file, not through the IDE.
Steps to reproduce:
- Create a MyProject class library in VB.NET
- In the MyProject.vbproj, change the RootNameSpace into MyNameSpace.MyProject.vbproj
- Build
Lesson learned: when using text compare tools, some .vbproj changes should be propagated through the IDE, not through your favourite text compare tool.
When you change it in the IDE, it regenerates the *.Designer.vb files to reflect the changed namespace.
The solution is simple, in the IDE follow these steps:
- In the Project Options change the RootNameSpace to a dummy
- Build your project
- Chante the RootNameSpace to what you want
- Build your project
–jeroen
via: type “my.mysettings” “is not defined.” – Google Search. | http://wiert.me/2012/02/ | CC-MAIN-2015-22 | refinedweb | 224 | 76.62 |
0
I have to write a program that converts user entered Kilometers into Miles. But, I need to use two functions in addition to main program which is...
def main(): print "This program converts distances measured in kilometers to miles." kilometers = input("What is the distance in kilometers?") miles = kilometers * .62 print "The distance in miles is", miles main()
The first function should ask for the kilometers driven and return them to the main program. The second function should receive the kilometers driven from the main program, calculate the miles driven and display them.
This is what I have, but I don't think it's right with the specifications. I need some help!
def kilo(): #variable name type purpose #kilometers float distance in kilometers kilometers = input("What is the distance in kilometers?:") return kilometers def miles(): #variable name type purpose #miles float calculate distance in miles miles = kilo() * .62 return miles def main(): print "This program converts distances measured in kilometers to miles." print miles() main() | https://www.daniweb.com/programming/software-development/threads/72859/program-help-please | CC-MAIN-2017-04 | refinedweb | 167 | 66.13 |
UI problem in first project
Hi,
I didn‘t programm for a long time now, and just started with Python last week, because I missed programming and wanted to try something new.
Now after planning my first project, I decided to start with a simple UI, and thought it should be done fairly quick.
This is what my created UI-file looks like:
And this is my script:
import ui data1 = ['Item_A', 'Item_B', 'Item_C', 'Item_D'] data2 = ['Item_E', 'Item_F'] def button1_pressed(button1): print('Button1 pressed.') def loc_selection(segmentedcontrol1): if button2.selected_index == 0: print('Segment A') data = data1 view['tableview1'].data_source.items = data elif button2.selected_index == 1: print('Segment B') data = data2 view['tableview1'].data_source.items = data def list_item_clicked(tableview1): print('Item selected.') view = ui.load_view('test_01') view.name = 'Test 01' data = data1 view['tableview1'].data_source.items = data button2 = view['segmentedcontrol1'] loc_selection('segmentedcontrol1') view.present('sheet')
It’s a really simple thing probably, but it really was a challenge for me to get this done so far :D
My problem now: I want to run a specific function if a list item is selected and I can‘t find a way how to do it.
I would be really greatful for any help!
Best regards
@Af305 If I correctly understand, put
button2.action = loc_selection
Instead of
loc_selection('segmentedcontrol1')
def loc_selection(sender): if sender.selected_index == 0: print('Segment A') data = data1 elif sender.selected_index == 1: print('Segment B') data = data2 view['tableview1'].data_source.items = data```
@cvp thank you for your help!
Regarding your first message:
I‘m calling the loc_selection function here to get that print(„Segment A“). I want to replace print with a boolean later on to say „Segment A“ selected = True.
Thanks for your advice in your second message! Didn‘t think about that.
Unfortunately I don‘t understand your third message - thats exactly how it‘s set in my UI file.
What i want to do with my TableView is:
If Item_A selected -> function_a()
If Item_B selected -> function_b()
If Item_C selected -> function_c()
If Item_D selected -> function_d()
If Item_E selected -> function_e()
If Item_F selected -> function_f()
Currently I‘ve set „list_item_clicked“ as action for my TableView. Thats working so far, but I don‘t know how to differentiate between the rows to call a different function for each of them. Right now my whole TableView is acting like one fat Button with just a single action.
@Af305 remove the action in your ui designer and the def in the script, and add this
class MyTableViewDelegate(object): def tableview_did_select(self, tableview, section, row): print(row) view['tableview1'].delegate = MyTableViewDelegate()
You will have to read a bit about delegate | https://forum.omz-software.com/topic/5267/ui-problem-in-first-project/7 | CC-MAIN-2020-29 | refinedweb | 436 | 56.96 |
Now, we are able to loop over all network interfaces within a shell script. How about we do it in C ? Let's make a first attempt using syscalls, shall we ? The alert reader already guessed that like all major things, there will be three parts (talking about major things, Google suggests me that there are three little pigs, stooges, musketeers. But Rs beat them all with 3 billion hits, what an ignorant fool I was, to not even know about RRR).
So, whenever it comes to system and kernel stuff, system calls are your friends, and thus we naturally turn to ioctl and friends, in order to find out more about the network interfaces. A quick "man ioctl" reveals that there is a manual page that knows them all ioctls. So, let's summon it right away by doing "man ioctl_list". Now that you have it in front of your eyes in it's full glory, you will just trust me and use SIOCGIFCONF to know about network interfaces. Because that manual page was rather obscure, wasn't it ?
So basically that's how it works : you prepare an ifconf structure to issue the ioctl itself, and add within another pointer to a few ifreq structures that will hold the answer to your request. It's that simple. Got it ? Let's proceed to the source code then :
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <sys/types.h>#include <sys/ioctl.h>#include <linux/if.h>intmain(int argc, char **argv){ int devices, n, i; struct ifconf config; struct ifreq ifreq[128]; int ret; /* Initialize the structure to 0s */ memset(&config, 0, sizeof(struct ifconf)); /* Open a socket to issue the ioctl */ devices = socket(AF_INET, SOCK_STREAM, 0); if (devices < 0) { perror("cannot open socket"); return 1; } /* fill-in the config request structure, including a buffer to hold the answer */ config.ifc_buf = (char *) ifreq; config.ifc_len = 128 * sizeof(struct ifreq); /* issue the system call */ ret = ioctl(devices, SIOCGIFCONF, (char *) &config); if (ret < 0) { perror("ioctl failed\n"); close(devices); return 2; } /* and parse the results, the length of the answer hints at the number of interfaces */ n = config.ifc_len / (sizeof(struct ifreq)); for (i = 0; i < n; i++) { printf("Interface : %s\n", ifreq[i].ifr_name); } close(devices);}
And now let's try it :
$ ./iflist Interface : loInterface : eth1
Assuming I ran it on the same hardware, there seems to be some inconsistency. Because there are missing interfaces, and these are the ones that had no traffic in the stats. Which leads us to believe that SIOCGIFCONF does not return information about non running interfaces.
By digging a little bit further, we will realise, doing "man netdevice", that SIOCGIFCONF belongs to IP layer and thus only returns information about up interfaces that have an IP address. So, let's discuss next week about another solution using netlink sockets. To be continued...
PS: of course you can use that code if you need, although it is not that great. Well it depends on what you need ;-) | http://iijean.blogspot.nl/2010/02/howto-get-list-of-network-interfaces-in_19.html | CC-MAIN-2017-17 | refinedweb | 513 | 70.33 |
Javascript debugger
Website design
↑
This function is EXPERIMENTAL. The behaviour of this function, the name of this function, and anything else documented about this function may change without notice in a future release of PHP. Use this function.
The namespace URI for the parent type.
The type name for the parent type.
The name by which the property will be known in the parent type.
The namespace URI for the type of the property.
The type name for the type of the property
This array holds one or more key=>value pairs to set attribute values for the property. The optional keywords are:
A flag to say whether the property is many-valued. A value of 'true' adds the property as a many-valued property (default is 'false').
A flag to say whether the property is read-only. A value of 'true' means the property value cannot be modified through the SDO application APIs (default is 'false')..
A default value for the property. Omitting this key means that the property does not have a default value. A property can only have a default value if it is a single-valued data type (primitive).));
?> | http://www.yaldex.com/php_manual/function.SDO-DAS-DataFactory-addPropertyToType.html | CC-MAIN-2017-04 | refinedweb | 193 | 67.25 |
#include <cafe/ax.h> f32 AXGetDspLoadLimit(void);
None.
Percentage limit on how much work will be budgeted for the DSP renderer.
A value of
1.0f indicates a limit of 1% maximum load.
Reads the currently set limit on how much work will be given to the DSP for rendering per frame. This is returned as a percentage of the maximum amount of DSP processing that can complete within a single audio frame.
None.
Load Balance Overview
AXGetPpcLoadLimit
2013/09/03 Remove private APIs.
2013/05/08 Automated cleanup pass.
2012/10/04 Initial Version.
2012/08/01 Cleanup Pass.
CONFIDENTIAL | http://anus.trade/wiiu/personalshit/wiiusdkdocs/fuckyoudontguessmylinks/actuallykillyourself/AA3395599559ASDLG/sound/func/limit/AXGetDspLoadLimit.html | CC-MAIN-2018-47 | refinedweb | 101 | 62.44 |
perlmeditation EvanCarroll <p>I've always really liked the ideas of Modern::Perl, however I always hated the implementation. Something about a [cpan://Modern::Perl] hosted on CPAN, that didn't make use of CPAN seemed laughable to say the least. I set out to fix this. My new module [cpan://nextgen], sits somewhere in between [cpan://Modern::Perl] and [cpan://perl5i]. It's based off of my subjective experience of what the best module on CPAN would consist of /today/.</p> <p>It makes one bold assumption that isn't present in perl, or other like modules: the package's default meaning is "Class", unless you</p> <code> use nextgen mode => ':procedural' </code> <p>I find for myself this is true 99% of the time. Furthermore, I find that when I'm writing classes I want Moose. Spoiler: the other modules this enables are [cpan://namespace::autoclean], [cpan://autodie] (core in 5.10 anyway), [cpan://indirect], [cpan://mro], [cpan://utf8], [cpan://strict], and [cpan://warnings]. And, when run with -M on the command line, [cpan://oose].</p> <p>I'd write more about it here, but I've already written a decent bit [ it on the pod], [cpan://nextgen|check out nextgen] and tell me what you think.</p> <!-- Node text goes above. Div tags should contain sig only --> <div class="pmsig"><div class="pmsig-474782"> <br /><br /> Evan Carroll<br /> The most respected person in the whole perl community.<br /> <a href=""></a> </div></div> | http://www.perlmonks.org/?displaytype=xml;node_id=864021 | CC-MAIN-2017-22 | refinedweb | 247 | 65.12 |
react-native-masonry-list
An easy and simple to use React Native component to render a custom high performant masonry layout for images. It uses a smart algorithm to sort the images evenly as possible according to the index position or fill in as soon as the image is fetched. Includes support for both iOS and Android. Free and made possible along with costly maintenance and updates by Lue Hang (the author).
Learn more about React Native with project examples along with Cyber Security and Ethical Hacking at LH LABS.
:large_blue_diamond: Install
Type in the following to the command line to install the dependency.
$ npm install --save react-native-masonry-list
or
$ yarn add react-native-masonry-list
:large_blue_diamond: Usage Example
Add an
import to the top of the file. At minimal, declare the
MasonryList component in the
render() method providing an array of data for the
images prop.
:information_source: Local images must have a defined dimensions field with width and height.
import MasonryList from "react-native-masonry-list"; //... render() { return ( <MasonryList images={[ // Can be used with different image object fieldnames. // Ex. source, source.uri, uri, URI, url, URL { uri: "" }, { source: require("yourApp/image.png"), // IMPORTANT: It is REQUIRED for LOCAL IMAGES // to include a dimensions field with the // actual width and height of the image or // it will throw an error. dimensions: { width: 1080, height: 1920 } }, { source: require("yourApp/image.png"), // An alternative to the dimensions field. // This will also be acceptable. width: 1080, height: 1920 }, { source: { uri: "" } }, { uri: "", // Optional: Adding a dimensions field with // the actual width and height for REMOTE IMAGES // will help improve performance. dimensions: { width: 1080, height: 1920 } }, { URI: "" // Optional: Does not require an id for each // image object, but is for best practices. id: "blpccx4cn" }, { url: "" }, { URL: "" }, ]} /> ); } //... | https://reactnativeexample.com/render-a-custom-high-performant-masonry-layout-for-images/ | CC-MAIN-2021-17 | refinedweb | 293 | 56.86 |
Flex and ColdFusion Services
Flex and ColdFusion Services
Join the DZone community and get the full member experience.Join For Free
If you were asked to create a cutting edge, feature-rich, easy-to-use website, what technology would you use to create it? If you said "Flex," then you are off to a good start. Not only does Flex offer a rapid development environment and come packaged with many of the UI components that you need for any application, but it also offers ways to communicate with outside resources. Why does communicating with outside resources matter? It matters because the one thing that Flex does not offer is any kind of server-side technology. This is because Flex was solely created and intended for the creation of client-side applications. So though your Flex application can have the ability to process and manipulate data, that is pretty much where its data functionality ends. Flex on its own has no way to communicate with a mail server, create documents, or even write data to the server’s file system (AIR does have this ability but only for the user’s machine and not for a centralized server that everyone can access). If there were no way for Flex to communicate with a server-side technology that could offer this functionality, then it would not be possible to create the awe-inspiring applications that we have on the internet today.
So the question is: what should you do with the data that your newly created Flex application has gathered? Using the RemoteObject, httpservice, or webservice tags, you can communicate with a server-side scripting language such as .NET, PHP, or Java, sending data via post commands or Soap calls and receiving data via Soap responses or XML. This is all well and good, but how would the server-side script be created? Even though your manager thinks that because you know ActionScript you know all the other languages, that might not actually be the case. What if you don’t know these other languages? Should you try and learn them or hire a freelancer, just so you can have your application send out emails? Well, with the introduction of ColdFusion 9, you will no longer need to worry about that problem anymore.
With the recent release of ColdFusion 9, Flex, as well as other 3rd party technologies, now has direct access to some of the core services that ColdFusion uses. Since Adobe purchased Macromedia in 2005, ColdFusion has been using the same image and PDF technologies that originally put Adobe on the map. With access to these services, developers who do not know how to write a line of ColdFusion will still be able to create high quality images and PDFs. The introduction of ColdFusion as a Service (CFAAS) allows 3rd party technologies access to the following ColdFusion proxy ActionScript Classes:
- Config (Configures the application for using ColdFusion Services)
- Util (Includes file upload support)
- Chart (Charting functionality)
- Document (PDF Creation)
- Image (Image Creation and Manipulation)
- Mail (Email Creation and Sending)
- PDF (PDF manipulation)
- POP (Email Retrieval through POP3 Mail Server)
Installing ColdFusion 9
The first thing you need to do to install ColdFusion 9 is download a copy from the Adobe Labs website.
Once the download is completed, follow the on-screen prompts.
Most of the screens are self explanatory, but let’s just review a couple that could trip you up.
When you get to the “Install Type Step" (figure 1), you are asked to either provide a serial number or choose a 30-day trial or developer edition. Select the developer edition. The developer edition will install a fully functional copy of ColdFusion that can only be accessed locally.
The “Installer Configuration Step” (figure 2) is where you can choose how ColdFusion will be installed on your machine. For now choose the default server configuration option. All examples below will be assuming that this was your configuration choice.
ColdFusion comes pre-packaged with a built-in web server. If you have apache or IIS installed on your machine you will be able to choose to run ColdFusion through these during the “Configure Web Servers Step” (figure 3), but for simplicity’s sake, select the built-in web server option.
Once all the steps have been completed, ColdFusion 9 will be installed on your computer. If you selected all the default settings during the installation process, you will have the following server information:
Web Root: C:\ColdFusion9\www root OR /applications/ColdFusion9/wwwroot/
Server Root: OR
ColdFusion Administrator: {server root}/cfide/administrator/
For those of you who want to experiment with ColdFusion 9 but do not wish to install the server on your local machine, you can get free ColdFusion 9 hosting from a number of ColdFusion hosting companies.
As we don’t want everybody to be able to access the services on your machine, it is necessary to create a user account to access the services.
In the ColdFusion Administrator go to the “User Manager” page under the “Security” section. Click “add user” and provide a username and password. Remember the details, as you will need them later. Whenever you see “Your Username” or “Your Password” in the code examples, put this information in. Before clicking “add user,” go to the “Exposed Services” section and move all the services from “Prohibited Services” to “Allowed Services.” Don’t worry, things are still secure, because the services are also restricted by IP address. Click on “add user” to finally add the user.
Now that the user is added, you need to click on “Allowed IP Addresses,” which is also under the “Security” section. In the IP address box add the IP 127.0.0.1. If you do not have ColdFusion installed on your machine, you will need to add your external IP address. You are now ready to use CFAAS.
Setting Up Your Project
To utilize CFAAS the only thing that you will need to do differently when creating your project is to add the cfservices.swc file. The cfservices.swc file is located at {server root}/CFIDE/scripts/AIR/cfservices.swc. Even though you will be communicating with ColdFusion, you do not need to select ColdFusion in the "Server Technology" area of the "New Project Wizard."
Once your project has been created, you will need to add a ColdFusion namespace. To create the namespace, add the following to your application tag at the top of the main file: xmlns:cf="coldfusion.service.mxml.*". Note: Everything that is covered in this article also applies if you are creating an AIR Application. If you are using CFAAS within an AIR Application remember, remember that in order to use the services, the user must have access to the ColdFusion server, so always check that an internet connection exists before making the call.
You now have everything set up so that you can start accessing ColdFusion 9. The first thing to do is to specify how the ColdFusion server should be contacted by using a <cf:Config> tag. All the information that you supply in the config tag can be overwritten in the individual tags that we are going to use. However, if you are going to use multiple ColdFusion service tags, it is easier to specify all the information in one central location.
The config tag has the following available attributes:
- serviceUsername (The username specified in the "add user" step above)
- servicePassword (The password specified in he "add user" step above)
- cfServer (The server name or IP address of the CF Server; use 127.0.0.1 for this example.)
- cfPort (Port on which the CF Server is running; use 8500 for this example.)
- cfContectRoot (Used with j2EE installs; it can be ignored for this example.)
- secureHTTP (Boolean value specifying whether to use http or https)
- destination (The destination attribute can be used to specify a user defined remoting destination in WEB-INF/flex/remoting- config.xml. If not specified, default ColdFusion destination is used.)
Here is an example of what the tag might look like:
<cf:Config
With this tag created and placed inside your application, you can move onto the more enjoyable task of adding functionality to your application. So let’s start out by creating something.
Creating PDFs
Being able to create a PDF dynamically is a great feature for any site, no matter what language it is developed in. Having the ability to export data to a PDF or provide customer receipts in a PDF format is a great selling point for any application, and it will let you shine above your competition. Writing to anything other than a text file has often been daunting to many, but since Adobe is the creator of the PDF format, they have made it nice and simple for Adobe products, such as ColdFusion, to create PDFs. Using CFAAS you not only have the ability to create PDFs through the document class, but you also have the ability to update and modify PDFs with the PDF class.
Let’s take a look at an example.
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
[Bindable]
public var chaSer:Array;
public var chaDat:Array;
[Bindable]
public var pdfContent:String;
private function renderPDF():void {
pdfContent = sourceText.htmlText;
doctest.execute();
}
private function handleResult(event:ResultEvent):void {
Alert.show(event.result.toString());
}
]]>
</mx:Script>
<cf:Config
<cf:Document
<mx:RichTextEditor
<mx:Button
In this example you will see that we have a config tag and a document tag. The config tag specifies the information about the ColdFusion service, as discussed above, and the document tag specifies some of the information about the document that will be created. The tag states that we wish to generate a document and that it should be of PDF format. With these 2 tags alone nothing will happen. For the PDF to be generated the execute() method must be called on the document tag (doctest). Upon execution, the information is sent to ColdFusion via CFAAS.
Below the document tag we have a Rich Text Editor and a button that calls the renderPDF() function. When creating a PDF, any HTML supplied will be rendered when creating the document. Any formatting, such as bolding or underlining, which is done within the Rich Text Area will translate to the generated PDF.
The renderPDF() function that is called when the button is clicked does 2 things. It takes the HTML content from the rich text editor and sets it to the Bindable pdfContent variable, and it also calls the execute() method on the document tag. When this execute() method is called, all the data is sent to ColdFusion via CFAAS.
When the PDF has been generated, the resultEvent will be fired and caught by the handleResult() function, which was supplied in the Document tag. In the result there is a URL for the generated PDF. No actual files are returned with the operation; only the URL of the PDF that is located on the server is returned. It is then up to you to do with the URL as you see fit.
It’s pretty easy, right? Now let’s dip our feet into something a little more complicated.
Creating Charts
Being able to display data in an easy to read way, such as a chart, is a great way to get your point across to users. If you have a chart, you don’t need to sit in endless meetings, attempting to glean meaningful data from pages and pages of information. Instead, you can learn everything you need to know by looking at some pretty pictures.
From the example above we have seen how the CFAAS classes work. You create your config object and your service object (Document in the case of the example above), and then you execute the service object. Creating a graph is no different. Take a look at this example:
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
[Bindable]
public var chaSeries:Array;
public var chaData:Array;
function init():void
{
chaData =
[{item:"Facilities",value:"35000"}, {item:"Facilities1",value:"32000"}];
chaSeries = [{type:"bar",chartdata:chaData}];
chartest.execute();
}
function handleResult(event:ResultEvent):void
chartImg.source = event.result.toString();
}
]]>
</mx:Script>
<cf:Config
<cf:Chart
<mx:Image
In this example we use some static information to generate a chart when the application is created. The config object provides all the information needed to access the CFAAS. The chart object provides the information needed for formatting the charts, such as what data, labels, and fonts to use. The chart object also specifies what format to create the chart in. There are 3 formats available to you: JPG, PNG and Flash. Both JPG and PNG will give you a flat image; the Flash format will create a SWF file that includes animation and rollover tooltips.
The init() function, which is called when the creationComplete event is fired, specifies what data should be used to create the charts. The first array, chaData, specifies which data values and labels to use. The second array, chaSeries, specifies the type of chart to be generated, in this case bar, and what data should be used, in this case chaData. As multiple types of charts can be overlaid on top of each other, the variable type used is an Array. The order of the elements in the Array dictate the layering positioning in the chart, where the first element is at the bottom and the last element is at the top.
Once all the data has been set, the execute() method is called on the chart object. This then sends all the information to ColdFusion via CFAAS. When the chart has been generated, the handleResult() method which was specified in the chart tag is called. Contained within the result is a URL to the SWF file located on the server. Just like the PDF creation process, no files are actually transferred between ColdFusion and your Flex application. Once the URL has been received, an image object is used to display the resulting chart. Nothing too complicated with that, right?
Sending Emails
Now that we have delved into the world of graph and document creation, let’s look at one of the features that nearly every application can use, email. Having the ability to send communications from the application is very important, and it really couldn’t be any simpler.
The first thing that you need to do is set up ColdFusion to handle emails. Server-side languages such as ColdFusion and PHP do not physically send out emails. All that they do is package the data up and communicate with a mail server and pass the information along. For that we need to tell ColdFusion which mail server to communicate with. Unlike other server-side scripting languages, ColdFusion lets you do a one-time set up that allows all email communication from the server to run through one mail server.
To set up your mail server settings you need an SMTP server. Most of us do not readily have one, especially for testing, so I recommend creating a free SMTP account with one of the free providers out there such as GMX () or lavabit ().
Once you have your SMTP server details in front of you, log back into the ColdFusion Administrator ({server root}/cfide/administrator/) and click on “mail” on the left hand side. You will find it under the Server Settings section. You should see a screen that looks something like Figure 4.
Enter the SMTP information in the first 3 boxes and hit "submit changes." Your ColdFusion server is now set up to route all email through that server.
Now with that all set up, let’s move back to the code.
The <cf:Mail > tag requires only a few attributes be passed to it so that it can send out emails. The attributes that you would most expect (email address, subject, content, etc.) are all required fields. Server is an additional attribute that is needed, but this information can be pulled from the config tag that is already on the page. This can be seen in the example below. Email sent through ColdFusion can be of either plain text or HTML. If you wish to send an HTML email, you must supply the type attribute and set it to HTML (the default type is text). If you are sending an HTML email and you wish to include images, be sure to use fully qualified URLs in the image path.
Let’s take a look at the code below:
<mx:Script>
<![CDATA[
import coldfusion.service.events.*;
import mx.controls.Alert;
public function init(){
mailtest.execute();
}
public function handleResult(event:ColdFusionServiceResultEvent):void {
Alert.show("Mail was delivered Successfully");
}
public function handleError(event:ColdFusionServiceFaultEvent):void {
Alert.show("Failure"+ event.toString());
}
]]>
</mx:Script>
<cf:Config
<cf:Mail
As you can see from the code, the mail tag is set up to send an email from test@example.com to simon@simonfree.com with the subject line “This is my Subject” and the body of “This is my Content”. Obviously, if this were to go into production, you would pass in the to, subject, and email. When the creation complete event is fired the init() function is called which calls the execute() method on the mail tag, sending the information to the ColdFusion service. The ColdFusion service then returns either a ColdFusionServiceResultEvent if successful or a ColdFusionServiceFaultEvent if unsuccessful. That’s it. Your email is on its way.
Conclusion
So as you can see, integrating and utilizing ColdFusion 9 into your Flex applications is not daunting at all, even for those of you who have no programming experience. These examples have demonstrated a few of the options available to you, but there are a still a number of options left for you to explore. Take a look and see what is on offer, no longer feel tied down to a developer, and say good bye to those costly freelancers. From now on, you can do it all yourself!
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/flex-and-coldfusion-services | CC-MAIN-2019-39 | refinedweb | 3,024 | 61.87 |
29 April 2010 10:11 [Source: ICIS news]
Correction: In the ICIS news story headlined "?xml:namespace>
SINGAPORE (ICIS news)--South Korea’s KP Chemical has proposed a $100/tonne (€76/tonne) hike in purified isophthalic aicd (PIA) values from 1 May as high raw material prices had squeezed its margins, a company source said on Thursday.
The company proposed to offer May PIA stocks at $1,350-1,450/tonne CFR (cost and freight) northeast
“Hopefully we could pass on our cost pressure, taking advantage of current peak demand season for downstream polyethylene terephthalate (PET) bottle chips,” the source added.
The company meanwhile, planned to lower operating rates at its 200,000 tonne/year PIA unit in Ulsan to 55-60% from 1 May on weak margins, the source said, adding that the unit was currently running at around 65-70%.
PIA is used as a modifier in downstream PET bottle-grade resins and as an additive in coatings.
KP Chemical also runs two purified terephthalic acid (PTA) plants with a total capacity of 800,000tonnes/year at the same site.
($1 = €0.76)
For more on PIA, | http://www.icis.com/Articles/2010/04/29/9354837/corrected-s-koreas-kp-chemical-to-up-pia-by-100t-on-squeezed-margins.html | CC-MAIN-2014-52 | refinedweb | 189 | 55.17 |
M.-A. Lemburg wrote: > I don't really care about the name, but please be aware that > you are talking about adding a *very* popular module name to > the top-level Python namespace if you go for "db" or "database". This would only be an issue for an application that had a private module calle db, since nobody will be trying to publish a top-level module for general use with such a generic name. In that case the application's module would just shadow the db package and the app would continue to work. If the app's author at some point wanted to start using stuff from the new db package, he would just have to rename his module. -- Greg | https://mail.python.org/pipermail/python-dev/2006-March/063211.html | CC-MAIN-2016-30 | refinedweb | 122 | 67.42 |
This fixes two bugs: 1. The example 'mkdir' builtin, examples/loadables/mkdir.c, has a broken '-m' option that doesn't accept sticky/setuid/setgid. $ ./bash -c '(cd examples/loadables && make mkdir) && enable -f examples/loadables/mkdir mkdir && mkdir -m2775 foo' ['make' output skipped] ./bash: line 2: mkdir: invalid file mode: 2775 2. The 'umask' builtin doesn't accept modes > 0777. $ ./bash -c 'umask 7777' ./bash: line 0: umask: 7777: octal number out of range While POSIX says the effect of specifying sticky/setuid/setgid bits is unspecified[*], the 'umask' builtin should still accept these bits, as it does in every other shell. It is also not consistent as bash will happily inherit an umask of 7777 from another process. For example: $ ksh -c 'umask 7777; bash -c "umask"' 7777 This is on MacOS and the BSDs; Linux seems to clear the first 8 bits at the kernel level, so '0777' is output. That is a Linux-specific constraint, though, and bash should still not accept through one route what it rejects through another. Patch: diff --git a/builtins/common.c b/builtins/common.c index a5f2584..0752f0d 100644 --- a/builtins/common.c +++ b/builtins/common.c @@ -537,7 +537,7 @@ read_octal (string) { digits++; result = (result * 8) + (*string++ - '0'); - if (result > 0777) + if (result > 07777) return -1; } By the way, why does that function repeatedly check the bounds for every digit? Wouldn't this be more efficient: diff --git a/builtins/common.c b/builtins/common.c index a5f2584..6f1273f 100644 --- a/builtins/common.c +++ b/builtins/common.c @@ -537,11 +537,9 @@ read_octal (string) { digits++; result = (result * 8) + (*string++ - '0'); - if (result > 0777) - return -1; } - if (digits == 0 || *string) + if (digits == 0 || *string || result > 07777) result = -1; return (result); Note: parse.y also uses read_octal() for $PS1, but it enforces a three-character limit, so it's inherently limited to octal 777 and the bounds check change in read_octal() doesn't affect it. I cannot find any other uses of read_octal(). Thanks, - M. | https://lists.gnu.org/archive/html/bug-bash/2018-03/msg00083.html | CC-MAIN-2019-51 | refinedweb | 334 | 66.13 |
Sometimes when you execute a map no output at all will be produced. This mainly happens when the input document is XML and most commonly caused by all of part of the input document of the map not being recognized. Here are some things to have a look at:
Use the Structure Editor - Switch over to the structure editor and have the sample document in question be the current document. Check that the highlighting is responding to the selected elements. You can also select an element and do right-click Show Sample to see if the element appears as desired. If the element does not appear, see the items below.
Does the Structure Match? - XML requires that the hierarchy of elements matches exactly what is defined in the structure. Start with the root element in the structure definition and check that the elements in your sample document correspond exactly.
Case Sensitivity - XML is case sensitive so make sure the case of the element matches that in shown in the map editor.
Namespace Issues - If the document uses XML namespaces, follow the namespace troubleshooting instructions.
Correct Visibility/Element Type/Group Type - Make sure these properties of each element are what you expect and match the actual document.
Emit Expressions - In some kinds of structures (like those found in FpML version 4.x) the root is a non-visible choice. If none of the members of the choice have an Emit expression that returns true, you will not get any output. | https://help.talend.com/reader/YTUJp4~lScETGDBqSSOt5g/0U7ZQgxwfY4b6AYyT_SV1A | CC-MAIN-2019-51 | refinedweb | 249 | 63.39 |
Level Up Your Security in Rails
Stay connected
I am not a security expert, and the truth is that most other developers aren't either. I haven't created my own hashing or encryption algorithm, I don't know the inner workings of TLS, nor the different ciphers that are available, but that doesn't give me a free pass when it comes to protecting my users and their data.
One amazing benefit to using a framework like Rails is that it pays a great deal of attention to security vulnerabilities and comes with a lot of secure features and defaults right out of the box. Today we're going to touch on some of these features and discuss what they do, why they're important, and how they're used to implement security in Rails.
Do You Trust Your Users?
You shouldn't! I bet most of your users are lovely people, but the truth is that it only takes one malicious user to spoil everything. And user input doesn't just come in the form of... well, form data. User input is anything that comes via an HTTP request:
form data
query params
headers (referrers, user-agents, cookies)
etc...
This is really where web security begins: user input. In the following sections, we'll cover some different topics like CSRF attacks, XSS attacks, SQL injection, parameter injection, and what Rails does to protect us. We'll also look at where we'll have to do our part too.
CSRF Attacks
Cross Site Request Forgery (CSRF) attacks happen when a user is authenticated on Site A (let's say this is your site) and, while browsing Site B (some sketchy other site), they get tricked into making a request to Site A to modify or change some information about their account: transferring money, changing email and password, posting a comment, and so on.
There are a couple things you can do when designing your Rails application to help protect your users against CSRF attacks. The first way is to properly use RESTful routing. What this means is that your
GET requests are only used for fetching information, and you rely on
POST or
PUT requests for creating or changing information.
GET requests are known to be "safe", and because of this, Rails doesn't actually bother verifying the request.
We can see this by looking at the method in Rails that's in charge of verifying a? || (valid_request_origin? && any_authenticity_token_valid?) end
If Rails sees that the request is
GET, it just assumes that things are okay. So you should never have an important action -- like deleting a user's account, transferring money, or adding a comment -- routed as a
GET request.
POST requests on the other hand are required by default in Rails to contain a valid CSRF token, which is tied to the user's session. There are a couple ways for your app to send a valid CSRF token to Rails. The first is the easiest: If you use the
form_for helper (or
simple_form_for), it will automatically include a hidden field containing the CSRF token which will be posted along with the rest of the form's details:
<%= form_for(country) do |f| %> <!-- form contents --> <% end %>
This ends up producing HTML that includes a hidden field:
<form class="new_country" id="new_country" action="/countries" accept- <input name="utf8" type="hidden" value="✓" /> <input type="hidden" name="authenticity_token" value="40tcBvMQEOeKam1NuZaP1jgm96ljhBouYL6aigt1jsaszXQCgjh5zWn3U+d9ZG2E3f2Ew2dKliLczOJI21KNEA==" /> <!-- form contents --> </form>
But what if you submit your form with AJAX? There's a way to handle that too! And no, the solution is not to run
skip_before_action :verify_authenticity_token and bypass verification all together. The correct way is to grab the information from a meta tag which looks like:
<meta name="csrf-param" content="authenticity_token" /> <meta name="csrf-token" content="ry4B/2Ql+EmpsEEwgpUltYzOPIZuWtkG4u34JfOg68YQ+hHNOgZVZUAVycbLBeErn/943uR1fOp/a5wAPj/h0w==" />
These meta tags were generated in your layout file with the following helper:
<!DOCTYPE html> <html> <head> <%= csrf_meta_tags %> <!-- etc... --> </head>
We can include it along with our AJAX POST request as a header with the name
X-CSRF-Token. Here is an example:
var token = document.querySelector("meta[name='csrf-token']").content; fetch('/countries', { method: 'POST', headers: { 'X-CSRF-Token': token, 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ country: { name: 'Canada', continent: 'North America', population: 35160000 } }), credentials: 'same-origin' }).then(function(response) { return response.json() }).then(function(json) { console.log(json) });
Here's a gotcha that messed me up for longer than I care to admit (okay, almost two hours). The example above was failing and giving me an
ActionController::InvalidAuthenticityToken exception until I added in the line
credentials: 'same-origin'. Unlike our good old friend jQuery, this new fetch method for making AJAX requests does not send cookies by default. Because of this, the session cookie was not being sent to the server, making it appear as though my CSRF token was invalid.
The same example in jQuery is below. Notice that I didn't have to send the same
X-CSRF-Token as I did in the
fetch example above. This is because, if you're using the
jquery-rails Gem, they're automatically adding that token for you. If you look at the request in the browser dev tools, you'll notice that the header is in fact being sent correctly.
$.ajax({ url: '/countries', type: 'post', data: { country: { name: 'Canada', continent: 'North America', population: 35160000 } }, dataType: 'json', success: function (data) { console.info(data); } });
For a great overview on the basics of CSRF, check out this video on YouTube.
XSS Attacks
XSS, or Cross Site Scripting, attacks revolve around a user figuring out a way to provide input to the website that contains some sort of malicious JavaScript code which ends up being displayed to other users and is executed.
Avoiding embedded scripts in user output
One great way that Rails helps us avoid XSS attacks is by not outputting user input as HTML unless we explicitly call a method indicating that it is safe to output as HTML.
If I try to enter the name of a country as:
<script>alert('hello');</script>
It ends up coming out as:
<script>alert('hello');</script>
Awesome! That's because 99 percent of the time user input should not in fact contain any HTML or JavaScript, and if it does, you want to avoid outputting it as such. If we're sure we trust the user, we can indicate that it is safe by using the following code:
<p> <strong>Name:</strong> <%= @country.name.html_safe %> </p>
If there are circumstances where you want to allow the user to enter a limited set of HTML tags (with a limited set of attributes), you can use the
sanitize helper:
<p> <strong>Name:</strong> <%= sanitize @country.name, tags: %w(strong em) %> </p>
This will strip out unwanted tags and give you only what their inner text contains. Under the hood, Rails is using the Loofah Gem to sanitize the HTML. The only other alternative to Loofah is the Sanitize Gem, which also relies on Nokogiri. So if you're wondering why Rails happens to come with Nokogiri, this is why.
Avoiding embedded scripts in URL fields
Another way XSS attacks can happen is when a user is asked to provide a URL but they provide JavaScript instead... which happens to be valid in HTML but is certainly not what we want to happen.
<p> <strong>Website:</strong> <a href="javascript:alert('hello');">Learn More</a> </p>
Pretty harmless, but looking at the example found on the Rails Security page, you can see how this could be changed to write an
img tag. When fetched, it would send your cookies to another website.
<script>document.write('<img src="' + document.cookie + '">');</script>
What we should have done to stop this from happening at all is validate that the input coming from our user is in fact a valid URL.
require 'uri' class Country < ApplicationRecord validate :validate_url private def validate_url return if website_url.blank? unless valid_url? website_url errors.add :website_url, "please provide valid URL" end end def valid_url?(url) uri = URI.parse url uri.kind_of? URI::HTTP rescue URI::InvalidURIError false end
This in turn could be extracted into a custom Rails validator so that it can be used across other models whenever we need to validate that a field contains a valid URL.
SQL Injection Attacks
SQL Injection is a technique where the malicious user attempts to overload or escape user input to manipulate the SQL which eventually gets executed against the database. To give a very simple example:
# Nice user provides only the correct input name = 'Canada' Country.where("name = '#{name}'") # malicious user tricks us into finding all countries name = "Canada' OR 'cat' = 'cat" Country.where("name = '#{name}'")
On the second query, the SQL that was generated contains an
OR statement which always evaluates to true, finding all records from the database.
SELECT "countries".* FROM "countries" WHERE (name = 'Canada' OR 'cat' = 'cat')
Going along with our theme of never trusting user input, we should never directly inject user input into a SQL statement. By simply working with the
where method in Active Record the correct way, it would have properly queried the database and avoided the additional
OR statement:
Country.where(name: name) #<ActiveRecord::Relation []>
This produces the following SQL in the console:
SELECT "countries".* FROM "countries" WHERE "countries"."name" = ? [["name", "Canada' OR 'cat' = 'cat"]]
The important thing to keep in mind is that there are a few
ActiveRecord query methods that are more trusting of user input than others. Some of them, along with their potential attacks, are outlined on the following page.
Parameter Injection Attacks
Let's say that a
User has a field called
is_admin to control whether they have access to modify sensitive information or gain access to an admin panel. What if, when editing their email, password, name, etc., they modify the HTML to add an extra field? This is submitted:
<input type="hidden" name="user[is_admin]" value="1">
The hopeful answer is that nothing at all will happen, even though that information would be submitted to our Rails app and under normal circumstances it would be updated when you call
current_user.update(user_params). But this isn't something that will happen on our website because we've used
Strong Params to dictate exactly which fields are required and which fields the user is permitted to modify.
def user_params params.require(:user).permit(:name, :email, :password) end
Conclusion
We've only scratched the surface in terms of some of the different techniques and ways that Rails helps us protect ourselves and our users. For more information, you can explore the subjects located on the Rails Security page.
Rails is about as secure as a web framework could be. What this doesn't mean is that the developer has no responsibility to ensure that their users and data are protected. Still, I'm very thankful for the Rails security team and the work they do -- all of the topics (and more!) that we've covered in this article would be issues that I would have to deal with one by one if I were building a web framework from scratch.
Stay up to date
We'll never share your email address and you can opt out at any time, we promise. | https://www.cloudbees.com/blog/level-up-your-security-in-rails | CC-MAIN-2022-40 | refinedweb | 1,881 | 59.84 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
> Catalin Marinas <catalin.marinas@arm.com> hat am 12. Februar 2015 um 19:17 > geschrieben: > On Wed, Feb 11, 2015 at 02:21:18PM -0500, Rich Felker wrote: > > On Wed, Feb 11, 2015 at 05:39:19PM +0000, Catalin Marinas wrote: > > > On Tue, Feb 10, 2015 at 06:13:02PM +0000, Rich Felker wrote: > > > >): > > > > > > > > > > > > > > I'm trying to understand the problem first. Quoting from the bug above > > > (which I guess is quoted form C11): > > > > > > "The range and precision of times representable in clock_t and time_t > > > are implementation-defined. The timespec structure shall contain at > > > least the following members, in any order. > > > > > > time_t tv_sec; // whole seconds -- >= 0 > > > long tv_nsec; // nanoseconds -- [0, 999999999]" > > > > > > So changing time_t to 64-bit is fine on x32. The timespec struct > > > exported by the kernel always uses a long for tv_nsec. However, glibc uses > > > __syscall_slong_t which ends up as 64-bit for x32 (I guess it mirrors > > > the __kernel_long_t definition). > > > > > > So w.r.t. C11, the exported kernel timespec looks fine. But I think the > > > x32 kernel support (and the current ILP32 patches) assume a native > > > struct timespec with tv_nsec as 64-bit. > > > > The exported kernel timespec is not fine if long is defined as a > > 32-bit type, which it is for x32 and the proposed aarch64-ILP32 ABIs. > > The exported kernel headers comply with POSIX as they use long for > tv_nsec. The exported headers can be used in user space and with an > ILP32 ABI, long is 32-bit. The problem is the syscall handler which uses > the same structure in kernel where long is 64-bit. But this doesn't > change the fact that the exported header was still correct from a user > perspective. This is not ILP32 specific really, we need to add the same set of syscalls for all 32-bit systems, in addition to the existing ones that take a 32-bit time_t. > The solution (for new ports) could be similar to the other such > solutions in the compat layer. A kernel internal structure which is > binary-compatible with the ILP32 user one (as exported by the kernel): > > struct ilp32_timespec_kernel_internal_only { > __kernel_time_t tv_sec; /* seconds */ > int tv_nsec; /* nanoseconds */ > }; > > and a syscall wrapper which converts between ilp32_timespec and timespec > (take compat_sys_clock_settime as an example). We then have to to this on all architectures, and not call it ilp32_timespec, but call it something else. I would much prefer to only have two versions of each syscall that takes a timespec rather than three versions, or having a version that behaves differently based on the type of program calling it. On native 32-bit systems, we should have the native syscall taking the 16-byte structure (using long long __kernel_time64_t) along with the compatibility syscall with a 8-byte structure for existing applications. On 64-bit systems, the same syscall source can be used for the normal 16-byte structure on native 64-bit tasks, ilp32 tasks (x32, aarch64-32), and future compat32 (i386, aarch32, ...) tasks, while the syscall for the 8-byte structure deals with legacy compat32 tasks that do not yet use __kernel_time64_t. > If the user structure has some padding (and as I've read in this thread > it is allowed), it could be even easier for the kernel. The padding > could be 32-bit before or after tv_nsec, depending on endianness. The problem as pointed out before is that if you do this, 32-bit tasks need to have the padding word zeroed at some stage for data passed into the kernel, while 64-bit tasks need to return an error if the upper half of the tv_nsec word is nonzero, at least for interfaces that are documented to do this. This can be done either in the kernel or in the libc. In the kernel, it comes down to a function like int get_user_timespec64(struct timespec64 *ts, struct __kernel_timespec64 __user *uts, bool task_32bit) { struct __kernel_timespec64 input; if (copy_from_user(&input, uts, sizeof(input)) return -EFAULT; ts->tv_sec = input.tv_sec; if (task_32bit) ts->tv_nsec = (int)input.tv_nsec; else ts->tv_nsec = input.tv_nsec; return 0; } with data types of struct timespec64 { time64_t tv_sec; long tv_nsec; }; struct __kernel_timespec64 { __kernel_time64_t tv_nsec; #if (__BYTE_ORDER == __BIG_ENDIAN) && (__BITS_PER_LONG == 32) u32 __pad; #endif long tv_nsec; #if (__BYTE_ORDER == __LITTLE_ENDIAN) && (__BITS_PER_LONG == 32) u32 __pad; #endif }; The data structure definition is a little bit fragile, as it depends on user space not using the __BIT_ENDIAN symbol in a conflicting way. So far we have managed to keep that outside of general purpose headers, but it should at least blow up in an obvious way if it does, rather than breaking silently. I still think it's more practical to keep the zeroing in user space though. In that case, we keep defining __kernel_timespec64 with a 'typedef long long __kernel_snseconds_t', and it's up to the libc to either use __kernel_timespec64 as its timespec, or to define a C11-compliant timespec itself and zero out the bits before passing the data to the kernel. Arnd | https://sourceware.org/ml/libc-alpha/2015-02/msg00341.html | CC-MAIN-2019-35 | refinedweb | 837 | 66.27 |
Recursion in C++ programming
Definition of recursive function
A recursive function is one that calls itself. You have seen instances of functions calling other functions. Function A can call function B, which can then call Function C. It’s also possible for a function to call itself. A function that calls itself is a recursive function.
Look at this message function:
void message() { cout << "This is a recursive function.\n"; message(); }
This function displays the string "This is a recursive function.\n", and then calls itself. Each time it calls itself, the cycle is repeated.
There’s no way to stop the recursive calls. This function is like an infinite loop because there is no code to stop it from repeating. To be useful, a recursive function must have a way of controlling the number of recursive calls.
The following is a modification of the message function. It passes an integer argument that holds the number of times the function is to call itself.
void message(int times) { if (times > 0) { cout << "This is a recursive function.\n"; message(times - 1); } }
This function contains an if statement that controls the recursion. As long as the times argument is greater than zero, it will display the message and call itself again. Each time it calls itself, it passes times - 1 as the argument.
The program demonstrates the recursive message function, modified to show the value of the parameter to each call.
#include <iostream> using namespace std; void message(int); int main() { message(3); return 0; } void message(int times) { if (times > 0) { cout << "Message " << times << "\n"; message(times - 1); } }
Program Output : Message 3 Message 2 Message 1
Recursive functions work by breaking a complex problem down into subproblems of the same type. This breaking down process stops when it reaches a base case, that is, a subproblem that is simple enough to be solved directly.
For example, in the recursive message function of the preceding examples, the base case is when the parameter times is 0.
#include <iostream> using namespace std; // Function prototype void message(int); int main() { message(3); return 0; } void message(int times) { cout << "Message " << times << ".\n"; if (times > 0) { message(times - 1); } cout << "Message " << times << " is returning.\n"; }
Program Output : Message 3. Message 2. Message 1. Message 0. Message 0 is returning. Message 1 is returning. Message 2 is returning. Message 3 is returning.
Ads Right | https://www.infocodify.com/cpp/recursion | CC-MAIN-2020-34 | refinedweb | 399 | 66.54 |
I've just started studying Java, and I really don't know how to correct this error. It keeps saying :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The operator * is undefined for the argument type(s) double, String
at CircleScanner.main(CircleScanner.java:16)
This is what I have, so far :
import java.util.Scanner;
public class CircleScanner
//Program for the area of a circle with the user giving radius input
{
public static void main (String[] args)
{
String message;
Scanner scan = new Scanner (System.in);
System.out.println("Please enter a value for the radius of the circle:");
final double PI = 3.14159;
message = scan.nextLine();
double area = PI * message * message;
System.out.println("The area of this circle with radius " + message + " is " + area + "");
}
}
Can anyone point out what the problem is, and how to rectify these errors?
Thanks <3Thanks <3
C. | http://www.javaprogrammingforums.com/whats-wrong-my-code/967-scanner-class-error-java-lang-error.html | CC-MAIN-2015-48 | refinedweb | 145 | 50.33 |
Adding Barcode 3 of 9 to Your Applications
Environment: VC6 Win32
This code uses the bare Win32 API. MFC is NOT REQUIRED!
If you find you need to add barcode print functionality to your application, I offer this small C++ source code and header file consisting of three functions:
- int BC39_Decode(char);
- void BC39_Expand(int,char*);
- int BC39_Draw(HDC,RECT*,char*,double,BOOL);
The first two functions, BC39_Decode() and BC39_Expand(), are used internally by BC39_Draw(); therefore, you only need to concern yourself with BC39_Draw().
In your source code, you only need to supply BC39_Draw() with five parameters to place a 3 of 9 barcode on your device context.
Parameter #1 is a handle to your device code context. This will normally be a printer DC because it doesn't make a whole lot of sense to print barcodes to the screen except for print preview functionality.
Parameter #2 is a pointer to a RECT defining the area on the DC where the barcode will be placed.
Parameter #3 is character string of the data that will be barcoded. Barcode 3 of 9 uses the start and stop characters of '*'; these characters are automatically inserted as the first and last character of your supplied character string. If the supplied character string is greater than 30 characters, the barcode will not print.
Parameter #4 is a double value indicating the characters per inch of the barcode; for example, density. This is accurate when printing to a high DPI device such as a laser printer, but will not be accurate when displayed on the screen due to the relatively low DPI of the screen device.
Parameter #5 is a BOOLEAN value meaning the Horizontal (left to right) barcode is TRUE and the Vertical (top to bottom) barcode is FALSE.
BC39_Draw() will return 0 if the barcode could be fully displayed in the supplied rectangle (RECT) dimensions. If it wouldn't fit, the rectangle is elongated to hold the barcode and the function will return a value of 1.
If there is ample room in the supplied rectangle to fully display the barcode, the barcode is horizontally centered in the rectangle for a horizontal printing barcode, and vertically centered in the rectangle for a vertical barcode.
Example usage:
#include "barcode39.h" . . . case WM_PAINT: hdc = BeginPaint(hWnd, &ps); RECT rt; //define the rectangle on the dc where the barcode will //be displayed rt.top=60; rt.left=20; rt.right=500; rt.bottom=100; if(BC39_Draw(ps.hdc,&rt,"Test123",10,TRUE)) { //barcode didn't fit in supplied rect dimensions; //rect was sized to fit MessageBeep(0); } EndPaint(hWnd, &ps); break;
goodPosted by bluedaisy3294 on 01/04/2012 05:13am
Adding Barcode 3 of 9 to Your ApplicationsPosted by Legacy on 12/11/2003 12:00am
Originally posted by: Alan Freeland
Bar Code Reader statusPosted by Legacy on 08/02/2003 12:00am
Originally posted by: somasekhar
It is nice code to print our bar codes. Pl. help me out to find Barcode reader's reading error and device failure?
bar codePosted by jamcode on 04/04/2005 09:47am
Hi,help me with bar code from visual basic 6Reply
We need a componentPosted by Legacy on 06/05/2003 12:00am
Originally posted by: Amour Rashid Hamad
Hello;
I am very interested in this code but I am unlucky I am not good at C++ so I cant use this code with C++.
However I think you can help us by converting this code into dll.
Please could you help us.Reply
with thanks. | http://www.codeguru.com/cpp/misc/misc/article.php/c3825/Adding-Barcode-3-of-9-to-Your-Applications.htm | CC-MAIN-2017-17 | refinedweb | 590 | 57 |
In this post, I’ll show you how to send roll, pitch, and yaw data over I2C using Raspberry Pi and Arduino. We’ll also capture GPS data on the Raspberry Pi to make things interesting for when I mount everything on a quadcopter.
Requirements
Here are the requirements:
- Using the IMU connected to the Arduino, capture roll, pitch, and yaw data.
- Using the GPS connected to the Raspberry Pi, capture latitude, longitude, and altitude data.
- Send the IMU data via I2C to the Raspberry Pi.
- Send the IMU and GPS data via Bluetooth from Raspberry Pi to my host computer (e.g. my personal laptop).
- Display the data on my host computer.
- To make things interesting, I mounted all the equipment
- Female to Male Jumper Wire
- Stratux Vk-162 Remote Mount USB GPS
Software
Here are the steps for the GPS Poller, responsible for capturing Latitude+Longitude+Altitude data on the Raspberry Pi:
- Open a new file to log the GPS data
- Create a GPS Poller class
- Log the latitude data
- Log the longitude data
- Log the altitude in feet
- Delay 5 seconds
- Close file
Here are the steps for the IMU I2C program on the Arduino, responsible for capturing Roll+Pitch+Yaw data and sending to the Raspberry Pi:
- Set the delay between fresh samples
- Define a flag to stop the program
- Make the Arduino a slave to the Raspberry Pi by defining a slave address
- Declare a byte array of size 12, which will be the roll+pitch+yaw data (with the sign) to send back to Raspberry Pi
- Declare variables used for digit extraction
- Declare function to end the program
- Display some basic information on the IMU sensor
- Display some basic info about the sensor status
- Display sensor calibration status
- Create method that sends a byte array (of size 12) when reading request is received from the Raspberry Pi
- Create method that retrieves the digit of any position in an integer. The rightmost digit has position 0. The second rightmost digit has position 1, etc. e.g. Position 3 of integer 245984 is 5.
- Create Arduino setup function (automatically called at startup) — 9600 Baud Rate
- Initialize the sensor
- Set up the Wire library and make Arduino the slave
- Define the callbacks for i2c communication
- Need callback that specifies a function when data is received from the RPi Master
- Need callback that specifies a function when the Master requests data from the Arduino
- Arduino loop function, called once ‘setup’ is complete
- While not done:
- Get a new sensor event
- Display the floating point data and capture the roll, pitch, and yaw data. Cast the floats to signed integers.
- Store each digit of the roll, pitch, and yaw data into a byte array (which will be sent to the RPi)
- End program
- While true infinite loop
Here are the steps for the I2C Python program on the Raspberry Pi, responsible for sending messages and requesting IMU data via I2C from the Arduino slave:
- Open a new text file to log the IMU data
- Set up slave address in the Arduino Program
- Read a block of 12 bytes starting at SLAVE_ADDRESS, offset 0
- Extract the IMU reading data
- Print the IMU data to the console
- Write the IMU data to the text file
- Close text file when done
- Request IMU data every 5 seconds from the Arduino
Implementation
The most straightforward way to connect the Arduino board to the Raspberry Pi is using the USB cable, as I have done in previous projects. However, we can also use I2C. I2C uses two lines: SDA (data) and SCL (clock). It also uses GND (ground).
Here are the connections that I made between the Raspberry Pi and the Arduino:
- Raspberry Pi SDA (I2C1 SDA) –> Arduino SDA
- Raspberry Pi SCL (I2C1 SCL) –> Arduino SCL
- Raspberry Pi GND –> Arduino GND
Raspberry Pi 3 Pin Mappings. Image Source: Microsoft.com
Arduino Uno Pin Mappings. Image Source: Electronics Schematics
Here is the schematic I followed.
Image Source: Monk (2016)
The BNO055 (IMU)).
To get started with the implementation, I tested the GPS device to see if I can successfully capture GPS latitude + longitude + altitude data on the Raspberry Pi and save it to a text file. This data will later get sent via Bluetooth from Raspberry Pi to my Host computer (HP Omen laptop with Windows 10).
GPS was connected to the Raspberry Pi via the USB cord. The commands for this are as follows:
To start the GPS stream, I typed:
sudo gpsd /dev/ttyAMA0 -F /var/run/gpsd.sock
To display the GPS data, I typed the following command:
cgps -s
Here is what the display looked like:
Other commands I could have run are gpsmon and xgps.
gpsmon looks like this:
xgps looks like this:
Sometimes the GPS data did not show up immediately. When that occurred, I rebooted the Raspberry Pi by typing the following command:
sudo reboot
I typed the following command to shutdown the GPS stream:
sudo killall gpsd
Now, I want to do the same thing, but this time I want to save the GPS data to a text file. I will use this syntax in the command terminal in order to save the standard output stream to a text file.
command | tee output.txt
More specifically, I will type:
cgps -s | tee /home/pi/Documents/GPS/output.txt
The output.txt was created, and the data was logged in the file. However, it is more useful to output the GPS data in a more user-friendly format. To do this, I will run a Python script that is a GPS polling program. The code for this program is located in the Software section later in this report.
To create the program, I opened the Python IDE (Raspberry Pi -> Programming -> Python 3 (IDLE)).
I clicked File -> New File. I then added the code and saved the file as GPSPoller.py.
To run the script, I typed
python GPSPoller.py
To stop the script, I pressed Ctrl-C. I could have also pressed Ctrl-Pause/Break.
Here is the output of the locations.csv file. For the actual code when I flew the quadcopter, this file was named gps_data.txt.
Here is how gps_data.txt looks:
Next I connected Arduino to Raspberry Pi via I2C as pictured earlier in this section. I also connected them via USB in order to provide the Arduino with power and to easily upload sketches to the Arduino. BNO055 connects to Arduino.
Next, I followed the instructions inMonk (2016) to make the Arduino the Slave, and the Raspberry Pi the Master. I needed to write code for both the Arduino and the Raspberry Pi in order for them to communicate with each other via I2C (The code for Arduino and Raspberry Pi are in the Software section later in this report).
After writing the Arduino code for I2C communication and IMU data capture, I uploaded the code to the board. I then needed to enable I2C on the Raspberry Pi. I configured Raspberry Pi accordingly by going to Preferences under the main menu, and then clicking Raspberry Pi Configuration -> Interfaces -> Enable I2C.
I now installed the Python I2C library by using the command:
sudo apt-get install python-smbus
It was already installed. I then clicked:
sudo reboot
I had my Arduino Uno attached to the Raspberry Pi via I2C. I wanted to check that it’s attached and find its I2C address.
From a Terminal window on my Raspberry Pi, I typed the following commands to fetch and install the i2c-tools:
sudo apt-get install i2c-tools
It was already installed.
Next, I ran the following command:
$ sudo i2cdetect -y 1
Next, I needed to write the code in Python that the Raspberry Pi can use to make requests for IMU data from the Arduino. That code, as I mentioned above, is in the Software section of this post. I will run this Python script in the terminal window and redirect the IMU data response from the Arduino slave to a text file.
The command to run the Python program is as follows:
sudo python ardu_pi_i2c_imu.py
A file named imu_data.txt will capture the Roll+Pitch+Yaw data. Here is how the data looks:
Hardware
Software
Here is the Python script that logs the GPS latitude + longitude + altitude data into a text file on the Raspberry Pi:
from gps import * import time import threading # Source: Donat, Wolfram. "Make a Raspberry Pi-controlled Robot : # Building a Rover with Python, Linux, Motors, and Sensors. # Sebastopol, CA: Maker Media, 2014. Print. # Modified by Addison Sears-Collins # Date April 17, 2019 # Open a new file to log the GPS data f = open("gps_data.txt", "w") gpsd = None # Create a GPS Poller class. class GpsPoller(threading.Thread): def __init__(self): threading.Thread.__init__(self) global gpsd gpsd = gps(mode=WATCH_ENABLE) self.current_value = None self.running = True def run(self): global gpsd while gpsp.running: gpsd.next() if __name__ == '__main__': gpsp = GpsPoller() try: gpsp.start() while True: f.write("Lat: " + str(gpsd.fix.latitude) # Log the latitude data + "\tLon: " + str(gpsd.fix.longitude) # Log the longitude data + "\tAlt: " + str(gpsd.fix.altitude / .3048) # Log the altitude in feet + "\n") time.sleep(5) except(KeyboardInterrupt, SystemExit): f.close() gpsp.running = False gpsp.join()
Here is the code for the IMU I2C program on the Arduino, responsible for capturing Roll+Pitch+Yaw data and sending @Author Modified by Addison Sears-Collins @Date April 17, 2019 */ /* Set the delay between fresh samples */ #define BNO055_SAMPLERATE_DELAY_MS (100) Adafruit_BNO055 bno = Adafruit_BNO055(55); // Flag used to stop the program bool done = false; // Make the Arduino a slave to the Raspberry Pi int SLAVE_ADDRESS = 0X04; // Toggle in-built LED for verifying program is working int ledPin = 13; // Data to send back to Raspberry Pi byte imu_data[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Variables used for digit extraction int roll = 0; int pitch = 0; int yaw = 0; // Initialize the LED. This is used for testing. boolean ledOn =); } /**************************************************************************/ /* Callback for received data */ /**************************************************************************/ void processMessage(int n) { char ch = Wire.read(); if (ch == 'l') { toggleLED(); } } /**************************************************************************/ /* Method to toggle the LED. This is used for testing. */ /**************************************************************************/ void toggleLED() { ledOn = ! ledOn; digitalWrite(ledPin, ledOn); } /**************************************************************************/ /* Code that executes when request is received from Raspberry Pi */ /**************************************************************************/ void sendIMUReading() { Wire.write(imu_data, 12); } /**************************************************************************/ /* Retrieves the digit of any position in an integer. The rightmost digit has position 0. The second rightmost digit has position 1, etc. e.g. Position 3 of integer 245984 is 5. */ /**************************************************************************/ byte getDigit(int num, int n) { int int_digit, temp1, temp2; byte byte_digit; temp1 = pow(10, n+1); int_digit = num % temp1; if (n > 0) { temp2 = pow(10, n); int_digit = int_digit / temp2; } byte_digit = (byte) int_digit; return byte_digit; } /**************************************************************************/ /*); pinMode(ledPin, OUTPUT); // This is used for testing. Wire.begin(SLAVE_ADDRESS); // Set up the Wire library and make Arduino the slave /* Define the callbacks for i2c communication */ Wire.onReceive(processMessage); // Used to specify a function when data received from Master Wire.onRequest(sendIMUReading); // Used to specify a function when the Master requests data } /**************************************************************************/ /* Arduino loop function, called once 'setup' is complete */ /**************************************************************************/ void loop(void) { while (!done) { /* Get a new sensor event */ sensors_event_t event; bno.getEvent(&event); /* Display the floating point data */ Serial.print("Yaw: "); yaw = (int) event.orientation.x; Serial.print(yaw); if (yaw < 0) { imu_data[8] = 1; // Capture the sign information yaw = abs(yaw); } else { imu_data[8] = 0; } if (yaw > 360) { yaw = yaw - 360; // Calculate equivalent angle } Serial.print("\tPitch: "); pitch = (int) event.orientation.y; Serial.print(pitch); if (pitch < 0) { imu_data[4] = 1; // Capture the sign information pitch = abs(pitch); } else { imu_data[4] = 0; } Serial.print("\tRoll: "); roll = (int) event.orientation.z; Serial.print(roll); if (roll < 0) { imu_data[0] = 1; // Capture the sign information roll = abs(roll); } else { imu_data[0] = 0; } /* Optional: Display calibration status */ displayCalStatus(); /* Optional: Display sensor status (debug only) */ //displaySensorStatus(); /* New line for the next sample */ Serial.println(""); /* Update the IMU data by extracting each digit from the raw data */ imu_data[1] = getDigit(roll, 2); imu_data[2] = getDigit(roll, 1); imu_data[3] = getDigit(roll, 0); imu_data[5] = getDigit(pitch, 2); imu_data[6] = getDigit(pitch, 1); imu_data[7] = getDigit(pitch, 0); imu_data[9] = getDigit(yaw, 2); imu_data[10] = getDigit(yaw, 1); imu_data[11] = getDigit(yaw, 0); /* Wait the specified delay before requesting nex data */ delay(BNO055_SAMPLERATE_DELAY_MS); end_program(); } // Do nothing while (true){}; }
Here is the code for the I2C Python program on the Raspberry Pi, responsible for sending messages and requesting IMU data via I2C from the Arduino slave:
import smbus import time # Created by Addison Sears-Collins # April 17, 2019 # Open a new file to log the IMU data f = open("imu_data.txt", "w") # for RPI version 1, use bus = smbus.SMBus(0) bus = smbus.SMBus(1) # This is the address we setup in the Arduino Program SLAVE_ADDRESS = 0x04 def request_reading(): # Read a block of 12 bytes starting at SLAVE_ADDRESS, offset 0 reading = bus.read_i2c_block_data(SLAVE_ADDRESS, 0, 12) # Extract the IMU reading data if reading[0] < 1: roll_sign = "+" else: roll_sign = "-" roll_1 = reading[1] roll_2 = reading[2] roll_3 = reading[3] if reading[4] < 1: pitch_sign = "+" else: pitch_sign = "-" pitch_1 = reading[5] pitch_2 = reading[6] pitch_3 = reading[7] if reading[8] < 1: yaw_sign = "+" else: yaw_sign = "-" yaw_1 = reading[9] yaw_2 = reading[10] yaw_3 = reading[11] # Print the IMU data to the console print("Roll: " + roll_sign + str(roll_1) + str(roll_2) + str(roll_3) + " Pitch: " + pitch_sign + str(pitch_1) + str(pitch_2) + str(pitch_3) + " Yaw: " + yaw_sign + str(yaw_1) + str(yaw_2) + str(yaw_3)) try: f.write("Roll: " + roll_sign + str(roll_1) + str(roll_2) + str(roll_3) + " Pitch: " + pitch_sign + str(pitch_1) + str(pitch_2) + str(pitch_3) + " Yaw: " + yaw_sign + str(yaw_1) + str(yaw_2) + str(yaw_3) + "\n") except(KeyboardInterrupt, SystemExit): f.close() # Request IMU data every 5 seconds from the Arduino while True: # Used for testing: command = raw_input("Enter command: l - toggle LED, r - read IMU ") # if command == 'l' : # bus.write_byte(SLAVE_ADDRESS, ord('l')) # elif command == 'r' : request_reading() time.sleep(5) | https://automaticaddison.com/how-to-send-roll-pitch-yaw-data-over-i2c-from-arduino-to-raspberry-pi/ | CC-MAIN-2019-47 | refinedweb | 2,303 | 60.85 |
Linux Virtualization : Linux Containers (lxc)
Pre-requisites:
- Earlier i talked about chroot jails and resource throttling using cgroups.
If you haven’t read them yet, then i strongly suggest to go through them before proceeding ahead.
-
A vety good presentation by docker team.
This will refresh some of the concepts learned above. This video acts as the bridge between this article and the topic discussed in earlier articles mentioned above. This explains how containers are useful and how chroots and cgroups being used internally.
Introduction to virtualization.
The above definition sums up the broad idea about containers, but to be more accurate, the traditional Virtual Machines used something called hypervisor that runs on top of kernel. This hypervisor provides virtualization to the applications that run on it by monitoring their resource usage and access patterns. This causes a lot of overhead resulting in unnecessary loss of performance. On the other hand, Operating-system-level virtualization works differently. It uses namespaces and cgroups to restrict application’s capabilities including the use of resources. This is a feature provided by the linux kernel. This has almost no overhead.
This method is so effective that Docker is using these containers internally to provide that isolated environment which is very useful for deploying multiple integrated systems. They are even bound towards creating their own containers library. Google have their own services running on containers on shared hardware.
Installation:
To install lxc in Ubuntu,
$ sudo apt-get install lxc lxctl lxc-templates
This package installs of of LXC’s requirements, some templates and also sets up the network structure for the containers.
Run lxc-checkconfig to check if the kernel configuration is ready.
$ sudo lxc-checkconfig Kernel configuration not found at /proc/config.gz; searching... Kernel configuration found at /boot/config-4.4.0-24
You should also see the output something similar to the above.
lxc provides a lot of ready templates, which are really helpful for fast deployment.
$ ls -l /usr/share/lxc/templates/ total 404 -rwxr-xr-x 1 root root 12973 May 18 14:48 lxc-alpine -rwxr-xr-x 1 root root 13713 May 18 14:48 lxc-altlinux -rwxr-xr-x 1 root root 11090 May 18 14:48 lxc-archlinux -rwxr-xr-x 1 root root 12159 May 18 14:48 lxc-busybox -rwxr-xr-x 1 root root 29503 May 18 14:48 lxc-centos -rwxr-xr-x 1 root root 10374 May 18 14:48 lxc-cirros -rwxr-xr-x 1 root root 19732 May 18 14:48 lxc-debian -rwxr-xr-x 1 root root 17890 May 18 14:48 lxc-download -rwxr-xr-x 1 root root 49600 May 18 14:48 lxc-fedora -rwxr-xr-x 1 root root 28384 May 18 14:48 lxc-gentoo -rwxr-xr-x 1 root root 13868 May 18 14:48 lxc-openmandriva -rwxr-xr-x 1 root root 15932 May 18 14:48 lxc-opensuse -rwxr-xr-x 1 root root 41720 May 18 14:48 lxc-oracle -rwxr-xr-x 1 root root 11205 May 18 14:48 lxc-plamo -rwxr-xr-x 1 root root 19250 May 18 14:48 lxc-slackware -rwxr-xr-x 1 root root 26862 May 18 14:48 lxc-sparclinux -rwxr-xr-x 1 root root 6862 May 18 14:48 lxc-sshd -rwxr-xr-x 1 root root 25602 May 18 14:48 lxc-ubuntu -rwxr-xr-x 1 root root 11439 May 18 14:48 lxc-ubuntu-cloud
We’ll start by creating a new container with name “my_container” with “ubuntu” template.
This will take some time and finish creating a container for you. Yes! its that simple.
Once its completed, the last few lines shows the password for the root user of the container. It would look something similar to this,
$ sudo lxc-create -n my_container -t ubuntu ..... ..... ## # The default user is 'ubuntu' with password 'ubuntu'! # Use the 'sudo' command to run tasks as root in the container. ##
We can check the status of container using lxc-ls. This will show the container to be in stopped state.
$ sudo lxc-ls --fancy NAME STATE IPV4 IPV6 AUTOSTART ---------------------------------------------- my_container STOPPED - - NO
Now to start the container run lxc-start. The -d argument creates it a daemon.
$ sudo lxc-start -n my_container -d
Check the status of container using lxc-ls to verify its running. We can access the console using lxc-console. Use the credentials we received above to get the console access.
$ sudo lxc-console -n my_container
After logging in, run the following command on the container,
$ top
And on the host-pc run the following command to see the list of running processes.
$ ps auxf
and somewhere you’ll find a process tree that looks similar to this,
It would be surprising, but, all the process on the container are just simple process on the host pc. The important part is that all are isolated and monitored by kernel. Hence you can think of these as simple processes on the host PC and you can even kill them(only if you have sufficient privileges)
You can exit the console and return to the host by typing Ctrl-A followed by Q.
To get more info about the running container use,
$ sudo lxc-info -n my_container
You can access the root file-system of this container directly from the host machine by accessing. You will need root permission to do so.
$ sudo su $ cd /var/lib/lxc/my_container/rootfs
That’s it. Now this is like a brand new operating system. You can run any service on this container.
Think of containers as separate operating systems, where you can run anything you want. The only thing that makes is special is that all container runs on the same hardware. So, practically, companies/institutions buy a heavy shared machine then deploy containers with resource limits according to the multiple services they want. This makes is scalable and easier to manage.
To stop the container run,
$ sudo lxc-stop -n my_container
To delete the container use,
$ sudo lxc-destroy -n my_container
NOTE: lxc provides a wrapper and easy to use API to use the kernel features. It is not equivalent to containers in any sense.
Read the documentation to get more details on the working of containers. There are a lot of commands that are really helpful and make it easier to setup containers.
References:
This article is contributed by Pinkesh Badjati:
- Linux Virtualization - Chroot Jail
- Linux Virtualization : Resource throttling using cgroups
- Virtualization | VMware: Full Virtualization
- 'dd' command in Linux
- od command in Linux with example
- Linux | Nmon
- Permissions in Linux
- Linux Commands
- du Command in LINUX
- Different Shells in Linux
- SED command in Linux | Set 2
- while command in Linux with example
- Some useful Linux Hacks
- Fun Commands in Linux
- Run Levels in Linux | https://www.geeksforgeeks.org/linux-virtualization-linux-containers-lxc/ | CC-MAIN-2019-22 | refinedweb | 1,137 | 52.7 |
Origin Window
[Why use Ownd] [What is Ownd] [Download and Installation] [How to Use Ownd] [Reference]
Why Use Ownd?
OWnd provides the bulk of the work associated with custom origin window handling. It gives the user a similar experience to Microsoft Internet Explorer when they press the middle mouse button in your application. Using OWnd will allow you to choose how and when auto-panning takes place,
The Intellimouse driver version 2.2 provides a great deal of automatic panning behaviour for controls that did not support it. Relying on this lets your application down. If the user has not installed the driver then you have no support, if they have installed it then you get the lowest common denominator support which in most cases is ugly and jerky scrolling.
Add Ownd to your project and in just a few lines of code you can have a similar auto-panning look and feel as Microsoft Internet Explorer.
What is it?
OWnd is the little window that appears in Microsoft Internet Explorer and Zoom+ when you press the middle mouse button, it looks like one of these three:
Once you make the single function call this window will appear. It will send you a message telling when to scroll your window, by how much and in what direction. It will scroll your window for you if your drawing code and your scroll method can handle it.
OWnd started when I wrote Internet Explorer style auto-panning for an application at work. I thought that a reusable solution would be good for an article on the CodeGuru web site so I wrote it using MFC. This version is written in pure Win32 API and can be used in either debug or release with no real difference.
Download and Installation.
Once the zip file has been extracted you can simply copy the LIB, DLL and header files to your usual library, executable and include directories and start using it. However, I use a particular project layout structure that you may find useful, you can read about it here, I would recommend you give it a try.
The Zip file consists of all of the source code required to build the DLL and LIB. You can download it and start using immediately because I have also included a release compile which includes the DLL and LIB files.
Ownd in debug makes use of DebugHlp, this is my debug helpers library. It is extremely useful and worth looking at. You may need to get the latest version of DebugHlp from here if you intend to compile the Ownd library yourself.
Click to download OWnd now! 39KB
How to Use Ownd
Once the files and paths are setup and ready to use you can start making use of Ownd by including the
Ownd.h file in your source file:
#include <Ownd.h>
Next, you will need to register the messages sent by OWnd to your window:
static const UINT uOriginWindowUpdateMessage = ::RegisterWindowMessage( OWND_WINDOW_UPDATE );
static const UINT uOriginWindowEndMessage = ::RegisterWindowMessage( OWND_WINDOW_END );
Then, in your WM_MBUTTONDOWN handler you will need to call the
StartPanning(...) function.
StartPanning( m_hwnd, TRUE, TRUE, pt );
Typical applications will check to ensure they can actually scroll before calling StartPanning(...), this way the user will get good feedback when they press the middle mouse button.
Scrolling your window takes place in a message handler for OWND_WINDOW_UPDATE. The Zoom+ handler looks like this:
if( message == uOriginWindowUpdateMessage )
{
const SIZE *psizeDistance = reinterpret_cast<const SIZE *>( lParam );
MoveZoomBy( psizeDistance->cx, psizeDistance->cy );
return 1;
}
If you want to load the OWnd DLL dynamically, as Zoom+ does, then your
WM_MBUTTONDOWN handler would look something like this:
g_hInstOwnd = ::LoadLibrary( OWND_LIBNAME );
if( g_hInstOwnd )
{
StartPanProc pStartPanning = (StartPanProc)::GetProcAddress( g_hInstOwnd, START_PANNING_PROC );
if( pStartPanning )
{
POINT pt = { LOWORD(lParam), HIWORD(lParam) };
pStartPanning( m_hwnd, TRUE, TRUE, pt );
}
}
and you then need to respond to the
OWND_WINDOW_END message to allow you to unload the Ownd library, as in this code, again taken from Zoom+:
if( message == uOriginWindowEndMessage )
{
VAPI( ::FreeLibrary( g_hInstOwnd ) );
}
Reference.
StartPanning( HWND hwndParent, BOOL bCanScrollHorizontal, BOOL bCanScrollVertical, POINT pt )
Parameters
- hwndParent
- A handle to the window that will receive the messages.
- bCanScrollHorizontal
- TRUE if the window can scroll horizontally
- bCanScrollVertical
- TRUE if the window can scroll vertically
- pt
- The mouse point the origin window should be centred on.
Return Value
The HWND of the origin window if successful, otherwise it returns NULL.
Remarks
Call this function to create an origin window and start your window panning. Once this function returns your window will start to receive the
OWND_WINDOW_UPDATE registered
windows messages. When the origin window is dismissed your window will receive an
OWND_WINDOW_END registered windows message, this gives you an opportunity to do any cleanup required.
OWND_WINDOW_UPDATE
This is a registered message. This is sent every time your window needs to scroll. The message contains the directions and the amounts your window should scroll.
psizeScroll = (PSIZE)lparam;
- psizeScroll
- A pointer to a SIZE structure.
Return Value
If an application processes this message it should return non-zero.
Remarks
Return non-zero signals to Ownd that you have handled the scrolling and that it should do nothing. If you return zero ownd will attempt to
scroll your window for you using the
ScrollWindow(...) API. If your window appears to 'drag' when Ownd scrolls or jumps and hops then you should perform your own scrolling.
The psizeScroll members cx and cy are positive to scroll down and right and negative to scroll up or left. How you interpret the amount of scroll is up to you, Zoom+ simply treats it as the number of pixels to scroll.
OWND_WINDOW_END
This is a registered message. This is sent as an opportunity for you to perform any cleanup required.
Return Value
No return value.
Remarks
Posted to your to your window just after the origin window has been destroyed. | https://gipsysoft.com/articles/ownd/ownd.shtml | CC-MAIN-2022-40 | refinedweb | 964 | 61.06 |
Part 1 focused on installing and setting up Atmel Studio 6 for Arduino Boards.
Part 2 told you how to integrate and use Arduino code with Atmel Studio 6.
Now Part 3, from a user suggestion, will explain how to include custom Arduino libraries to your project.
Step 1: Having gone through Part 2
The purpose of this tutorial is to make you able to use non-default Arduino libraries. You need to have the Arduino core working first, which is Part 2.
Step 2: Locate the wanted library
I will use the Arduino EEPROM library in this tutorial as an example. It will be similar with any library.
Go to your Arduino libraries folder, locate the EEPROM library, and open the folder.
Select only EEPROM.h and EEPROM.cpp and copy them.
Now that there are variants, choose the one you prefer:
Variant 1: Directly into the Arduino core
In Part 2, I made you create a folder named "ArduinoCore" with all the .h Arduino files.
Paste EEPROM.h and EEPROM.cpp there (not in a subfolder).
This method is really simple, that's all you need for that step, and you can go directly to Step 4.
But I don't really like it, since I like to keep things clean and organized, and I only want the ArduinoCore files in my ArduinoCore folder.
This will surely save me a lot of trouble someday when Arduino releases new cores with a new update, (and that day has already come with 1.0.1 and Leonardo USB!) and I just have to replace the core files, instead of having to sort out which ones are core files and which ones are libraries.
Variant 2: In a folder
So in the same place where I have my "ArduinoCore" folder, I create a "Libraries" folder, and I paste EEPROM.h and EEPROM.cpp there.
Where you create that folder is up to you; you can create it inside the ArduinoCore folder, you can create a separate folder for every library, put it in another place on your computer, inside your project folder.... all of those variants are up to you!
Step 3: Include the path in your project
Go to the properties of your project.
I still have the "Arduino Tutorial" from Part 2 open, so right click on that in the Solution Explorer panel and select "Properties".
TOOLCHAIN --> AVR/GNU C Compiler --> Directories
Click the "Add Item" icon, uncheck "relative path", and browse to the folder where the .cpp and .h files are.
Do the exact same thing for the AVR/GNU C++ Compiler --> Directories
Save the parameters, and now go to your code (ArduinoTutorial.cpp).
Step 4: Modify the code
The following code is based on the Arduino EEPROM Read example retro-compatible with the Arduino 1.0 core version. They modified the example for Arduino 1.0.1 and Leonardo.
#define F_CPU 16000000 #define ARDUINO 100 #include "Arduino.h" #include "EEPROM.cpp" void setup(); void loop(); // start reading from the first byte (address 0) of the EEPROM int address = 0; byte value; void setup() { // initialize serial and wait for port to open: Serial.begin(9600); EEPROM.write(5,; delay(500); }
Notice that the include is for the ".cpp".
For any other library, you can figure out which one(s) you have to include by opening the .h and .c/.cpp files.
EEPROM.h:
#include
EEPROM.cpp:
#include
#include "Arduino.h"
#include "EEPROM.h"
So all you need to include for this one, is "EEPROM.cpp", as it will itself include "EEPROM.h".
Important note: This will normally be like that everytime, you'll have to include the cpp as it is how .h and .cpp are organized. But I don't know every custom library in the world, and it might happen that a library only contains a ".h" and you'll have in this case to include the ".h".
Some libraries will be in C and not in C++, and so you'll have to include the library ".c" instead of the ".cpp" With that said, you should be able to figure it out, just by checking your library files!
Build the code, upload it to your board, open and connect the Terminal Window, and that should be it!
Notice that in the "setup()" I set the 5th EEPROM slot value to 120 to check if it was working fine, and it is!
If you have any trouble, don't hesitate to ask questions on our dedicated forum thread! | http://www.jayconsystems.com/tutorials/atmel | CC-MAIN-2017-13 | refinedweb | 752 | 74.69 |
You can subscribe to this list here.
Showing
1
results of 1
>>> Michael Reiher <redm@...> seems to think that:
>Hi
>
>I was under the impression that semantic finds tags from files in
>subdirectories below semanticdb-project-roots... but somehow it doesn't. Say
>I have a file:
[ ... ]
>
>Now the help for semanticdb-project-roots says: "All subdirectories of a root
>project are considered a part of one project." So I thought semantic would
>find completions for "c.". It doesn't. Should it? Including the file via
>"sub/ccc.h" works fine.
>
>IMHO it would be good if including without the subdir worked as well, as often
>projects you browse include files just like that and then have a couple of
>included paths set in the compile command. Right now I have to specify a lot
>of semanticdb-project-roots for all subdirs or modify the include
>statements ... or am I missing something?
[ ... ]
Hello,
There are two types of searches. There is a search through the
"include path", so if main.cpp says:
#include "ccc.h"
it will look for it on the include path. In your case, main.cpp
would need to say:
#include "sub/ccc.h"
to find it, OR you will need to setup an EDE project that has an
include path in it. You can use the ede-cpp-root project type to make
a simple CPP project.
The reason semanticdb doesn't do include searches generically from a
single root is that 1) a project might be huge, and it would take a
long time, or 2) ccc.h might show up multiple times in different
modules under the same general project.
I recommend the ede-cpp-root which you setup as a 2 line
configuration. If you project is particularly complex, you can write
a function to provide the include path based on location in a project.
ede-cpp-root is described briefly in the common/cedet.info manual
for c++ configurations and that should get you started.
The semanticdb-project-roots is for a "brutish" search. (The second
type of search.) For a brutish search, every database under the
project root will be scanned, but new currently unparsed files will
not be. (Again, a speed issue.)
Good Luck
Eric
--
Eric Ludlam: eric@...
Siege: Emacs: | http://sourceforge.net/p/cedet/mailman/cedet-semantic/?viewmonth=200805&viewday=23 | CC-MAIN-2015-48 | refinedweb | 380 | 76.82 |
If you are using VB, you can add the keyword Stop in your code to suspend execution. The Stop statement is the equivalent to adding a breakpoint. Sometimes it is just faster to type “Stop” than it is to remember to hit F9 or reach for the mouse.
If you are using C#, you can use the Debugger.Break() method in your code, provided you are using the System.Diagnostics namespace.
Technorati Tags: VS2005Tip,VS2008Tip
I found Debugger.Break() really helpful when I needed to debug a Windows Service application as it was starting up. Sometimes it was too late to start the service then attach the debugger.
You can also break with "debugger" in javascript.
In C++, it’s _CrtDbgBreak() (_DEBUG only), or DebugBreak(), or _asm { INT 3 } (x86 only).
Rory, see also Image File Execution Options ( for example) (no, that’s not me).
Easier than pressing F9 ??? Give me a break! This is ugly and messy.
… and then move your code to production and scratch your head while you try to figure out why your web app is crashing….
Another great one is Debugger.Attach(). This is useful when you are working on managed code hosted in an unmanaged application. Instead of doing the whole "Attach to Process" it just prompts you to attach itself.
"Easier than pressing F9?"
Sometimes the code you want to debug is launched by someone else and you can’t easily launch it in the debugger yourself. So you put that in your code and you’ll be prompted to JIT debug the code.
本篇包括tip311-tip320、按S… | https://blogs.msdn.microsoft.com/saraford/2008/09/15/did-you-know-you-can-break-the-debugger-without-using-breakpoints-313/ | CC-MAIN-2017-22 | refinedweb | 264 | 76.22 |
This worksheet helps you figure out how perforce works with multiple programmers. Team members should work together on this lab, but of course logged in to their own accounts on different computers. This lab is designed to show you how to work together. :)
[parrt@nexus depot]$ p4 info User name: parrt Client name: parrt.nfs Client host: nexus.cs.usfca.edu Client root: /home/parrt/depot Current directory: /home/parrt/depot Client address: 138.202.170.4:58303 Server address: dweller.cs.usfca.edu:1666 Server root: /var/local/perforce Server date: 2003/10/21 13:21:54 -0700 PDT Server version: P4D/LINUX24X86/2003.1/46260 (2003/07/03) Server license: Univ. of San Francisco 35 users (expires 2004/08/11)
Password: your-password
[parrt@nexus test]$ p4 edit A.java //depot/test/A.java#2 - opened for editand another like this:
~/USF/depot/test $ p4 edit A.java //depot/test/A.java#2 - opened for edit ... //depot/test/A.java - also opened by parrt@parrt.nfsThis means that somebody is alreadying editing it and whoever submits their changes last will have to do a resolve. If the first person changes A.java to:
/** A */ public class A { int i; }and submits, perforce will not complain:
Change 9 created with 1 open file(s). Submitting change 9. Locking 1 files ... edit //depot/test/A.java#3 Change 9 submitted.However, the other user changes A.java to
/** A is a test file */ public class A { }Upon submit they will see:
Change 10 created with 1 open file(s). Submitting change 10. //depot/test/A.java - must resolve before submitting //depot/test/A.java - must resolve #3 Out of date files must be resolved or reverted. Submit failed -- fix problems above then use 'p4 submit -c 10'.There are two different changes to be made to the original A.java. You are the second to submit so must do the resolve. Type p4 resolve to see what perforce knows about the changes:
~/USF/depot/test $ p4 resolve /Users/parrt/USF/depot/test/A.java - merging //depot/test/A.java#3 Diff chunks: 1 yours + 1 theirs + 0 both + 0 conflicting Accept(a) Edit(e) Diff(d) Merge (m) Skip(s) Help(?) am:The am means accept merged file. Since no chunks are conflicting (i.e., on the same line), it is ok to accept the merge. perforce will respond:
//parrt.localhost/test/A.java - merge from //depot/test/A.javaDoing a submit will now work:
~/USF/depot/test $ p4 submit -c 10 Submitting change 10. Locking 1 files ... edit //depot/test/A.java#4 Change 10 submitted.Finally, have the original modifier person sync to get the merged copy of the file. Now both people will see:
~/USF/depot/test $ cat A.java /** A is a test file */ public class A { int i; }In general you should be VERY careful modifying the same file as your partner. You should agree on boundaries. | https://www.cs.usfca.edu/~parrt/course/601/labs/perforce.html | CC-MAIN-2020-16 | refinedweb | 492 | 62.04 |
Hey. It allows the computation of immutable values in an asynchronous manner i.e. in a non-blocking manner.
What is a Future?
A Future represents a value that will be available in the future or the exception that occurred while evaluating that value. A Future is a concurrency abstraction that represents a future value and comes with a very powerful and convenient API that lets you deal with that future result in a type-safe and high-level manner. A Future can be in three possible states: it can either be scheduled/running, failed, or successful.
Whenever a Future operation is created, Scala creates a new thread to execute the Future’s code.
How to use Futures?
To use Scala Futures, we require an Execution Context which executes the Future and this acts as a thread pool. Execution Context is provided implicitly to the code running in Future.
We require the following two imports to execute a future:
import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global
Creating a Future in Scala is easy, we need to simply enclose a block of code in the Future. This can be seen in the following example:
scala> def sum(x: Int, y: Int) = Future { x + y } sum: (x: Int, y: Int)scala.concurrent.Future[Int]
The above example creates a future called sum which is of type Future[Int] and this function will get executed in a separate thread when it is called.
Callback mechanism
You require a callback mechanism for a future to process the result of the future obtained after execution. We need to write callback functions which execute on the basis of success or failure of Future’s execution. Following callback functions can be used :
onComplete: It takes a callback function of type Try[T] => U i.e. the future gets completed, either with a successful result or failure.
onSuccess: This method is called when the future gets completed with a successful result. It takes a partial function.
onFailure: This method is called when the future gets completed with a failure. It also takes a partial function.
All the above callback functions return Unit and so are avoided for use. It is not necessary that the callback function will be executed on the same thread or a different thread and there is no specific order in their execution.
For example,
scala> sum(9,8).onComplete{ case Success(result) => print(result) case Failure(ex) => print(ex) } 17
To use the above code, include the following imports:
import scala.util.Success and import scala.util.Failure
Further many combinators can be used with Futures to use the result obtained after the execution of Future. For example, map, flatmap and foreach (used to process the successful result of futures), recover, recoverWith and fallBackTo (used to handle failure in futures).
Also, for comprehension can be used to combine multiple futures which run independently which makes the code a lot cleaner and optimized. To use for comprehension, we must first declare the individual futures, then combine them using a for-yield construct and then process the final result of all the futures. For example,
scala> val f1 = Future { Thread.sleep(800); 1 } f1: scala.concurrent.Future[Int] = Future() scala> val f2 = Future { Thread.sleep(200); 2 } f2: scala.concurrent.Future[Int] = Future() scala> val f3 = Future { Thread.sleep(400); 3 } f3: scala.concurrent.Future[Int] = Future() scala> val result = for { | r1 <- f1 | r2 <- f2 | r3 <- f3 | } yield (r1 + r2 + r3) result: scala.concurrent.Future[Int] = Future() scala> result.onComplete { | case Success(result) => print(result) | case Failure(ex) => print(ex) | } 6
Conclusion
Multithreading code is difficult to write but with the help of immutability in functional programming and with the use of Scala Future libraries, it has become a lot easier. They provide mechanisms to handle failures, combine futures, process results of futures in an easy manner.
Hope this blog is helpful in writing non-blocking concurrent code.
Thanks for reading! | https://blog.knoldus.com/back2basics-futures-in-scala/?shared=email&msg=fail | CC-MAIN-2018-39 | refinedweb | 658 | 57.57 |
Stuart commented:
What do you do if you have a Java program that depends on String.hashCode() doing exactly what Java defines it to do (ie, produce consistent output with other VMs) rather than what .NET defines String.GetHashCode() to do? I encountered this in my own code so in theory I can implement (or steal from ClassPath) an implementation of String.hashCode() and use that, but the problem could come up in other scenarios. It's an interesting one, don't you think? :)
I haven't gotten around to implementing it, but the idea is that all virtual calls to Object.toString() are changed to:
if(o instanceof String) return StringHelper.hashCode(o); else return Object.GetHashCode();
One reason I haven't done this yet, is because I think it is totally brain damaged that Sun actually specified the hashcode algorithm for String (and in JLS 1.0 they specified a broken algorithm, which JDK 1.0 didn't implement), another reason is that I haven't figured out how to build this generically (specified in the map.xml file, instead of hardcoded in the VM).
A similar issue also occurs with Object.toString(). Nonvirtual calls to Object.toString() should be redirected to a helper function that returns:
getClass().getName() + "@" + Integer.toHexString(hashCode())
This isn't really a problem (if you accept the fact that non-Java classes return something different for toString(), which I do), but for arrays it does pose a problem. For arrays to return the proper string when toString() is called on them (virtually through an object reference), all virtual calls to Object.toString() need to be treated like hashCode() above.
btw, how come your example isn't "import System.Reflection"? Does netexp auto-lowercase all namespace names?
At the moment it does. Not because this is the Java convention, but because Java cannot really deal with a namespace System (because of the class java.lang.System).
That seems risky if (as I believe, but don't know for sure) it's possible to have two distinct .NET namespaces with names differing only by case...
This is true, but in practice it seems unlikely you'll ever encounter a problem with this, but the case conversion will definitely be optional in the) | http://weblog.ikvm.net/CommentView.aspx?guid=37 | CC-MAIN-2021-04 | refinedweb | 377 | 58.58 |
A common need for Windows forms is to remember the last position, size and state of the form. One way to do this is to call a function when your form loads and closes. I decided to do it the Object Oriented way. If your form inherits this class, it will automatically load and save the the form settings; Left, Top, Height, Width, and State; to a .config file.
using KrugismSamples" to the list of references at the top of the form code.
public class Form1 : System.Windows.Forms.Form
to:
public class Form1 : PersistentForm
That's it! When the form is loaded, the saved values are set to the form. When the form is closed, the settings are saved.
PersistentFormclass in the Add Reference, Projects tab.
Imports KrugismSamples" to the top of the source.
Inherits System.Windows.Forms.Form
to:
Inherits PersistentForm
That's it! When the form is loaded, the saved values are set to the form. When the form is closed, the settings are saved.
This class is very straightforward. It simply inherits the
Windows.Forms.Form class. It then overrides the
OnCreateControl() and
OnClosing() events. By
overriding the base events, no additional code needs to be added to the form.
(The
LoadSettings() and
SaveSettings() code is not
shown here.)
public class PersistentForm : System.Windows.Forms.Form { public PersistentForm() { } protected override void OnCreateControl() { LoadSettings(); // Load the saved settings from the file base.OnCreateControl (); } protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { SaveSettings(); // Save the settings to the file base.OnClosing(e); } }
General
News
Question
Answer
Joke
Rant
Admin | http://www.codeproject.com/KB/cs/persistentform_class.aspx | crawl-002 | refinedweb | 261 | 61.22 |
Cannot import quandl in Python 3
import quandl in spyder
quandl python github
quandl get not working
python get economic data
quandl package
is quandl free
modulenotfounderror no module named inflection
I have spyder (Python2.7) and spyder3 (Python3.5) installed on Ubuntu 16.04. I was able to import quandl in spyder (Python2.7) setup, but not in spyder3 (Python3.5). Do you have any suggestions?
Below is the error returned in the terminal when testing Python 3.5:
Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import quandl Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'quandl' >>> import Quandl Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named 'Quandl'
It would seem your Python3.5 installation does not have quandl installed.
You can install quandl easily via pip using:
pip install quandl
(or
pip3 install quandl depending on your system's configuration)
installation & authentication, You can download the Quandl Python package from PyPI or from GitHub. Python. pip install quandl import quandl. On some systems, you may need this you can find detailed installation instructions for Python modules here: Python 3.x. Sounds like the wrong version installed. What version of Python are you using? IIRC, Quandl is made for Py 2 only or some nonsense. Gotta go in and fix it if you want to use with Python 3. It's a really basic single-script module. You can run it through 2to3.py.
try lowercase. it works for in 3.5.2
Quandl Installed but Import Error, What version of Python are you using? IIRC, Quandl is made for Py 2 only or some nonsense. Gotta go in and fix it if you want to use with Python 3. It's a really Cannot download quandl with python 3.7. Ask Question Asked 1 year, 11 months ago. Python import not working at all. 0. Python Quandl installed but not importing. 0.
I was following a tutorial where it said
import Quandl
instead I used
import quandl
and it worked
I had the same problem although I have installed quandl correctly using
pip install quandl
hope this helps somebody
issue in importing quandl · Issue #2874 · jupyter/notebook · GitHub, import quandl output: ModuleNotFoundError Traceback (most recent call last) in () ----> 1 import quandl 2 ModuleNotFoundError: No module named 'quandl' i am using python jupyter. Requirement already satisfied: chardet<3.1.0,>=3.0.2 in You can't perform that action at this time. You signed in with Python 3.7.3 The strange part occurs when i try running a one line python script with import quandl . This time the program runs without errors, which means that the cause of the ModuleNotFoundError: No module named 'quandl' is the jupyter notebook, which is not being able to properly find the quandl module.
On systems that have both 2.x and 3.x installed you need to adjust your use of the pip command as follows:
To pip install package_name to target your 2.x python use: pip install package_name
To pip install package_name to target your 3.x python use: pip3 install package_name
Do not rename / reassign pip and pip3, they are not the same.
No module named 'quandl' · Issue #140 · quandl/quandl-python , I'm python 3.7 and I already install quandl but still can't import quandl can fix this problem? Requires: Python >= 3.5 Maintainers administrator-quandl couture-ql eric.vautour jjmar junos scott_quandl shuof
Maybe
pip3 install quandlwill work here.
However, you can find explicitly your pip script inside your python3 directory. then run the following command:
pip install quandl
you can rename or alias
pip script inside the python3 directory to
pip3 for better use in the future.
python 3.x - cannot import quandl in python3 -, import quandl traceback (most recent call last): file "", line 1, in importerror: no module named 'quandl' import quandl traceback (most recent call Our first python script. Lets test out the Quandl python library by running a simple python script that will get some data from Quandl. Create a directory where we will store files: Create directory. 2. Open a command prompt and type “python” to access the python environment: Python cli. 3.
Python cannot import quandl, I can't believe I didn't even realize that. More posts from the learnpython community. The Quandl package is here. In order to install this for Python 3, modify the setup.py file's print statements (they are 2.7 syntax). If setup.py doesn't work for you, then just manually move the package right in. So, when you've downloaded Quandl and extracted it, you should have a "Quandl" directory from the download.
Quandl import error : learnpython, Trouble with importing Quandl and pandas to IDLE But cannot import in IDLE. 2. Also anaconda/lib/python3.6/site-packages (from pandas). Usage Limits. The Quandl Python module is free. If you would like to make more than 50 calls a day, however, you will need to create a free Quandl account and set your API key:
Trouble with importing Quandl and pandas to IDLE, I tryed puting in the command prompt Quandl and then my file like in pgzrun but it says that there's no module I am using Python 3 in a PC. PYTHON. Get millions of financial and economic datasets from hundreds of publishers directly into Python. Most datasets on Quandl, whether in time-series or tables format, are available from within Python, using the free Quandl Python package. The Quandl package uses our API and makes it amazingly easy to get financial data.
- I can install and import quandl on 3.6.
- try to install quandl for python3, just download the source and install it with "python3 setup.py install"
- Many thanks to all for your answers! Already fixed the problem. Ended up with using "pip3 install quandl" for Python3.5 associated with spyder3
- i am using python 3.6.5
- ModuleNotFoundError: No module named 'quandl' | http://thetopsites.net/article/51693221.shtml | CC-MAIN-2020-45 | refinedweb | 1,024 | 66.44 |
A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement that allows a program to make a decision based on the value of a condition. For example, the condition "grade is greater than or equal to 60" determines whether a student passed a test. If the condition in an if statement is true, the body of the if statement executes. If the condition is false, the body does not execute. We will.
The application of Fig. 2.15 uses six if statements to compare two integers input by the user. If the condition in any of these if statements is true, the assignment statement associated with that if statement executes. The program uses a Scanner to input the two integers from the user and store them in variables number1 and number2. Then the program compares the numbers and displays the results of the comparisons that are true.
Figure 2.15. Equality and relational operators.
(This item is displayed on pages 57 - 58 in the print version)
The declaration of class Comparison begins at line 6
public class Comparison
The class's main method (lines 941) begins the execution of the program.
Line 12
Scanner input = new Scanner( System.in );
declares Scanner variable input and assigns it a Scanner that inputs data from the standard input (i.e., the keyboard).
Lines 1415
int number1; // first number to compare int number2; // second number to compare
declare the int variables used to store the values input from the user.
Lines 1718
System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user
prompt the user to enter the first integer and input the value, respectively. The input value is stored in variable number1.
Lines 2021
System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user
prompt the user to enter the second integer and input the value, respectively. The input value is stored in variable number2.
Lines 2324
if ( number1 == number2 ) System.out.printf( "%d == %d ", number1, number2 );
declare an if statement that compares the values of the variables number1 and number2 to determine whether they are equal. An if statement always begins with keyword if, followed by a condition in parentheses. An if statement expects one statement in its body. The indentation of the body statement shown here is not required, but it improves the program's readability by emphasizing that the statement in line 24 is part of the if statement that begins on line 23. Line 24 executes only if the numbers stored in variables number1 and number2 are equal (i.e., the condition is true). The if statements at lines 2627, 2930, 3233, 3536 and 3839 compare number1 and number2 with the operators !=, <, >, <= and >=, respectively. If the condition in any of the if statements is true, the corresponding body statement executes.
Common Programming Error 2.9
Common Programming Error 2.10
Common Programming Error 2.11
Common Programming Error 2.12
Good Programming Practice 2.15
Good Programming Practice 2.16
Note that there is no semicolon (;) at the end of the first line of each if statement. Such a semicolon would result in a logic error at execution time. For example,
if ( number1 == number2 ); // logic error System.out.printf( "%d == %d ", number1, number2 );
would actually be interpreted by Java as
if ( number1 == number2 ) ; // empty statement System.out.printf( "%d == %d ", number1, number2 );
where the semicolon on the line by itselfcalled the empty statementis the statement to execute if the condition in the if statement is true. When the empty statement executes, no task is performed in the program. The program then continues with the output statement, which always executes, regardless of whether the condition is true or false, because the output statement is not part of the if statement.
Common Programming Error 2.13
Note the use of white space in Fig. 2.15. Recall that white-space characters, such as tabs, newlines and spaces, are normally ignored by the compiler. So statements may be split over several lines and may be spaced according to the programmer's preferences without affecting the meaning of a program. It is incorrect to split identifiers and strings. Ideally, statements should be kept small, but this is not always possible.
Good Programming Practice 2.17
Figure 2.16 shows the precedence of the operators introduced in this chapter. The operators are shown from top to bottom in decreasing order of precedence. All these operators, with the exception of the assignment operator, =, associate from left to right. Addition is left associative, so an expression like x + y + z is evaluated as if it had been written as ( x + y ) + z. The assignment operator, =, associates from right to left, so an expression like x = y = 0 is evaluated as if it had been written as x = ( y = 0 ), which, as we will soon see, first assigns the value 0 to variable y and then assigns the result of that assignment, 0, to x.
Good Programming Practice 2 | https://flylib.com/books/en/2.254.1/decision_making_equality_and_relational_operators.html | CC-MAIN-2018-22 | refinedweb | 845 | 57.47 |
Here is my assignment.
The Gregorian calendar was introduced in 1582. Every year divisible by four was
declared to be a leap year, with the exception of the years ending in 00 and not divisible
by 400. So 1200, 1600, and 2000 are leap years while 1300, 1400, 1800, and 1900 are
not. Write a program that requests a year as input and states whether it is a leap year.
Code Java:
/** * * Author : Gregory B Shavers Jr * CSC 225 - Online * problem 6 */ import java.util.*; public class problem6 { public static void main( String [] args) { double year, leapYear, leapYear2; Scanner scan = new Scanner(System.in); System.out.print(" What is the year? ");//ask for year year = scan.nextDouble(); leapYear = year%400;//calualates leap year leapYear2 = year%4; //calualates leap year if ( leapYear == 0 ) { System.out.println( " This is a leap year. " ); //display leap year } else if ( leapYear2 == 0 ) { System.out.println ( " This is a leap year." ); // display not leap year } else { System.out.println( " This is not a leap year."); } } }
I need help writing a condition statement to finish this assignment. My condition statement should not allow a number to be a leap year if its not equal to 00 and not divisible by 400. Is there any ideas?
Thanks Again!
--- Update ---
I'm sorry ending with 00. | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/23860-need-help-gregorian-calendar-printingthethread.html | CC-MAIN-2014-49 | refinedweb | 217 | 77.64 |
Hey Guys,
I'm trying to do a basic line graph here, but I can't seem to figure out how to adjust my x axis.
from pylab import * plot ( range(0,10),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' ) plot ( range(0,10),[12,5,33,2,4,5,3,3,22,10],'o-',label='sample2' ) xlabel('x axis') ylabel('y axis') title('my sample graphs') legend(('sample1','sample2')) savefig("sampleg.png",dpi=(640/8)) show()
And here is the error I get when I try adjusting my range.
File "C:\Python26\lib\site-packages\matplotlib\axes.py", line 228, in _xy_from_xy raise ValueError("x and y must have same first dimension") ValueError: x and y must have same first dimension
I want my range to be a list of strings: ["12/1/2007","12/1/2008", "12/1/2009","12/1/2010"
Any suggestions? | https://www.daniweb.com/programming/software-development/threads/278326/x-axis-on-a-simple-line-graph-in-matplotlib | CC-MAIN-2018-26 | refinedweb | 151 | 61.26 |
Java CGI HOWTO
by David H. Silber v0.5, 1 December 1998
This e-mail address is being protected from spambots. You need JavaScript enabled to view it particular version of unix used.
1. Introduction.2 Overcoming Problems in Running Java CGI Programs
5. Using the Java CGI Classes.
This e-mail address is being protected from spambots. You need JavaScript enabled to view it
.
1.4 The Mailing List
I have created a majordomo list to allow people to help each-other
work through their mutual problems in installing and using this
software. Send a message to
This e-mail address is being protected from spambots. You need JavaScript enabled to view it
,
containing the word subscribe.
2. Setting Up Your Server to Run Java CGI Programs (With Explanations))
- Get the Java CGI package from. (The version number may have changed.)
- Unpack the distribution with this command:
gzip -dc java_cgi-0.5.tgz | tar -xvf -(If the version number has changed, use the instructions from within that distribution from this point on.)
- Edit the
Makefileyou will find in the newly created directory
java_cgi-0.5as appropriate to your system.
- As root, run
make install. This will compile the Java programs, apply your system-specific information and install the various files. If you want the HTML version of this documentation and an HTML test document, run
make allinstead.
- You should be ready to go.
4. Executing a Java CGI Program
4.1 Obstacles to Running Java Programs Under the CGI Model
There are two main problems in running a Java program from a web server:
You can't run Java programs like ordinary executables.
You need to run the Java run-time interpreter and provide the initial class (program to run) on the command-line. With an HTML form, there is no provision for sending a command-line to the web server..
Invoking java.cgi from an HTML form..
HTML classes.
5.1 CGI
Class Syntax
public class CGI
Class Description
The CGI class holds the ``CGI Information'' -- Environment
variables set by the web server and the name/value sent from a form
when its submit action is selected. All information is
stored in a
Properties class object.
This class is in the ``Orbits.net'' package.
Member Summary
CGI() // Constructor. getNames() // Get the list of names. getValue() // Get form value by specifying name.
See Also
CGI_Test.
CGI()
- Purpose
Constructs an object which contains the available CGI data.
- Syntax
public CGI()
- Description
When a CGI object is constructed, all available CGI information is sucked-up into storage local to the new object.
getNames()
- Purpose
List the names which are defined to have corresponding values.
- Syntax
public Enumeration getKeys ()
- Description
Provides the full list of names for which coresponding values are defined.
- Returns
An
Enumerationof all the names defined.
getValue()
- Purpose
Retrieves the value associated with the name specified.
- Syntax
public String getValue ( String name )
- Description
This method provides the corespondence between the
namesand
valuessent from an HTML form.
- Parameter
- name
The key by which values are selected.
- Returns
A
Stringcontaining the value.
5.2 CGI_Test
This class provides both an example of how to use the
CGI class and a test program which can be used to
confirm that the Java CGI package is functioning
correctly.
Member Summary
main() // Program main().
See Also
CGI.giscript. Currently unused.
5.3 Email
Class Syntax
public class Email extends Text
Class Description
Messages are built up with the
Text class
add*() methods and the e-mail-specific methods added
by this class. When complete, the message is sent to its
destination.
This class is in the ``Orbits.net'' package.
Member Summary
Email() // Constructor. send() // Send the e-mail message. sendTo() // Add a destination for message. subject() // Set the Subject: for message.
See Also
- Purpose
Constructs an object which will contain an email message.
- Syntax
public Email()
- Description
Sets up an empty message to be completed by the Email methods.
- See Also
Text.
send()
- Purpose
Send the e-mail message.
- Syntax
public void send ()
- Description
This formats and sends the message. If no destination address has been set, there is no action taken.
sendTo()
- Purpose
Add a destination for this message.
- Syntax
public String sendTo ( String address )
- Description
Add
addressto.
- Parameter/
- address
A destination to send this message to.
Member Summary
main() // Program main().
See
- Parameter
- argv[]
Arguments passed to the program by the
java.cgiscript. Currently unused.
5.5 HTML
Class Syntax
public class HTML extends Text
Class Description.
Member Summary.
See Also
HTML_Test, Text.
HTML()
- Purpose
Constructs an object which will contain an HTML message.
- Syntax
public HTML()
- Description
Sets up an empty message to be completed by the HTML methods.
- See Also
Text.
author()
- Purpose
Set the name of the document author.
- Syntax
public void author ( String author )
- Description
Set the name of the document author to
author.
- Parameter/
- author
The text to use as the author of this message.
- See Also
title().
definitionList()
- Purpose
Start a definition list.
- Syntax
public void definitionList ()
- Description.
- See Also
definitionListTerm(),
endList(),
listItem().method is called.
- See Also
definitionList(),
listItem().
endList()
- Purpose
End a list.
- Syntax
public void endList ()
- Description
End a list. This method closes out a list. Note that, currently, lists cannot be nested.
- See Also
definitionList().
listItem()
- Purpose
Add an entry to a list.
- Syntax
public void listItem ()
public void listItem ( String item )
public boolean listItem ( String term, String item )
- Description
Add an entry to a list. If the first form is used, the text for the current list item should be appended to the message after this method is called and before any other list methods are called. In the second and third forms, the
itemtext is specified as a parameter to the method instead of (or in addition to) being appended to the message. The third form is specific to definition lists and provides both the term and the definition of the list entry.
- Parameters
- item
The text of this list entry.
- term
The text of this definition list entry's term part.
- See Also
definitionList(),
definitionListTerm(),
endList().
send()
- Purpose
Send the HTML message.
- Syntax
public void send ()
- Description
Send the HTML message..
Member Summary
main() // Program main().
See Also
HTML.giscript. Currently unused.
5.7 Text
Class Syntax
public abstract class Text
Class Description
This class is the superclass of the
HTML classes. Messages are built up with the methods
in this class and completed and formatted with the methods in
subclasses.
This class is in the ``Orbits.text'' package.
Member Summary
Text() // Constructor. add() // Add text to this object. addLineBreak() // Add a line break. addParagraph() // Add a paragraph break.
See Also
HTML.
add()
- Purpose
Add text to this item.
- Syntax
public void add ( char addition )
public void add ( String addition )
public void add ( StringBuffer addition )
- Description
Add
additionto the contents of this text item.
- Parameter
- addition
Text to be added to the text item.
- See Also
addLineBreak(),
addParagraph().
addLineBreak()
- Purpose
Force a line break at this point in the text.
- Syntax
public void addLineBreak ()
- Description
Add a line break to the text at the current point.
- See Also
add(),
addParagraph().
addParagraph()
- Purpose
Start a new paragaph.
- Syntax
public void add ()
- Description
Start a new paragraph at this point in the text flow.
- See Also
add(),
addLineBreak().
6. Future Plans
- message.
-.
- Allow HTML lists to be nested.
- Add error checking code to enforce correct ordering of HTML list formatting codes.
- The location of the file of environment data should be configurable from the
Makefile.
- Get rid of the spurious empty name/value pair that appears in the list when we are dealing with the GET method of data transfer.
- Consider having CGI implement the java.util.Enumeration interface to successively provide variable names.
- Add a
Testclass, which would use every method in this package.
- Document how
CGI_Test,
HTML_Testbuild on each other to provide incremental tests for debugging purposes.
- Document how Test uses every feature available in this package.
7. Changes
7.1 Changes from 0.4 to 0.5
- Changed documentation and comments to reflect the final nature of this release.
7.2 Changes from 0.3 to 0.4
- Fleshed out the HTML class to provide minimal functionality.
- Wrote the HTML_Test class and javahtmltest.html-dist.
- Added the HTML methods to deal with a definition list.
7.3 Changes from 0.2 to 0.3
- Added the Text and Email classes. HTML was also added, but it is merely a stub at this point.
- Put the various classes into packages. The main classes are in
Orbits.net.*, the support class
Textis in
Orbits.text.Text.
- Changed
CGItestto
CGI_Test.
- Added the
7.4 Changes from 0.1 to 0.2
- The environment variables are put into a temportary file instead of being crammed into the Java inperpreter command-line. The
CGIclass and
java.cgihad to be modified.
- The
javacgitest.htmldocument is made part of the distribution.
- The text files which are modified by
makeupon installation are provided with names that end with -dist. | http://www.linux.com/learn/docs/ldp/Java-CGI-HOWTO | CC-MAIN-2014-41 | refinedweb | 1,493 | 61.43 |
An unexpected journey
I didn’t set out on my career path, at least not intentionally. After college, I was certain I wanted to write and perform music for a living, but while working at an odd job I discovered I really liked “working with computers”. I didn’t really know what that meant since my degree is in English, so I thought I’d go back to school for Computer Science. While there, a kind professor handed me a copy of RedHat 5.0 (did I just date myself?) so I could do my projects at home, allowing me to help with the baby on the way.
I had compilers and editors and desktops and servers and source code all just in this box of CDs. It was Free, and I was free to tear stuff apart and examine it and learn. Not long after, I moved to Debian and over the next few years bought probably thousands of dollars in computer books and just devoured them. I also got some old IBM computers second-hand and set up a little network to learn all I could about server software, which led me to develop an intense interest in security. It was fantastic.
Fast forward a bit, and I found myself setting up a business with Debian Woody. Back then Debian stable still had the GNOME 1.4 desktop (aliased fonts!) and I found an unofficial set of GNOME 2 packages (anti-aliased fonts! ;), but I really wanted GNOME 2.2 for the business laptops. The developer all of it as the “GNOME 2.2 Backport for Debian Woody” and provided security support and an upgrade path for the backport for more than 3 years until Woody’s end of life. People seemed to really like it, and this experience helped me understand how much good you can bring to people by working on open source software.
Thinking back on my experience and Ubuntu’s roots, it was almost inevitable that I started working for Canonical, where I worked for 13 years in various capacities on the Ubuntu Security team. While there, I learned from my colleagues, stretched and grew. I started doing reactive security but then took on various engineering-focused leadership roles. Eventually I worked for now fellow Influxer Rick Spencer. We worked in earnest on the Ubuntu Phone where I spent most of my time designing and maintaining the application sandbox for the new ‘click’ packaging format. After a while, click packages evolved into snaps where I spent lots of time on its even more ambitious sandboxing mechanism that took advantage of cool Linux security primitives like AppArmor, seccomp, namespaces, capabilities, cgroups and more.
Snaps really took off, and I found myself helping teammates, community members and partners with their applications packaged as snaps by routinely deep-diving into all kinds of disparate topics and codebases like the kernel, systemd, Kubernetes, the chromium content API, robotics, wayland, containerd, polkit, DBus, (what felt like) a gazillion syscalls and on and on. For someone who loves to learn, I learned a lot!
A warm welcome
Late last year, I was ready for a change and I reflected on my career and thought about what was important to me. I serendipitously read Rick’s Why I Joined InfluxDB where he discusses what he feels the three components of loving your job are:
- What you do
- How you do it
- Who you do it with
This really resonated with me. After some wonderful conversations with Rick and other great folks (you know who you are!), I joined InfluxData late last January.
At InfluxData, an important part of our mission is providing great tools and experiences for developers so they can do great things. Since I’m happiest when I’m able to bring value by helping others achieve their goals, what we do as a company aligns perfectly for me. We have a culture of working together, and day-to-day, I’m able to share my experience to help solve interesting problems and learn a bunch of cool new stuff in the process.
In terms of how we do things, open source (an important theme in my career) is the foundation of InfluxData. The heart of our products is open source, we develop with open source tools and we run on infrastructure built on open source. Plus, we are a distributed company, and I’m free to work where I want and free to choose the tools that work best for me (open source of course).
I’ve had the pleasure to work with many great people during my career, but there is something different and special about InfluxData. I had the opportunity to talk with Ryan Betts before starting and he spoke warmly to the importance of culture, inclusion and kindness. This was echoed throughout the hiring process and after I joined. My team and everyone I’ve worked with have all been fantastic! Now I get to experience and be a part of our culture all while working alongside and for passionate, talented and kind people every day.
Six months in, I’m very grateful for the opportunity and so glad I joined. | https://w2.influxdata.com/blog/why-i-joined-influxdata-jamie-strandboge/ | CC-MAIN-2022-33 | refinedweb | 866 | 68.91 |
memset() prototype
void* memset( void* dest, int ch, size_t count );
The
memset() function takes three arguments: dest, ch and count. The character represented by ch is first converted to unsigned char and then copies it into the first count characters of the object pointed to by dest.
The behaviour of the function is undefined if:
- The object is not trivially copyable.
- count is greater than the size of dest.
It is defined in <cstring> header file.
memset() Parameters
- dest: Pointer to the object to copy the character.
- ch: The character to copy.
- count: Number of times to copy.
memset() Return value
The memset() function returns dest, the pointer to the destination string.
Example: How memset() function works
#include <cstring> #include <iostream> using namespace std; int main() { char dest[50]; char ch = 'a'; memset(dest, ch, 20); cout << "After calling memset" << endl; cout << "dest contains " << dest; return 0; }
When you run the program, the output will be:
After calling memset dest contains aaaaaaaaaaaaaaaaaaaa | https://www.programiz.com/cpp-programming/library-function/cstring/memset | CC-MAIN-2020-16 | refinedweb | 162 | 63.7 |
I have a difficulty to create a C program for the converting calender date into Julian and reverse. and also Computing days between two calendar dates. I will be so appreciated if someone can help me. to write this program. Here is the complete explanation for writing this program: A calendar date is simply a date that contains a year, month, and day and a Julian date is an integer between 1 and 366, inclusive, which tells how m any days have elapsed since the first of January in the current year (including the day for which the date is calculated). For example, calendar date 4/12/2008 is equivalent to Julian date 103, 2008. Write a C program to contain a selection menu (hint: think do - while loop) that allows the user to choose one of the options. An illustration is given below: DATE SELECTION MENU 1) Convert calendar date into Julian date 2) Convert Julian date into calendar date 3) Compute days between two calendar dates 4) Exit program ENTER SELECTION (1-4): Be sure your program contains separate functions for each of the required operations, passing parameters as necessary. Remember that no global variables are allowed in your program except for the file pointer. You should create at least the following functions for your program: display Menu displays selection menu and prompts user for selection get Calendar Date prompts and gets calendar date from user get Julian Date prompts and gets Julian date from user to Calendar converts Julian date into calendar date to Julian converts calendar date into Julian date days Between Dates calculates the number of days between two calendar dates Hint to compute the number of days between two calendar dates: For each date, figure out the number of days since January 1, 1900 and then subtract. For this assignment we will define a leap year as any year that is evenly divisible by 4 but not 100, except that years divisible by 400 are leap years. Here�s a function you can use to calculate leap years. Try and work through its details. int isLeapYear(int year) { return ((!(year % 4) && year % 100) || !(year % 400)); } Test data for the lab is given below. Be sure to turn in output for each of the test data provided below. The information appearing in the parentheses after each piece of the test data are the correct (hopefully) solutions. You may use these solutions to test your program on the supplied test data. Ultimately, however, your program should be able to run on any valid data. | http://www.chegg.com/homework-help/questions-and-answers/difficulty-create-c-program-converting-calender-date-julian-reverse-also-computing-days-tw-q3813539 | CC-MAIN-2015-32 | refinedweb | 428 | 58.42 |
if you mean this sketch, i just tried: keeps saying "no i2c devices found"
Were working on the Astra G/corsa C/ Vectra C version.
void TID::cycle(){ start_tid(); tid_address(); tid_data(_SYMBOLS1); tid_data(_SYMBOLS2); tid_data(_SYMBOLS2);// needs three sets of symbols for the 10 digit display for (int i=0; i<10;i++){ // <<<<<<<needs to cycle up to 10!!! tid_data(_display[i]); }; stop_tid();}
tid_byte(0x9B); //the address for the 8 char display is embedded here, for the 10 char you have to use 0x9A <<wrong
and there was an error in the code, it said 0x9A where 0x9B is needed
#include <TID.h>//Created by Daniel CraneTID mydisplay(3,4,5);//SDA, SCL, MRQvoid setup(){ pinMode(13,OUTPUT);}void loop(){ mydisplay.display_message("SCROLLING MONKEY5!",500); digitalWrite(13,HIGH); delay(500); digitalWrite(13,LOW); delay(1000); }
mydisplay.display_message("SCROLLING MONKEY5!",500);
BTW: the TID in my Corsa is the same like in the Astra G, dandymon has shown a picture of it.
what I dont know for sure are the english terms since I am not a native speaker
if you have another suitable dc power supply
Or should this be managed from the Arduino, too? | http://forum.arduino.cc/index.php?topic=78634.msg1217773 | CC-MAIN-2015-35 | refinedweb | 195 | 56.29 |
Performance/Strings
From HaskellWiki
Latest revision as of 15:59, 31 August 2009
[edit] 1 Strings
Sometimes the cost of representing strings as lists of Char can be too much. In this case, you can instead use packed strings. There are a number of options:
- One of the packed string libraries, for example Data.ByteString
- Unboxed arrays of Word8 or Char
- Ptrs to foreign malloced Word8 buffers
The packed string libraries have the benefit over arrays of Word8 or Char types, in that they provide the usual list-like operations.
Some interesting results for Data.ByteString are documented here. In particular, it compares FPS against the existing PackedString and [Char] functions, and is used successfully with 1 terabyte strings.
[edit] 2 Example
Pete Chown asked the question:
I want to read a text file. As an example, let's use /usr/share/dict/words and try to print out the last line of the file.
The python version completes in around 0.05s.
[edit] 2.1.
[edit] 2.2 Attempt 2 : Data.ByteString
Using ByteString, we get:
import qualified Data.ByteString as B import IO main = B.readFile "/usr/share/dict/words" >>= B.putStr . last . B.lines
Runs in 0.063s
[edit] 2.3 Attempt 3 : No Lists
Avoid splitting the file into lists at all, and just keep a single buffer (as a C programmer would perhaps do):
import qualified Data.ByteString as P import Maybe import IO main = P.readFile "/usr/share/dict/words" >>= P.putStrLn . snd . fromJust . P.breakLast '\n'
Runs in 0.013s
[edit] 2.4 Related work
An extended tutorial on using PackedStrings/ByteStrings for high performance string manipulating code is here.
A discussion of the fastest way to parse a file of numbers, comparing various approaches using ByteStrings. | https://wiki.haskell.org/index.php?title=Performance/Strings&diff=29879&oldid=2337 | CC-MAIN-2017-22 | refinedweb | 294 | 68.36 |
CHFLAGS(2) NetBSD System Calls Manual CHFLAGS(2)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
chflags, lchflags, fchflags -- set file flags
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <sys/stat.h> #include <unistd.h> int chflags(const char *path, u_long flags); int lchflags(const char *path,, or the effective user ID is not the super-user and one or more of the super-user-only flags for the named file would be changed. [EOPNOTSUPP] The named file resides on a file system that does not support, 9.99 August 6, 2011 NetBSD 9.99 | https://man.netbsd.org/macppc/chflags.2 | CC-MAIN-2022-05 | refinedweb | 109 | 68.26 |
Despite their many differences, all business plans have certain elements in common that all potential investors expect to find (Exhibit 1). Additionally, an appendix is often included that contains detailed information, often presented in the form of tables or graphs. Within this more or less required structure, the business plan is free to grow in its own direction. In Phase I, competitors only worked on a few key elements and individual topics. In Phase II, new elements are added while the topics from the previous phases are expanded, and, gradually, the plan fills with content.
ELEMENTS OF A BUSINESS PLAN
Part of this phase
Phase 1
Business
Phase 2
Business
Concept 1 Executive summary 2 Product or service 3 Management team 4 Market and competition 5 Marketing and sales 6 Business system and organization 7 Implementation schedule 8 Opportunities and risks 9 Financial planning and financing
Plan
Exhibit 9
1. Executive summary
"A good executive summary gives me a sense of why this is an interesting venture. I look for a very clear statement of the long-term mission, an overview of the people, the technology, and the fit to market."
Ann Winblad, Venture Capitalist
The executive summary is designed to pique the interest of decision makers. It should contain a brief overview of the most important aspects of the business plan. In particular, it should highlight the product or service, the value to the customer, the relevant markets, management expertise, financing requirements, and possible return on investment. Venture capitalists look at the executive summary first, though they usually just skim it. The quality of the summary itself is not likely to make them invest in your project, yet it can convince them not to. A clear, objective, and concise description of your intended start-up, which must be easy to comprehend, especially by the technical layperson, will show them that you know your business. Therefore, prepare your summary with the utmost care; it may well decide whether the rest of your business plan is read. The executive summary is an independent element of the business plan: Do not confuse it with the introduction of your business concept on the title page. Look at your executive summary with a critical eye – repeatedly – especially after all other aspects of your business plan have been completed. Ask yourself if you have described your business idea as clearly, compellingly, and concisely as you can. Your readers should be able to read and comprehend the summary in five to 10 minutes. Test it. Give your executive summary to someone who has no previous knowledge of your business concept or its technical or scientific basis.
KEY QUESTIONS: Executive summary What is your business idea? In what way does it fulfill the criterion of uniqueness? Who are your target customers? What is the value for those customers? What market volume and growth rates do you forecast? What competitive environment do you face? What additional stages of development are needed? How much investment is necessary (estimated)? What long-term goals have you set? How high do you estimate your financing needs? What are the sales, cost, and profit situations? What are the most important milestones along the way to your goal? What test customers have you approached/could you approach? What distribution channels will you use? What partnerships would you like to enter into? What opportunities and risks do you face? What is the picture on patents?
concrete steps! . Summarize the results of your detailed business planning and state your exact financing needs! How will you delegate management tasks? How much production capacity is necessary? How will the implementation of your business idea be organized? List your next.
If it enhances the understanding of your product. Development status of the product/service In explaining this issue. imagine you are the venture capitalist who wants to minimize the risk involved in participating. If you are offering a range of innovative products or services. Try to refrain from including technical details and describe everything as simply as possible. It is important to indicate how your product differs from those that are now or will be on the market. applying the same criteria to all. such as those of technical control associations. you must convincingly substantiate the added value your customers will receive from your start-up. Customer value It doesn't make any sense to start up a new business unless the product or service is superior to current market offerings. A finished prototype will show your potential investor that you are up to meeting the technical challenge. put yourself in the place of the customer and weigh the advantages and disadvantages of your product over the others very carefully. It is even better to have a pilot customer who already uses your product or service. Define the business areas in detail so there is no overlap. . This is the point at which you should address the subject of patents for protection from duplication or imitation." Bruno Weiss. include a photo or sketch in your business plan. A short description of how far development has progressed and what still needs to be done is also essential. the whole thing's a waste of time. have applied for. Note any permits you have obtained. Product or service "If you don't know what the customer value is. or will apply for. categorize them into logical business areas according to product or customer.2. the postal service. Regulatory requirements on products and services pose another set of risks. or the protection of a model through registration. Be sure to discuss in detail the function the product or service fulfills and the value the customer will gain from it. If there are still problems or issues to cover regarding development. or the department of health. To do so. You should also explain the nature of the innovation itself and the edge you have over competitors. If comparable products and services are already available from your competitors. Entrepreneur Your business plan derives from an innovative product or service and its value to the end consumer. be sure to mention them and how you intend to overcome these difficulties.
personnel. from whom and at what cost? What kind of service/maintenance will you offer? What product or service guarantees will you grant? Compare the strengths and weaknesses of comparable products/services with yours in an overview! What resources (time. materials) do you require for each subsequent development? What share of sales do you expect from your various products/services (if applicable)? Why? What income from royalties/sales do you estimate from possibly marketing the property rights? Who would be your licensees/buyers? . if so.KEY QUESTIONS: Product or service What end customers will you address? What are the customers’ needs? What customer value does your product/service provide? What is the nature of your innovation? What is the current status of technical development? What partnerships are necessary to achieve full customer value? What competitor products already exist or are under development? Is your product/service permitted by law? What are the prerequisites for development and manufacturing? What stage of development has your product or service reached? Do you have patents or licenses? What further development steps do you plan to take? What milestones must be reached? What versions of your products/services are designed for what customer groups and applications? What patents/licenses do the competitors have? Do you need to obtain licenses and.
accountants. Entrepreneurs frequently underestimate the significance of this question and make the mistake of skimping on content and making do with meaningless phrases. If key positions are to be given to inexperienced staff members. not ideas. be sure to emphasize those that are particularly important for implementing your specific plans. PR firms. or management consultants is a sign of professionalism and will reassure the venture capitalist that you have all the contacts you may need. Do not hesitate to name your most influential advisors. Take the time to describe your management team well. explain this decision in detail." Eugene Kleiner. Professional experience and past success carry more weight than academic degrees.regroups and makes a second or even third attempt to clear the hurdle Also explain how the responsibilities in the company are to be delegated and indicate which positions still require reinforcements.6. Venture Capitalist The management section is often the first part of the plan that venture capitalists turn to after reading the executive summary. but usually no more than six. people Committed to staying together through thick and thin Staying power. No one will have all the qualifications and experience necessary to found a company. They want to know whether the management team is capable of running a promising business. even when there are setbacks . . Considerable involvement on the part of advisors such as experienced entrepreneurs. Management team "I invest in people. When discussing management's qualifications. It is particularly helpful to compare the assignments to be filled with the skill profiles of current team members. CHARACTERISTICS OF A POWERFUL MANAGEMENT TEAM Common vision: Everybody wants to succeed Complementary attributes and strengths At least three.3.
Bringing together just the right people to form a "dream team. begin looking for suitable partners as soon as possible. success. requires a great deal of time and care.WHAT PROFESSIONAL INVESTORS LOOK FOR Has the team already worked together? Do team members have relevant experience? Do the founders know their weaknesses and are they willing to Have the founders agreed on their future roles? Are ownership Has the management team agreed on a common goal. professional experience. is immensely important for later business success and. standing in the business world? What experience or abilities does the team possess that will be useful for implementing your concept and setting up your company? What experience or abilities are lacking? How will the gaps be What goals do the team members pursue by starting up the How high is the motivation of each individual team member? closed? By whom? business? . KEY QUESTIONS: Management team • Who are the members of your management team and what distinguishes them: education. or are Do the individual team members fully back the project? make up for them? issues settled? there underlying differences of opinion? Finally. therefore." so to speak.
There may be many unknowns. of course. who are convinced they are getting a greater value than they would from a competing product. will buy your product. Market and competition "If there is no competition. You should also indicate what main factors are now influencing or may influence the given industry segment. Work with a focus in order to save yourself some energy: Work with hypotheses.. patent offices). your estimate will be harder to topple. • Think logically. and total dollars in sales. interviews. industry directories. or service. Be creative and determined. . Show what factors will affect developments (technology. Your expectations for market growth are critical. what information you will need. databases. as well as the willingness of your party to disclose information. market studies. for it is the customers who give your company a reason for being. chambers of commerce.4. Market size and growth A dramatic increase in the value of the company can be expected only if the market holds great potential. by buying – or not buying – your product. Using a short discussion outline will increase your efficiency and productivity. they will decide if and how successful your company will be. make a list of questions you want answered. observe the following: • Build on a solid foundation. An estimate should be a logical conclusion (i. And in the end. legislative initiatives. and where you might find it. etc. the Internet (keep your searches focused).) and what relevance these factors have for your business. The external data necessary for an analysis are often easier to obtain than you might think." Brian Wood Thorough understanding of your customers and their needs is the foundation of every successful business. Knowing your market and competition well is thus critical to the success of your undertaking. It often helps to call around. unit sales. The market size should be presented in figures representing the number of customers.e. it should not have any leaps in logic or depend on unspecified assumptions). When making an estimate. associations and government agencies (statistics offices. or by not buying a product at all. This collection of individual pieces of data seldom provides a direct answer to your questions – you will have to draw well-founded conclusions or make sound estimates. scholarly essays). Only those customers. make use of all possible sources including trade literature (journals. but if you rely on easily verifiable figures. there is probably no market. banks for industry surveys. and.
The shortest distance to your goal is not always a straight line. you must segment your market. look for a substitute variable that relates to the one you need. Check your facts. product application Buying habits: brand preferences. purchasing criteria. The choice of segmentation criteria is up to you. with a number of different sources if at all possible.. supplier agreements Situational factors: urgency of need. ask yourself. and that the customers within each segment can be reached by means of the same marketing strategy.as well as their behavior . active seniors Behavior: frequency of product use. company size Lifestyle: techies. digital. Depending on the industry. To do this. profession. and profit).• Compare your sources. such as statements made in an interview. Possible customer segmentation criteria for the consumer goods markets: Location: country. • Be creative. . Take your sales strategy and the behavior of the competition into consideration. counterculture. industry. For each estimate.can be determined. location Operations: technology employed (e. urban/rural (population density) Demographics: age. market share. For example. sales revenues. "Does this result really make sense?" Market segmentation Follow up your general explanations with your choice of target customer and your planned market success (sales volumes. analog) Buying habits: centralized or decentralized purchasing. you may also want to allow for price erosion. order size Define the potential sales revenues for a given period per segment. • Check for plausibility.g. as long as you are certain that the number of customers in each segment . when a variable is unknown. income. sex. price consciousness Possible customer segmentation criteria for industrial goods markets: Demographics: company size.
Competition Define the strengths and weaknesses of your competitors. . market share. The most important guideline for positioning is. Positioning vis-à-vis the competition Why should a potential customer buy your product and not that of your competitor? Because it offers greater value (in some aspect that is important to the customer) than competing products. you have developed a value proposition or unique selling proposition for your business idea. therefore. customer support. Evaluate your own company according to these same criteria and make a comparison as to how sustainable your competitive advantage will be. target groups. The point is to meet a need better. product lines. The advantage to the customer must be immediately clear. to the longterm success of your business." or. and distribution channels. growth. to look at the product from the customer's point of view. brand. The following guidelines may help: • • • • • • Identify relevant customer needs or problems Define clear customer segments of sufficient size Design an attractive range of products and services Make yourself unique through differentiation from the competition Address the subjective perception of the customer Ensure customer satisfaction even after purchase Because positioning is so critical to the market success and. Formulating this value proposition and anchoring it firmly in the mind of the customer is the main task of marketing communication. or business. and important. In the interest of brevity. Only then can customers connect the value proposition that you offer with the name of your product or business and buy your product. therefore. evaluate your major potential competitors using the same criteria. Marketing experts talk about the positioning of a product. your positioning must be distinctive from that of competitors. cost positioning. At the same time. as marketing experts would say. Well-positioned products leave consumers with a particular impression. it will be a result of intense effort and will need frequent revision to achieve the maximum effect. Additional insight will be found as you refine and modify your product during development and respond to new revelations as a result of customer surveys. because it is objectively or emotionally "better. memorable. not to present new product attributes. such as sales volume and revenues (pricing). To do this. forgo the use of a great deal of detail. you should pay particular attention to it. Persuasive positioning will not come about immediately. The point of departure for positioning is the product itself.
Who are your target customer groups? now and in the future (rough estimates)? What customer examples can you give? What major competitors offer similar products/services? What new developments can be expected from competitors? How sustainable will your competitive edge be? What market volume (value and amount) do you estimate for your individual market segments over the next 5 years? What will influence growth in the market segments? .KEY QUESTIONS: Market and competition How is the industry developing? What factors are decisive for success in your industry? What role do innovation and technological advances play? How will you segment the market? What market volumes do the individual market segments have.
consulting. What is your estimate of current and future profitability of the individual market segments? What market shares do you hold in each market segment? What segments are you targeting? Who are your reference customers? reference customers? What role do service. cont.KEY QUESTIONS: Market and competition. and retail sales play? How much do you depend on large customers? What are the key buying factors for customers? How does the competition operate? What strategies are pursued? What are the barriers to market entry and how can they be overcome? What market share does your competition have in the various market segments? What target groups do your competitors address? How profitable are your competitors? What are your competitors marketing strategies? What distribution channels do your competitors use? How sustainable will your competitive edge be? Why? How will competitors react to your market launch? respond to this reaction? Compare the strengths and weaknesses of your major competitors with your own in the form of an overview! How will you How do you plan to get . maintenance.
After a closer analysis of the needs of various customer segments. A. marketing. • Higher prices generally lead to higher profit margins and allow the new company to finance its own growth. In this case. and perhaps quantified. place. the customer value in the business concept or product description. do you want to generate the highest possible return from the out-set (skimming strategy)? New companies generally pursue the skimming strategy for good reason: • A new product is positioned as "better" than previous options. Marketing and sales "Marketing is far too important to be left to the marketing department. New investments can be financed out of profits and outside investors are no longer needed. The pricing strategy you choose depends on your goal: Do you want to penetrate the market quickly by going with a low price (penetration strategy)? Or. never to go into the business in the first place. and the measures planned for sales promotion. so a higher price can be justified. They require a persuasive description of your strategies for market launch. You have defined. The price you can ask depends entirely on how much the value of your product is worth to the customer. cost is a considerable factor. A skeleton framework to follow is that of the four "Ps": product. B. better yet. you now must evaluate whether your product actually meets them or to what extent it may require adaptation. Of course. This raises the question of whether you should manufacture one single product for all segments or whether you want to adjust the product to meet the needs of individual segments. Now define a price bracket based on the quantified customer value of your product. Entrepreneur Key elements of a well-conceived business concept are well-planned marketing and sales activities. This contradicts the conventional wisdom that price is derived from costs. Product Your original product idea has already given you some sense of the characteristics of your product. You can verify and refine your assumptions through discussions with potential customers.5." David Packard. . but the cost-price ratio only becomes critical when the price asked will not cover costs within the foreseeable future. price. it is advisable to get out of the business as quickly as possible or. and promotion. Price The basis for an attainable price is the willingness of customers to pay the price asked of them.
are the same whether they deliver thousands or many millions of letters. have greatly expanded the spectrum of distribution channels over the past few years. such as how many potential customers will you have? Are they companies or individuals? How do they prefer to shop? Does the product require explanation? Is it in an upper or lower price bracket? Basically. Fixed costs at Federal Express. or whether a specialized operation will handle it for you. a penetration strategy is the best way to be faster than the competition in capturing a large market share. Here is a selection: . Certain situations make following a penetration strategy the better choice: • Setting a new standard. With the Macintosh. you will have to consider whether your company will handle distribution itself. Such cases naturally also raise the question as to whether this type of business is appropriate for a start-up. however. • High fixed costs. it involves another monumental marketing decision: In what way. Distribution can be roughly categorized into two forms: direct or multi-channel. the penetration strategy generally requires high initial investment in order for supply to meet the high demand. in turn. affect other measures. Although this may sound simple. particularly in information technology. for air transport and sorting facilities. Apple followed a skimming strategy and missed the chance to establish the Mac as the new standard. C. The choice of distribution channel is thus closely related to other marketing decisions and will. do you want to deliver your product? The choice of distribution channel is influenced by various factors. Businesses with high fixed costs are forced to find a wide audience as quickly as possible to make those costs worthwhile. Netscape distributed its Internet browser free of charge.• Unlike the skimming strategy. This heightened investment risk is something investors usually prefer to avoid. Place Your product or service will somehow have to reach the customer physically. thus setting a standard. • Competition. This sort of "make-or-buy" decision will have a significant impact on both the organization and the business system of your enterprise. Technological developments. via which distribution channel. for example. If the entry barriers are low and tough competition is likely.
are not always easy to find. Outside agents are relatively expensive. although only for the sales they conclude successfully. • Franchising. They take over the function of the in-house sales person.. however. and only a small number of stores is necessary to cover the market. Specialized companies act as agents for the distribution of products from various manufacturers. On the other hand. Products are sold via retailers who have easy access to potential customers. which is obviously also sought by the competition and is accordingly expensive. making them an attractive channel for new companies since risk is limited. while ensuring control of the sales concept without huge personal investment. but will also allow the greatest control over distribution. Good agents. • Outside agents. requiring extensive knowledge of the product. capital goods). it is important to acquire a good shelf position. • Own sales staff. Sales agents are above all deployed when the product is complex (e. Face-to-face customer visits are expensive. Selling in your own store is a good choice when the design of the purchasing experience is central to the product. Addresses can be purchased from database companies and sorted according to desired criteria. Having your own sales staff as the distribution channel is relatively expensive and only worthwhile for involved products. The success of . It can be difficult for a small company to maintain contact with a large number of retailers. Select customers receive a mailing through the postal service. • Direct mail. • Wholesalers. whereby the franchiser maintains control of the business policies (McDonald's is an example). the number of customers must be fairly small. Here. • Stores. Franchising enables rapid geographic growth. A business concept is put into practice independently by a franchisee that pays a licensing fee. The product must also offer retailers an attractive profit if they are to include it in their range at all. They make no commission if they do not sell the product.• Third-party retailers. Independent shops will require investment. A wholesaler who has good contacts to the retail trade can take over this activity. wholesalers often demand a cut for their efforts.g. helping to improve market penetration while lowering distribution costs.
as well as convince customers that your product meets their needs better than competing or alternative solutions. Promotion Before potential customers can appreciate your product. radio. • Call center. trade fairs • Customer visits Communication is expensive. customers are invited to order a product by telephone. Through advertising. so make the most of it. magazines. movie theaters • Direct marketing: direct mail to select customers. The Internet is a relatively new marketing channel. Internet • Public relations: articles in print media about your product. Calculate exactly how much advertising you can afford per sale and choose your communication messages and media accordingly. with no need to set up stores throughout the entire sales region. Communication must explain the value of your product or service to your customers. . you must advertise to attract attention. D. trade journals. written by you or a journalist • Exhibitions. they have to hear about it. telephone marketing. And to achieve this. business or you. Focused communication yields the best results. focus on the people who make the purchasing decision or have the greatest influence on the purchasing decision. • Internet. Those are the objectives of communication. it lands in the wastebasket. persuade.the direct mailing depends on whether the reader feels an immediate appeal – otherwise. through which a global market can be reached at minimal cost. and inspire confidence. You can also hire the services of specialized call center operators. TV. Simple products can be distributed to many customers in this way. inform. When you address your customers. There are various ways of getting the customer's attention: • Classic advertising: newspapers.
among your buyers. ultimately makes the purchasing decision? What target groups will you reach by what means of distribution? Do you want to penetrate the market quickly with a low price.KEY QUESTIONS: Marketing and sales What final sale price do you want to charge (estimated)? the profit margin (estimated)? What sales volumes and sales revenues are you aiming for (estimated)? In which partial market segments will you make your market entry? How do you plan to turn this “toehold” into a high-volume business? What sales volumes are you targeting (detailed data by market segment)? Describe the typical process of selling your product/service. Who. or bring in the highest return from the start? Explain your decision! What criteria did you use to arrive at this final sale price? How high is .
cont. maintenance. and outfitting) must the operation meet in order to effectively implement its marketing strategy? area? How will sales volume and operating results be spread out among the various distribution channels (estimated)? Which market share per distribution channel do you plan to capture? What are your expenses—at launch and later? What price will you charge for your product/service per target group and distribution channel? What payment policies will you lay down? What is your estimated expenditure for this . qualifications. in time and resources.KEY QUESTIONS: Marketing and sales. How will you draw the attention of your target groups to your product or service? How will you attract reference customers? How much. and hotlines play? How difficult will it be and/or what will it cost to create long-lasting customer loyalty? What other planning steps are necessary in the run-up to launching your product/service? Draw up a schedule with the most important milestones! What demands (employee number. will it cost to acquire a customer? What advertising materials will you use to do so? What part do service.
The business system of a computer manufacturer will be very different from that of a fast food chain. and retail sales. For clarity's sake. component manufacture. A generic business system common to nearly all industries and enterprises is shown in Exhibit 10. Together with your management team. When they are presented systematically in relation to one another. think them through systematically. There are no general rules or standards for a business system. You may also need to separate sales into logistics. raw materials processing. complete. of course. think carefully about what activities really create something new and how you and your staff can best make use of your time . A team of three to five will not be able to cover all tasks themselves. And the business system of a department store may look quite different from that of a direct merchandising company although both will sell many of the same products. For a manufacturer." Ted Levitt. wholesale distribution. Business system and organization "Organizations exist to enable ordinary people to do extraordinary things. the business itself. depending on the industry in which you operate and. for example. The business system model maps out the activities necessary to prepare and deliver a final product to a customer. such as purchasing. You will need to adapt it to your own situation and make it concrete in order to put it into practice. for example. and display them with transparency. they are grouped into functional blocks. Editor. it may be useful to subdivide the production category into separate stages. G EC SE S T E RB I S Y E NI U NS S M Reca e ah d sr n d epe el m vo n t Pd t n r ui oc o Me g a t r i kn Ss a l e Sve ei rc Ei i xb ht 1 0 Use the above model as the starting point for designing your own business system. a business system results. An individual plan will be appropriate to each case. and useful for planning – just don't let it get too complicated. Concentrate on the major activities in your business system. Devising a business system is a good way to understand the business activities of a company. either because they do not have the abilities or because they could not do so with the necessary efficiency. and assembly. Your own system should be logical. Harvard Business Review Business system Every entrepreneurial assignment is comprised of the interplay of a number of individual activities.6.
I v n r ne t M . Decide who is responsible for what in each business area (delegation of tasks and responsibilities). Your organization must be flexible and always adaptable to new circumstances.such as a management. s Ot r r oia a M .P R A I T Z O Mn g gDe to a a in ir c r M . It is essential that tasks and responsibilities are clearly delegated and that you design a simple organization with few levels.you'll be up and running. Once you have determined which activities make up your business system. Fc r a it M. you will need to consider several other organizational issues. (See Exhibit 11) S ML S A TU O G N AI N A P E T R. Specialization is particularly important for start-ups. human resources. They should concentrate all their energy on just a few select activities in the business system. You may have to make this move fairly quickly. If you keep your organization simple. Pc n r eu ia Eh it x ib 1 1 Business location Describe briefly the choice of location for your business. Do not enter into a longterm rental agreement. even software giant Microsoft concentrated solely on the development of the DOS. as your business may have to move in response to the growth you anticipate. At the beginning. The rest will follow as needed during operation. The buzzword here is focus. choose those that you can execute better than anyone else. Be prepared to reorganize your company repeatedly during the first few years.to create the highest value for your customer and get ahead of the competition. A trend toward specialization can be observed in many industries. Dx r u Rs ac a d ee r h n Dv lo mn ee p e t P d cio r ut n o Mr ein ak t g F ac in n e Hmn ua Rs uc sa d eo r e n Am isr t n d in t aio M . On the other hand. Dx r u M . finance. and administration . staff members will know which assignments he or she must complete and can carry them out independently. Organization In addition to a business system. . leaving all other activities in the business system up to IBM. As soon as you have set up the interdisciplinary functions . everyone should be in a position to fill in for another team member for a short time if necessary.
Furthermore. Those aspects of performance that make a major contribution to your competitive advantage are of strategic importance to your business. Often. Your team must. Casual partnerships are typical for mass products. consider whether in specific instances it is best to carry out a particular task. you may find a business partner who is willing to acquire the necessary skills to do so. and some partners cannot easily be replaced if. therefore. or whether it would be better to hand over the task to a specialized company. The question for a start-up is how you want to cooperate with other companies. suppliers will not be able to meet all the special needs of a customer since they cannot sell tailored products to all their customers. you need to find out whether the product or service is available in the form or with the specifications you require. cannot be dissolved from one day to the next. You will usually find the best terms in this way and will learn more about the service you are buying. whenever possible. for example. For each activity. Both parties can end the partnership quickly and easily. rely on the following criteria: • Strategic significance. Activities outside your chosen focus should be handled by third parties. for some reason. Specialists may not only be able to carry out the assignment better. When considering make-or-buy decisions. or have someone else do it—to make or to buy? Make-or-buy decisions need to be conscious decisions taken after weighing the advantages and disadvantages. you can help a supplier improve its performance. These may include bookkeeping or human resources. But they must also live with the knowledge that supply or demand could dry up just as quickly. the question to ask is: Do we do it ourselves. Before you make a decision to buy. acquiring the necessary abilities. . every-day services. • Informal. If you cannot find someone to supply what you need. and a consumer goods manufacturer would never give away its marketing activities. they may also be able to offer a cost advantage thanks to higher production volumes. Supplier partnerships. • Availability. But supporting activities within the new company do not necessarily have to be carried out by you. Negotiate."Make or buy" and partnership decisions Once you have determined the core of your business and have drawn up the necessary business system. Every partnership has its advantages and disadvantages. • Suitability. they are no longer available. non-binding partnerships represent no great obligation for either side. A technology company could hardly relinquish research and development. They must remain under your control. you will have to think about who will best carry out the individual activities. Every business activity demands specific abilities that may not be available within the management team. with several suppliers. and standardized components for which replacement buyers and sellers are easily found.
fire. etc. Such risks and possible financial consequences must be thought through from the outset and perhaps regulated by contract. As in interpersonal relationships. In these situations. They are typical of highly specialized products and services or high trade volumes. it is not too early to begin thinking about whom you may want to cooperate with and what form this may take. Partnerships will allow a young company to benefit from the strengths of established companies and focus on developing their own strengths. Partnerships involve risks that are usually brushed aside when business is going well. Both sides must be able to gain a fair advantage from the relationship. for example. it is usually difficult for both sides to change partners or to buy or sell large quantities of special parts within a short time period. a partnership cannot be sustained. Without an incentive for both sides. Make sure to lay down in detail under which conditions a partner can withdraw from a partnership. The advantage for both sides is the security of a binding relationship and the possibility of concentrating on one's own strengths. a buyer can face difficulties if a major supplier ceases to deliver (bankruptcy. end up in a difficult situation if the buyer suddenly cuts back production and purchases fewer components. strike. a number of factors must be considered: • Win-win situation. • Dissolution. • Risks and investments. business relations can also suffer tension and result in irreconcilable differences. This is especially true if the supplier has acquired specialized production tooling that cannot immediately be used for other orders and buyers. In order for a partnership to develop into a successful business relationship.• Close partnerships are sometimes characterized by a high degree of interdependence. Conversely. When working on your business plan. A supplier with an exclusivity agreement can. Through partnerships. KEY QUESTIONS: Business system and organization . you can usually grow faster than you could on your own. while benefiting from the strengths of partners.).
what will you buy? Which partners will you work with? What are the advantages of Where will you locate your business? What capacity for product manufacture and service production How much will production and delivery of your product/service How. What will you make. What does the business system for your product/service look What activities do you want to handle yourself? Where will the focus of your own activities lie? What business functions make up your organization. how will you organize your inventory? How much of your product has to be put in storage? How are your costs structured (fixed. can you adjust your capacity in the short What measures are planned for quality assurance? If you need a warehouse. Implementation schedule . and how is What resources do you need (quantitative and qualitative) to How high is your need for technical input (raw materials. variable)? like? it structured? create your product/service? materials to create your service)? working together for you and your partners? do you plan (number of units)? cost? term? 7. and at what cost.
Professor Investors want to know how you envision the development of your business. Additionally. The following three elements will usually suffice: • Gantt implementation schedule (see example in Sample Business Plan – a downloadable document from the GLVQ website. Maintaining a simply structured working environment will help you draw up clear job descriptions and seek just the right employees. Usually. and age. Growth will require you to recruit new employees who will have to be trained and integrated into the business. and the total amount of annual writeoffs listed in the planned income statement. Moreover. above all. property is written off in full over 4 to 10 years in equal annual amounts (straight-line method). systematic personnel planning will become more and more indispensable. such as the industry itself. Drawing up your implementation schedule Concentrate on the most major milestones and the most important interdependent events. A realistic 5-year plan will inspire credibility among investors and business partners." William A."Business is like chess: To be successful. you must anticipate several moves in advance. indirect labor costs can amount to over 50% of the wage.) • Major milestones • Important connections and interdependencies between the work assignment groupings Human resources planning As your new business takes off. The amount of depreciation depends on the service life planned for the property. Keep in mind that a qualified. it will help you think through your various activities and interdependencies. You will often not be able to avoid "stealing" good employees from competitors. specialized workforce may be difficult to find even in times of high unemployment. The cost of personnel depends on a number of factors. Include costs in your personnel planning in order to arrive at the total cost of human resources (wages and indirect labor costs) for the income statement in your business plan. Investments are to be included in the liquidity calculation. KEY QUESTIONS: Implementation schedule . employee qualifications. overly optimistic planning. Investment and depreciation planning Investment and depreciation planning includes all investments that may be capitalized and the corresponding write-offs. You will endanger your business if you attempt to reach your targets with faulty and. Sahlmann.
and when must they be reached? your How do you plan to structure the work to reach these targets? Which tasks and milestones are interdependent? For which tasks/milestones do you anticipate bottlenecks? How many new employees will you need in the individual over the next 5 years? What will this cost? How much real capital is necessary to achieve initial sales? List your planned short-term investments! List your planned longer-term (3 to 5 years) investments! What investments will be required when which milestones are How high is the annual depreciation for each investment? business areas reached? 8. Opportunities and risks . What are the most important milestones for the development of business.
Sahlmann. These calculations will allow venture capitalists to judge how realistic your plans are. Change various parameters in the scenarios (such as price or sales volumes) to simulate how a change in conditions might affect your key figures (sensitivity analysis). technology) does your business venture face? What measures will you take to counter these risks? What extraordinary opportunities/business possibilities do you see for your company? How could an expansion of your capital base help? What will your planning look like for the next 5 financial years under both a best and worst case scenario? What effect will this have on your need for capital and your return? In your view."One of the greatest myths about entrepreneurs is that they are all risk seekers. and to better assess the risk of their investment. All sane people want to avoid risk " William A. competition. KEY QUESTIONS: Opportunities and risks What basic risks (market. Professor The object of this exercise is to identify a margin of error for departures from your assumptions. how realistic are these scenarios? What consequences do they have on your business planning? . it is advisable to draw up best-case and worst-case scenarios involving key parameters to identify the opportunities and risks. If possible with reasonable effort.
which also provides information on your various financing needs. To this end.9. These are revealed through liquidity planning. This statement is also necessary according to commercial and tax law. an income statement focuses on the issue of whether transactions lead to an increase (= revenue) or a decrease (= expense) in the net worth of your business (defined as the sum of all assets minus debt)." Unknown Financial planning assists you in evaluating whether your business concept will be profitable and can be financed. Do not forget to cover the cost of your personal living expenses. income statement. Financial planning and financing "Planning substitutes chaos for mistakes. Minimum required financial planning in your business plan: A cash flow calculation (liquidity planning). if so. the profit situation of your business can be seen in the income statement. There are many ways to present the figures. that is. The appendix contains sample tables of how to perform liquidity planning and make up an income statement. beyond the generation of positive cash flow quarterly). If you are in doubt about the exact amount of costs your business will incur. the results of all preceding chapters must be compiled and consolidated. Projected growth in value results from the planned cash flows from your operative business. thereafter annually main assumptions need to be described in the plan) Planned income statement Whether a company's assets grow or diminish depends on the bottom line at the end of a year. Go through your entire business plan and decide whether your assumptions will lead to revenues or expenses and. gather quotes and estimates. In addition. how high they will be. Forecasts over 3 to 5 years. The income statement can help you forecast this. In contrast to liquidity planning (= planned cash flow). In the . as well as a balance sheet. at least 1 year beyond the point of Detailed financial planning for the first 2 years (monthly or All figures must be based on reasonable assumptions (only the balance sheet breaking even.
calculate the difference between all revenue and expenses in a financial year. because the amount paid out does not lead to a change in the net worth of the business. and purchased goods and services. For the third. expendable supplies. auxiliaries. For the purpose of simplification. advertising. continue to make annual projections. and fifth years. by which you will arrive at an annual net profit/loss. To enhance the accuracy of your planning for the first year. rent. List write-offs in your investment and depreciation planning. liquidity planning involves only those transactions that cause a change in your cash reserves. among other things. Sales of your product or service may be booked in the current financial year. strictly observe legal regulations. liabilities. but it will not give you a reliable assessment of your level of liquid funds. The income statement is generally planned in annual intervals. which leads to bankruptcy that will mean the financial ruin of your business. fourth. This will give you an overview of the operating result. Material costs comprise all expenses for raw materials. Liquidity planning Your company must have a certain amount of cash on hand at any given time in order to avoid becoming insolvent. When assigning individual revenues and expenses. . insurance. even though payment does not occur until the next. and non-market output are not included. you should make monthly forecasts. Your company is solvent when the sum of its receipts is greater than the sum of its disbursements at any given time. Liquidity planning is concerned with the date of payment when the money actually comes in or goes out. The cost of investments themselves (i. including. the purchase price of the investment) is not included in the income statement. office supplies. this would be the salary of your general manager. Thus. Lay out the amount and timing of all the payments you expect. Your planned human resources expenditure includes wages and salaries plus social security contributions and taxes and is listed under personnel costs. and quarterly forecasts for the second year. Finally. you will need to list the sales revenue even though the money has not yet been deposited into your accounts. Detailed liquidity planning should help ensure a positive cash flow. You will have to draw on capital for those times when this planning does not cover all expenses.. postage.case of a limited liability company. The same is true for expenses. For this. and legal counsel.e. the category "other costs" is treated as a collective item. The principle is simple: Receipts are compared directly to disbursements. you will need liquidity planning. Depreciation. The sum of all these individual payments will equal the total capital required for that planning interval. Please note that writing or receiving an invoice does not mean that the money is already in your account or that you have paid the bill.
All the management team can offer investors for their cash is a promise – not exactly a good position from which to negotiate. As with the income statement. there is a standard accounting format. Nevertheless. Financing needs Liquidity planning enables you to determine the amount of capital you will need and when you will need it. Your family may ask little in return for financial assistance." the saying goes . . you have a good chance of being financially successful if business goes well.and the same is true of money. SO R E O C PITA A VA IO S S G S O DE LO M NT U C S F A L T R U TA E F VE P E Seed phase P ersonal sa vings Fam loans ily G overnm grants ent Individuals (“business an gels”) V enture capital M ortgages L eases B ank loans S tock exchange Start-up G row th Establishm ent Exhibit 12 "You can't get something for nothing. fourth and fifth years. Select the right mix for your business from the myriad sources of financing available to you (Exhibit 12). Projected balance sheet Venture capitalists are interested in seeing how your assets are expected to grow as represented on a projected balance sheet. required by law. the type and value of the assets are placed on the asset side of the balance sheet across from the source of the capital on the liabilities side. Liquidity planning should thus be carried out every month for the first year. Here. quarterly for the second year and only annually for the third. but it does not indicate how these needs will be met.The farther you look into the future. the more uncertain your planning will be. They are prepared at annual intervals. for balance sheets. because professional investors also have an interest in top performance from the team. We basically distinguish between equity (investors have a stake in the business) and loan capital (which is borrowed from outside sources). professional lenders are more demanding. Be clear about your needs and expectations and those of your investors.
if the IRR is 72%. As a result. all funds contributed to a new company result first in negative cash flows. results in zero. Calculating the investor's return Investors evaluate the success of an investment by the return they get on the capital invested. and contacts. discounted at present. that you understand all the details of the deal. Professional investors. the internal rate of return (IRR) method is used. you desire rapid expansion. are not interested in managing the business as long as you meet your targets. control of the funds invested. From the point of view of the investor. This is a reasonable return considering the risk involved. positive cash flows will not immediately be paid out in the shape of dividends. They have. It can also be calculated by hand. however. you will want to procure venture capital. they must be discounted. anticipated return should be apparent at a glance in the business plan. you are probably well advised to make use of family funds and loans from friends and banks. after all. that means that the investors get an annual return of 72% on their capital. in fact. Because cash flows will occur over several years. For example. have to relinquish the majority of the equity. such as legal or marketing expertise. even if they have the majority shareholding. To calculate the return. There are usually legitimate reasons for them. They will support you actively with their management skills and contribute specialty knowledge. ties. You may also want to gather a number of bids from various investors. etc. The IRR is the discount rate at which the sum of all positive and negative cash flows. but will be first used to strengthen the balance sheet. If. Venture capitalists will generally expect to obtain a large share of the company. and lawyers. You will retain a majority shareholding. After a business breaks even. It is always advisable to contact experienced entrepreneurs and get the expert advice of trustees. A deal can be very complicated. Most calculators and spreadsheets have a special IRR function with which to calculate the IRR (in Excel this is the IRR () function). . Cash will be returned to the investors at realization. The discount factors for the various years can be arrived at using the following formula discount factor= 1 (1+r)T whereby r = the discount rate in percent and T = the year in which the cash flow takes place. however. such as tax breaks. that is. invested in the management team in order to lead it to success. Be absolutely certain. Do not be put off by complicated arrangements. calculated back to the present (interest and compound interest calculation). tax advisors. however.If you are seeking a long-term commitment and are satisfied with a small company. but you are significantly restricting your chances for growth. You may.
g. with a tax advisor. tax consultants or accountants) is highly recommended.. and income develop? How will your cash flow develop? When will you expect to break even (= sum of all revenues greater than the sum of all expenses)? How high is your need for financing based on your liquidity planning? How much cash is needed in the worst case scenario? What assumptions underlie your financial planning? Which sources of capital are available to you to cover your financing needs? What deal are you offering potential investors? What return can investors expect? How will they realize a profit (exit options)? .. If you have no experience in financial planning. consulting with coaches or experts (e. Note that most business ventures fail due to lack of financial planning. start looking! KEY QUESTIONS: Financial planning and financing How will your revenues. discuss the issues of turnover sales and income taxes. In particular. which have been simplified here.e. A simple rule of thumb is that the value is six to eight times the cash flow or net profit (after taxes) of the business in the year of initial public offering. expenses. If you don't have someone with the necessary skills on your team already.Valuation of a company (i. working out how much a market is prepared to pay for shares when a business goes public) is an art in itself.
or advertisements and articles. Take care that the appendix is kept manageable and does not include excessive data.10. important ancillary calculations. . management resumes. such as organization charts.6. Business plan appendix You should use the appendix to your business plan for supplementary information. patents. | https://www.scribd.com/document/66804319/Business-Plan-Stucture | CC-MAIN-2019-04 | refinedweb | 9,181 | 60.11 |
Would there be a way to write something that states if there is something with DWELL populate with House, but if it is NULL populate with Mobile home but if it is something else populate it with what is on the Points_2 CPUC field?
Here is my current working code.
Here is my current working code.
import arcpy, time arcpy.env.overwriteOutput = True arcpy.env.workspace = r"C:\Temp\Defult.gdb" fcTarget = 'Points_1' fcJoin = 'Points_2' rowR.CPUC == 'DWELL': rowW.FacltyType = 'Single Family Home' rowW.APA_CODE = '1110' rowW.StructType = 'Primary, Private' rowW.Verified = 'Yes, GRM, TA, ' + time.strftime('%m-%d-%Y') rowW.Status = 'Active' rowW.StructCat = 'Residential' else: rowW.FacltyType = 'MobileHome' rowW.APA_CODE = '1150' # put any additional conditional field statements here # put any 'global' field statements here (applies to both SF/MH) curW.updateRow(rowW) rowR = curR.next() # changed the delete statement, targeting the cursor objs (rather than the row objs) if curW: del curW if curR: del curR
See this:
....don't know if you got this yet, but if you locate this part of your current code:
Replace that part with this part below --- think that'll work (better test it, because I didn't): | https://community.esri.com/thread/84952-udatecursor-help | CC-MAIN-2018-22 | refinedweb | 196 | 70.5 |
Using finally Blocks
Using finally blocks, you can provide a code that will always execute even if exceptions are thrown. We learned that if an exception was thrown inside a try block, all the following codes in the try block will be skipped because the execution will immediately jump to the catch block. Those skipped codes could have a vital role in the program. That’s the purpose of the finally block. You place the codes that you think is essential or needs to be executed inside the finally block. The following program shows an example of using a finally block.
using System; namespace FinallyBlockDemo { public class Program { public static void Main() { int result; int x = 5; int y = 0; try { result = x / y; } catch (DivideByZeroException error) { Console.WriteLine(error.Message); } finally { Console.WriteLine("finally blocked was reached."); } } } }
Example 1 – Using the finally Block
Attempted to divide by zero. finally blocked was reached.
The finally block comes right after catch block. If there are multiple catch blocks, the finally block must be placed after them. Note that if you will use a finally block, you are allowed to not define a catch block such as the following:
try { //some code } finally { //some code }
finally blocks are often used when you want to dispose of an object or close a database connection or file stream. | https://compitionpoint.com/finally-block/ | CC-MAIN-2021-21 | refinedweb | 224 | 64.1 |
A string is basically a sequence of characters that can be indexed. In fact, although a string is not declared as a subclass of vector, almost all the vector operators discussed in Chapter 5 can be applied to string values. Indeed, a string qualifies as a sequence container type. However, a string is also a much more abstract quantity. In addition to simple vector operators, the string datatype provides a number of useful and powerful high level operations.<!>
In the C++ Standard Library, a string is actually a template class, named basic_string. The template argument represents the type of character that will be held by the string container. By defining strings in this fashion, the C++ Standard Library not only provides facilities for manipulating sequences of 8-bit characters, but also for manipulating other types of character-like sequences, such as 16-bit wide characters. The datatypes string and wstring (for wide string) are simply typedefs of basic_string, defined as follows:
typedef std::basic_string<char, std::char_traits<char>, std::allocator<char> > std::string; typedef std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> > std::wstring;
NOTE -- In the remainder of this chapter, we refer to the string datatype, but all the operations we introduce are equally applicable to wide strings.
As we have already noted, a string is similar in many ways to a vector of characters. Like the vector datatype, a string is associated with two sizes. The first represents the number of characters currently being stored in the string; the second is the capacity, the maximum number of characters that can potentially be stored in a string without reallocation of a new internal buffer.
As in the vector datatype, the capacity of a string is a dynamic quantity. When string operations cause the number of characters being stored in a string value to exceed the capacity of the string, a new internal buffer is allocated and initialized with the string values, and the capacity of the string is increased. All this occurs behind the scenes, requiring no interaction with the programmer.
Programs that use strings must include the string header file:
#include <string> | http://stdcxx.apache.org/doc/stdlibug/12-1.html | CC-MAIN-2015-18 | refinedweb | 355 | 50.06 |
Pointers in C Language.
Pointer syntax:.
How to Use a Pointer?.
NULL Pointers in:
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf (“The value of ptr is : %x n”, ptr );
return 0;
}
When the above code is compiled and executed, it produces following result:.
Concepts of pointers:
Pointers have many but easy concepts and they are very important to C programming. There are following few important pointer concepts:
• C – Pointer arithmetic: There are four arithmetic operators that can be used on pointers: ++, –, +, –
• C – Array of pointers: You can define arrays to hold a number of pointers.
• C – Pointer to pointer: Allows you to have pointer on a pointer and so on.
• Passing pointers to functions in C: Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
• Return pointer from functions in C: C allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well..
• Incrementing a Pointer:.
• Decrementing a Pointer: The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type.
• Pointer Comparisons: Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to variables that are related to each other, such as elements of the same array, then p1 and p2 can be meaningfully compared.
Example:
#include< stdio.h >
main ()
{
int ptr1,ptr2;
int a,b,x,y,z;
a=30; b=6;
ptr1=&a;
ptr2=&b;
x=*ptr1+ *ptr2 6;
y=6*- *ptr1/ *ptr2 +30;
printf (“n Address of a +%u”,ptr1);
printf (“n Address of b %u”,ptr2);
printf (“n a=%d, b=%d”, a,b);
printf(“n x=%d ,y=%d”, x,y);
ptr1=ptr1 + 70;
ptr2= ptr2;
printf (“n a=%d, b=%d,” a, b);
}-dimentional++.
C – Pointer to pointer:
A pointer to a pointer is a form of multiple indirections, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value..
Example:
#include<stdio.h>
int func (int a, int b)
{
Printf (“n a = %dn”,a);
printf (“n b = %dn”.
Dynamic memory allocation:..
malloc ()
calloc ()
realloc ()
free (). | http://www.lessons99.com/pointers-in-c-language.html | CC-MAIN-2019-04 | refinedweb | 393 | 62.27 |
I wanted to share with you some recommended best practices that I battle tested over about four or so years working with Metaflow at Netflix. The goals are a short development loop; reusable, maintainable, and reliable code; and just an overall fun and rewarding developer experience. This list is probably not complete but I can add more later.
Minimal directory structure
I’ll start with a suggested minimal directory structure. This example has a training flow and a prediction flow, with common code across the two plus a Jupyter notebook for debugging.
<your-repo> ├── flows | ├── train.py | ├── predict.py | ├── debug.ipynb | └── common.py └── .gitignore
The training and prediction flow specs import common code and do… you know, machine learning. They are separated out to support ongoing predictions on a model that is potentially re-trained on a different schedule. So you might run train.py quarterly, and run predict.py weekly on fresh incoming data.
Note
import common. That brings me to…
Put common code into a separate script
In the minimal code structure and flow example I’ve got a script called common.py. That contains reusable functions, classes, and variables that both train.py and predict.py can use. Pulling your code into a separate script makes it more easily reusable and testable and shortens your Metaflow steps and overall flow spec.
Git-ignore .metaflow
Don’t forget to add
.metaflow to your .gitignore
because those directories contain the local data artifacts.
Debug in a Jupyter notebook
You can debug common code and access Metaflow data artifacts in Jupyter notebooks. Here’s a minimal example of all of that.
I’m using autoreload magic so that I can make changes to common.py
and have those changes immediately reflected at the cell level
without having to re-import common or otherwise run a bunch of other cells.
Your working directory in the notebook should be
<your-repo>/flows/ in this case.
(Note: that debug snippet shows artifacts from my previous Metaflow post.)
Develop a separate Python package
When it makes sense to (and not earlier) I try to separate out the more broadly reusable code into a separate, pip-installable Python package. That’s in addition to using local common.py scripts. You can put the code in the same repo, or break it out into another one. Here’s a minimal example of putting it in the same repo. You’ll see a full working example of this at metaflow-helper.
<your-repo> ├── flows | ├── train.py | ├── predict.py | ├── debug.ipynb | └── common.py ├── .gitignore ├── your_package | ├── __init__.py | └── models.py └── setup.py
Adding the setup.py makes
your_package pip installable.
During development I’ll
fire up a Python venv with
python -m venv venv && . venv/bin/activate
and then install the package in editable mode
with
pip install -e .,
all from the top level of the repo.
In each Metaflow step I’ll pip install from git if the package is not already locally available. Here are the functions that do that, which I put into common.py.
Now at the top of each step you would do something like:
common.install_dependencies( {'your_package': 'git+ssh://git@github.com/<github-username>/<your-repo>.git'} )
This will try to
import your_package (the dictionary key)
and if it fails, pip-install from Github.
Doing this will seem like nonsense during development, but when you
deploy to a production environment this will become necessary.
Installing via pip lets you get athe code from Github or PyPI,
and will let you pin in both cases.
Here are some different ways to pin.
# Install the latest commit from the default branch {'your_package': 'git+ssh://git@github.com/<github-username>/<your-repo>.git'} # Pin by installing a tagged commit {'your_package': 'git+ssh://git@github.com/<github-username>/<your-repo>.git@v0.0.1'} # Pin by installing a commit hash {'your_package': 'git+ssh://git@github.com/<github-username>/<your-repo>.git@00db203'} # Install from PyPI {'your_package': 'your_package'} # Pin by install from a PyPI version {'your_package': 'your_package==0.0.1'} # etc etc
You can call
install_dependencies in your debugging Jupyter notebook, too.
If
your_package is already available to it, nothing will happen.
This means you can test your Metaflow artifacts, common flow code,
and your external package code all in the same notebook.
And speaking of pinning…
Pin your packages
If you plan on running your flows on a cron schedule or against triggers over long periods of time, do yourself a favor and pin your packages. This increases stability of repeated flow runs that use artifacts from other flows that ran earlier. For example, predict.py needs to load the model artifact persisted in train.py, potentially days, weeks, or months later, depending on your design.
It’s useful to think of your Metaflow jobs like you would any long-running application, for instance a web app. Pin for reproducibility and to minimize maintenance over the long term.
You can take this thinking one step further with Metaflow:
think of each Metaflow step as an independent, long-running application
and pin potentially different packages at the top of every step.
One example where I’ve seen this come up is in
using Tensorflow.
Tensorflow requires a specific version range of numpy,
but otherwise I want access to a more recent numpy release elsewhere.
If I isolate my Tensorflow modeling code to a single step or set of steps,
and do pre- and post-processing in separate steps, I can pin Tensorflow with
a floating numpy version and in the other steps I’ll in general get a different numpy version.
The
install_dependencies function pattern I mentioned above
in Develop a separate Python package
will let me do this.
Now that I’ve said all this stuff about pip…
Migrate to conda
The pip-install pattern is useful for shortening the development cycle, but the Metaflow maintainers recommend adopting conda to maximize reproducibility. I don’t have a good recommendation at this time on how to adopt the conda pattern while still keeping the development loop short. My guess is one of pip-installing inside conda-decorated steps or conda-installing from git, might work. I’ll give these a try as soon as I have a need to.
Keep flows and flow steps short
If you pull common code into local Python scripts or into a separate package, you’ll be in a good position to make your flow spec and each of its steps as short as possible.
Keeping them short is useful for readability and maintainability. You’ll also invariably have to do other high-level stuff at the step level without the option of pulling that code into common functions, for example Metaflow step-level exception handling. Do flow-control-level operations in steps and otherwise call just a few functions per step if you can.
Keeping the scope of steps small is also useful for debugging different logical chunks of your pipeline without having to rerun upstream code and for resuming execution after a failed run. Often times in production you’ll get failures due to platform failures, and it’s useful to have completed as much upstream processing successsfully as possible. Then you can resume from the failed steps forward. Or you’ll get a runtime failure from an unhandled edge case. It’s helpful when upstream, smaller scope steps have completed successfully and the runtime failure is isolated to a small step. Small steps make the whole debugging and maintenance experience more enjoyable.
Fail fast in your start step
Your start step is an opportunity to fail fast. This means things like:
- Try to ping your external services.
- Load the pointers for you Metaflow artifact dependencies.
- Validate configuration and variables.
If any of your canary procedures fail, let the flow error out and report back to you. It’s far better to fail in the start step if you can rather than failing toward the end of a potentially very long running flow.
Implement a test mode
Implement a test mode that will run your flow as-is but on as small a data set as possible and with hyperparameter settings that make the ML training optimization as quick as possible. I like to do this by creating a flag parameter that I can use to subset the data and reduce parallelism to one concurrent task for any given step. If you’re training a model, reduce the number of maximum possible optimization iterations to something small like 10 epochs. Here’s one way to create a test-mode using a Metaflow Parameter.
Now I can run the flow normally with
python train.py
or in test mode with
python train.py --test_mode 1
I did a variant of this in my model selection example from my previous Metaflow post. Instead of using a boolean flag I point to different configuration files by string, some of which perform the same tasks of subsetting the data down and shortening the model training times dramatically.
Run flows in test mode in a CI/CD pipeline
If you’ve got a nice and short test mode working you can run it as part of continuous integration/continuous delivery & deployment. You’ll see working examples of this in metaflow-helper. I’ve got separate jobs and badges set up for unit testing and for running the Metaflow examples in test mode.
Use an IDE
I prefer PyCharm. It plays nice with Metaflow. Debugging seems to work fine, but it can be a bit tricky to debug parallel tasks in foreach steps. Using test-mode (see Implement a test mode) and eliminating parallel tasks helps. Make sure to reuse your virtual environment interpreter if you set one up already. I’ve also set PyCharm up for Metaflow development against a remote server – that works pretty well, though there are a lot of configuration options to set.
VS Code works as well. It’s faster but has reduced functionality. I especially miss refactoring and fully-featured inspection when I use VS Code. There’s a time and a place for both and as always it boils down to personal preference.
I haven’t tested other IDEs like Spyder. I’d like to hear if others have and what the good and the bad are about each one.
What did I miss?
I didn’t talk about more advanced practices I like, such as Metaflow run tagging and setting up isolated test and development environments that operate without affecting the production environment. I’ll cover those future posts.
I’d like to hear from you on what I may have missed or how you do things differently! | https://www.highonscience.com/blog/2021/05/25/metaflow-best-practices-for-ml/ | CC-MAIN-2021-39 | refinedweb | 1,779 | 65.01 |
On Monday 30 November 2009 14:49:07 Guennadi Liakhovetski wrote: > On Mon, 30 Nov 2009, Hans Verkuil wrote: > > On Thu, 26 Nov 2009, Guennadi Liakhovetski wrote: > > > > From 8b24c617e1ac4d324538a3eec476d48b85c2091f Mon Sep 17 00:00:00 > > > > 2001 > > > > > > From: Guennadi Liakhovetski <g.liakhovet...@gmx.de> > > > Date: Thu, 26 Nov 2009 18:20:45 +0100 > > > Subject: [PATCH] v4l: add a media-bus API for configuring v4l2 subdev > > > pixel and frame formats > > > > > > Video subdevices, like cameras, decoders, connect to video bridges over > > > specialised busses. Data is being transferred over these busses in > > > various formats, which only loosely correspond to fourcc codes, > > > describing how video data is stored in RAM. This is not a one-to-one > > > correspondence, therefore we cannot use fourcc codes to configure > > > subdevice output data formats. This patch > > > adds codes for several such on-the-bus formats and an API, similar to > > > the familiar .s_fmt(), .g_fmt(), .try_fmt(), .enum_fmt() API for > > > configuring those > > > codes. After all users of the old API in struct v4l2_subdev_video_ops > > > are converted, it will be removed. Also add helper routines to support > > > generic pass-through mode for the soc-camera framework. > > > > > > Signed-off-by: Guennadi Liakhovetski <g.liakhovet...@gmx.de> > > > --- > > > > > > v2 -> v3: more comments: > > > > > > 1. moved enum v4l2_mbus_packing, enum v4l2_mbus_order, and struct > > > v4l2_mbus_pixelfmt to soc-camera specific header, renamed them into > > > soc-namespace. > > > > > > 2. commented enum v4l2_mbus_pixelcode and removed unused values. > > > > > > v1 -> v2: addressed comments from Hans, namely: > > > > > > 1. renamed image bus to media bus, now using "mbus" as a shorthand in > > > function and data type names. > > > > > > 2. made media-bus helper functions soc-camera local. > > > > > > 3. moved colorspace from struct v4l2_mbus_pixelfmt to struct > > > v4l2_mbus_framefmt. > > > > > > 4. added documentation for data types and enums. > > > > > > 5. added > > > > > > V4L2_MBUS_FMT_FIXED = 1, > > > > > > format as the first in enum. > > > > > > soc-camera driver port will follow tomorrow. > > > > > > Thanks > > > Guennadi > > > > > > > > > drivers/media/video/Makefile | 2 +- > > > drivers/media/video/soc_mediabus.c | 157 > > > ++++++++++++++++++++++++++++++++++++ > > > include/media/soc_mediabus.h | 84 +++++++++++++++++++ > > > include/media/v4l2-mediabus.h | 59 ++++++++++++++ > > > include/media/v4l2-subdev.h | 19 ++++- > > > > <cut> > > > > > diff --git a/include/media/v4l2-mediabus.h > > > b/include/media/v4l2-mediabus.h new file mode 100644 > > > index 0000000..359840c > > > --- /dev/null > > > +++ b/include/media/v4l2-mediabus.h > > > @@ -0,0 +1,59 @@ > > > +/* > > > + * Media Bus API header > > > + * > > > + * Copyright (C) 2009, Guennadi Liakhovetski <g.liakhovet...@gmx.de> > > > + * > > > + * This program is free software; you can redistribute it and/or > > > modify + * it under the terms of the GNU General Public License version > > > 2 as + * published by the Free Software Foundation. > > > + */ > > > + > > > +#ifndef V4L2_MEDIABUS_H > > > +#define V4L2_MEDIABUS + * should be stored in RAM, and "PADHI" and "PADLO" define > > > which bits - low or > > > + * high, in the incomplete high byte, are filled with padding bits. > > > + */ > > > > Hi Guennadi, > > > > This still needs some improvement. There are two things that need to be > > changed here: > > > > 1) add the width of the data bus to the format name: so > > V4L2_MBUS_FMT_YUYV becomes _FMT_YUYV_8. This is required since I know > > several video receivers that can be programmed to use one of several data > > widths (8, 10, 12 bits per color component). Perhaps _1X8 is even better > > since that is nicely consistent with the 2X8 suffix that you already use. > > The PADHI and PADLO naming convention > > is fine and should be used whereever it is neeeded. Ditto for BE and LE. > > Ok, my first thought was "no, there only very seldom will be a need for a > different padding / order / bus-width," but the second thought was "but > if there ever will be one, you'll have to rename the original code too..." > > > 2) Rephrase '"BE" or "LE" specify in which order those samples should be > > stored > > in RAM' to: > > > > '"BE" or "LE" specify in which order those samples are transferred over > > the bus: > > BE means that the most significant bits are transferred first, "LE" means > > that the least significant bits are transferred first.' > > > > This also means that formats like RGB555 need to be renamed to > > RGB555_2X8_PADHI_LE. > > > > I think that this would make this list of pixelcodes unambiguous and > > understandable. > > Right, how about. Regards, Hans > V4L2_MBUS_FMT_Y10_1X, > }; > > > Regards, > > > > Hans > > > > > +enum v4l2_mbus_pixelcode { > > > + V4L2_MBUS_FMT_FIXED = 1, > > > + V4L2_MBUS_FMT_YUYV, > > > + V4L2_MBUS_FMT_YVYU, > > > + V4L2_MBUS_FMT_UYVY, > > > + V4L2_MBUS_FMT_VYUY, > > > + V4L2_MBUS_FMT_RGB555, > > > + V4L2_MBUS_FMT_RGB555X, > > > + V4L2_MBUS_FMT_RGB565, > > > + V4L2_MBUS_FMT_RGB565X, > > > + V4L2_MBUS_FMT_SBGGR8, > > > + V4L2_MBUS_FMT_SBGGR10, > > > + V4L2_MBUS_FMT_GREY, > > > + V4L2_MBUS_FMT_Y, > > > +}; > > Thanks > Guennadi > --- > Guennadi Liakhovetski > -- > | https://www.mail-archive.com/linux-media@vger.kernel.org/msg12662.html | CC-MAIN-2021-31 | refinedweb | 675 | 56.45 |
I'm using EF Core 2.2 with ASP.net MVC Core 2.2.
I have an entity with a List array that is not being stored to the table. I thought that it would write out a list of foreign keys to the objects in the array, but that's not happening. What am I forgetting?
public class ProjectModel { [Key] public int ID { get; set; } public List<MyObject> ListOfObjects { get; set; } } public class MyObject { [Key] public int ID { get; set; } [Required] public string Name{ get; set; } }
Code where add and save is occurring:
MyObject cm = MethodToGenerateObject(); if(pm.ListOfObjects == null) { pm.ListOfObjects = new List<MyObject>(); } pm.ListOfObjects.Add(cm); _context.Entry(pm).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; }
But no MyObject data is saved to the database. Why?
Thanks to @Sam, I searched for navigation properties and found this helpful guide:
the first one to many relationship example helped solve my problem. | https://entityframeworkcore.com/knowledge-base/54698038/list-myobject--not-being-saved-in-ef-core-2 | CC-MAIN-2020-40 | refinedweb | 157 | 51.24 |
This is a technical overview of the XML feautes in Oracle Text (the product formerly known as interMedia Text) version 9.0.1. This is intended for an audience fairly familiar with previous versions of the product.
Every new version of Oracle Text/interMedia Text/ConText Option has added new structured document searching features, so we've built up a lot of functionality -- 8.1.7 has nested section search, doctype disambiguation, attribute value searching, automatic section indexing, and more. But with the industry embracing XML, demand is growing for even more sophisticated features which are beyond the capabilities of the current section architecture.
9.0.1 introduces a new section type and new query operators which support an XPath-like query language. ConText indexes with XML path searching are able to perform sophisticated section searches that were impossible in previous versions.
In order to use XML path searching, the index must be created with the new path section group:
exec ctx_ddl.create_section_group('mypathgroup','PATH_SECTION_GROUP');
create index myindex on mytable(doc) indextype is ctxsys.context parameters ('SECTION GROUP mypathgroup');
You can add only
SPECIAL sections to a path section group; you do not have to add
ZONE,
FIELD, or
ATTR sections, and it does not support
STOP sections in this version. Most of the time, you won't even need to create your own -- just use the default one:
create index myindex on mytable(doc) indextype is ctxsys.context parameters ('SECTION GROUP ctxsys.path_section_group');
The path section group is somewhat like the auto section group in that it automatically indexes all tags and attributes it encounters. For query, you can still use
WITHIN, but the path section group also supports the more powerful
INPATH and
HASPATH operators.
Now we'll talk a little about how path sections are indexed, and how they differ from zone and attribute sections. You can skip this section if you're just interested in usage.
We'll illustrate the difference in index data with this simple doc:
<OUTER><INNER ATTR="attrvalue">text</INNER></OUTER>
The auto section group produces the following in $I:
A simple within query like:
select id from mytable where contains(doc, 'text WITHIN inner')>0
can be fulfilled by fetching the info for word
TEXT and section
INNER, then looping through each word offset of
TEXT, and checking to see if it is between
INNER START and
START + LENGTH. A simple attribute query like:
attrvalue WITHIN inner@attr
(we'll just write the text query for brevity) can be fulfilled in much the same way, but using type 4 and 5 tokens instead of types 0 and 2.
This section type cannot support more complex queries. For instance, equal sections like
INNER and
OUTER are a problem. The query:
(text WITHIN outer) WITHIN inner
matches this document. The index data records the same offsets for
INNER and
OUTER, so it is impossible to tell if
INNER is inside
OUTER or vice versa. Another problem is attribute value sensitive section search. For document:
<SHIPMENT> <MEDIA TYPE="dvd">Ice Blue Eyes</MEDIA> <MEDIA TYPE="book">The Monopoly Companion</MEDIA> </SHIPMENTS>
(We won't include the xml declaration and
DOCTYPE stuff -- just pretend that they are there) If you want to find shipments that include the DVD "Ice Blue Eyes", you'd have to include both section and attribute criteria:
find documents where "Ice Blue Eyes" occurs within a "MEDIA" section whose "TYPE" attribute has the value "dvd"
Unfortunately, attribute values and sections (types 4 and 5) are completely separate from normal text and sections (types 0 and 2). There is no way to link an attribute section to the particular zone section occurrence in which it occurs.
The path section group solves both problems by indexing the document like:
Zone sections and attribute sections (types 2 and 5) have been replaced with path sections and path attribute sections (types 7 and 8). Each occurrence of a path section has a
LEVEL bit which indicates the nesting level of the tag. The root tag gets a level of 1, its children get a level of 2, their children get a level of 3, etc. Including level information solves the equal section problem, because we can now tell which tag is the outer tag.
Path attribute sections have a
OCC part which links the attribute section occurrence to a path section occurrence. Here,
INNER@ATTR has an
OCC of 1 because it occurs in the first occurrence of
INNER. The ability to correlate attributes and tags solves the attribute value sensitive section search.
The query interface is through SQL selects, so your XML queries return entire documents, not just selected parts of them. While we work on better extraction features for future release, you can explore using the new
XMLType, which has extraction methods. Just use extraction methods in the select list and contains in the where clause.
The way path sections are indexed enables more complicated section searches, but the
WITHIN operator is not expressive enough to handle them. Instead of
<text query> WITHIN <section name> (e.g. Ice WITHIN MEDIA )
indexes with a path section group use the INPATH operator in queries:
<text query> INPATH(<path expression>) (e.g. Ice INPATH(//MEDIA) )
but it functions in much the same way, limiting the scope of the text query to certain parts of the indexed documents. The parentheses around the path expression are required. The path expression is more than just a simple section name -- it is a mini query, with a specialized query language. The next section explores the path query language in more detail.
You can still use the
WITHIN operator even if you are using the path section group. There should be no difference in behavior between the path section group or auto section group when using
WITHIN queries.
The Text path query language is based on XPath, and we will probably continue to use XPath as a guide for future development, but it is NOT XPath. Not all the XPath operators exist in the Text path query language, for instance. Also, the Text path query language operators are case-insensitive, while XPath's are strictly lower-case. There are other semantic differences covered below. Just don't make assumptions about the path language based on XPath expectations.
When specifying tags in path queries, you must specify it exactly as it appears in the document in order for it to match. There are two commonly-made mistakes you should avoid.
First, tag names are case-sensitive so the query
"title" does not match the tag
<TITLE> or the tag
<Title>. It will match only
<title>.
Second, there is no namespace support in this version. Take the fragments:
DOC 1 <A xmlns:<ORCL:B> DOC 2 <A xmlns:<ORACLE:B>
<ORCL:B> in
DOC 1 is the same tag as
<ORACLE:B> in
DOC 2, because their namespace tags normalize to the same URI. However, when querying for these tags, you must specify it as written in the document, so
"ORCL:B" to find the tag in doc 1, and
"ORACLE:B" to find it in doc 2.
"B" alone will not find either tag, nor will something like
"". Future versions will probably add more sophisticated namespace support.
The simplest
INPATH query string is a single tag:
perro INPATH(TITLE)
Like a
WITHIN query, this query finds
perro where it occurs between
<TITLE> and
</TITLE>. However, unlike a
WITHIN query,
<TITLE> must be the top-level tag. Take these two documents:
DOC 1 <TITLE>Clifford El Gran Perro Colorado</TITLE> DOC 2 <BOOK><TITLE>Años De Perro</TITLE></BOOK>
The query
perro WITHIN TITLE
will find both documents, but the
INPATH query will find only document 1. It does not match document 2 because there the
TITLE tag has a level of 2.
What's really happening is that no level for the query node is specified, so it uses the default context, which is always the top level for
INPATH queries. You can explicitly specify the top level context with slash:
perro INPATH(/TITLE)
or explicitly specify the default context using dot:
perro INPATH(./TITLE)
both are equivalent to the query without the slash. All examples from here will include the top level slash for readability.
A double slash indicates "any number of levels down". So, the query:
perro INPATH(//TITLE)
is looking for
perro inside a
TITLE tag that occurs at the top level or any level below. In other words, this query is equivalent to:
perro WITHIN TITLE
and finds both
DOC 1 and
DOC 2.
A child tag is a tag which is enclosed within another tag. For instance, in:
DOC 2 <BOOK><TITLE>Años De Perro</TITLE></BOOK>
TITLE is a child of
BOOK. We can find this document using the any-level tag searching, as in the previous section. But what if the corpus also contained:
DOC 3 <MOVIE><TITLE>Mi vida como un perro</TITLE></MOVIE>
In order to find only books with
perro in the title, we need to limit the search to
title tags whose parent is a
book tag:
perro INPATH(/BOOK/TITLE)
Reading the path right-to-left, we are looking for a top-level
BOOK tag with a child
TITLE tag, which matches only
DOC 2.
The single slash is direct parentage. The query above will not find:
DOC 4 <BOOK><DESCRIPTION> <TITLE>Años De Perro</TITLE> </DESCRIPTION></BOOK>
Because here
TITLE is not a direct child of
BOOK.
TITLE's direct parent is
DESCRIPTION, whose parent is
BOOK --
TITLE is a grand-child of
BOOK. To find this doc, you can use the any-level slashes:
perro INPATH(/BOOK//TITLE)
Reading the path right-to-left, we are looking for a top-level
BOOK tag with some descendant
TITLE tag. This query will match both
DOC 3 and
DOC 4. Note that this is not the same as:
((perro WITHIN TITLE) WITHIN BOOK)
First, the
INPATH query restricts
BOOK to the top-level. Second, equal sections are not confused. That is, the query:
((perro WITHIN BOOK) WITHIN TITLE)
would match
DOC 4, but the query:
perro INPATH(/TITLE//BOOK)
would not. Path sections know that
TITLE is a child of
BOOK, even though they occur at the same text offsets.
Finally, if you wanted to match only
DOC 4 and not
DOC 3 -- that is, you want to match
TITLE only if it is a grandchild of
BOOK, and not a child or great grandchild, etc. -- you can use the single level wildcard:
perro INPATH(/BOOK/*/TITLE)
The * matches exactly one level, so this path query filters out
DOC 3.
You can combine these ancestor/descendant elements for even more complicated queries:
felis INPATH(//kindgom/*/*/order/family//genus)
You can search within an attribute value using the syntax
<tag>/@<attribute>:
perro INPATH(//MOVIE/@SPANISHTITLE)
matches:
DOC 5 <MOVIE SPANISHTITLE="Mi vida como un perro">My Life As A Dog</MOVIE>
and is equivalent to the query:
perro WITHIN MOVIE@SPANISHTITLE
One limitation resulting from how attributes are indexed is that all attributes must specify their direct-parent tags. The following:
perro INPATH(//@TITLE) perro INPATH(A/*/@TITLE)
are not allowed, because the tag for the title attribute is not specified:
select * from doc where contains(text, 'perro INPATH(//@TITLE)')>0; * ERROR at line 1: ORA-20000: Oracle Text error: DRG-50951: Unable to resolve element name for attribute TITLE
The square brackets are used to impose a condition on a node without changing the path context. For instance, the query:
monopoly INPATH(/auction[image])
is looking for
monopoly inside a top-level
auction tag which has an
image tag as a direct child. The search for
monopoly occurs within the entirety of
<auction> and
</auction>, and not just within
<image> and
</image>. This document will match:
<auction>Sailing Monopoly <image src="...">pic</image></auction>
but will not match:
<auction>Sailing Monopoly</auction>
because there is no
image element. The default context inside a test element is the tag to which it is applied, so
monopoly INPATH(/auction[image])
is actually the same as:
monopoly INPATH(/auction[./image])
You need the dot to reference the default context. Without the dot:
monopoly INPATH(/auction[/image])
it would mean top-level image tag. This is not supported, and will result in a syntax error.
The existence test for image will match only if
image exists and is a direct child. It does not match:
<auction>Sailing Monopoly<desc><image src="...">pic</image></desc></auction>
because here
image is not a direct child of
auction. You can match this document using the any-level wildcard, instead:
monopoly INPATH(/auction[.//image])You can also test for attribute existence:
monopoly INPATH(/auction[@reserve])
The test node can be combined with other operators for interesting searches:
monopoly INPATH(/auction[.//image]/title)
The test node does not change context, so the
/title applies to
/auction rather than
/auction//image -- this query finds auctions where
monopoly occurs inside a direct-child
title tag, but only if the auction has an
image tag in it somewhere. For instance, the doc:
<auction> <title>Sailing Monopoly</title> <description> New Sailing Monopoly with custom pewter tokens from USAOpoly <image src="...">here is a picture</image> </description> </auction>
To test for non-existence, use the NOT operator:
monopoly INPATH(/auction[not(taxinfo)])
this query looks for
monopoly within an
auction element that does not have a direct child
taxinfo. The
NOT operator is case-insensitive in our path query language. In XPath it only works in lowercase.
The test operator is capable of more than simple existence testing. More useful is attribute value testing, which contrains nodes by the value of their attributes. For instance, given a document like:
<MOVIE> <TITLE LANGUAGE="German">Tiger und Dragon</TITLE> <TITLE LANGUAGE="French">Tigre et Dragon</TITLE> <TITLE LANGUAGE="Spanish">Tigre y Dragón</TITLE> <TITLE LANGUAGE="Mandarin">Wo hu cang long</TITLE> <TITLE LANGUAGE="English">Crouching Tiger, Hidden Dragon</TITLE> </MOVIE>
the query:
dragon INPATH(//TITLE)
will search all language titles. To limit the search to just English titles, you can add an attribute value equality test:
dragon INPATH(//TITLE[@LANGUAGE = "English"])
Only equality and inequality (using
!=) are supported. Range searches are not supported in this version. The left-hand side must be an attribute or tag, while the right-hand side must be a literal. The query:
gato INPATH(//A[@B = @C])
is not allowed, nor is something like
gato INPATH(//A["dog" = "cat"]
Only string literals are allowed. Numeric literals, such as
tora INPATH(//MOVIE[@PRICE = 5])
will raise a syntax error. This means that numbers are not normalized. The query above will not match:
<MOVIE PRICE="5.0">Tora! Tora! Tora!</MOVIE>
because the string
5 is not equal to the string
5.0, although numerically they are equal.
The equality test is not strict equality -- it uses "contains-equality". Two text fragments are contains-equal if the lexer produces identical index info. Some of the significant ways that this deviates from strict equality are:
MIXED_CASEon, it would consider
fooand
FOOto be equal strings.
WORD1 WORD2, the word offset of
WORD2is always 1 greater than the word offset of
WORD1-- it doesn't matter how many spaces or newlines there are between them. Also, any non-alphabetic, non-join character is converted to whitespace (and subsequently ignored). This can confuse names, with
Chase Matthewbeing contains-equal to
Chase, Matthew, or phrases, with
fruit-plantsbeing contains-equal to
fruit, plants.
Paris in the springwould be contains-equal to the document
Paris: avoid during spring.
The rules for contains equality seem complex, but it works the same as regular text queries hitting document text -- you've probably internalized these rules already. One significant difference between equality and contains, though, is that the equality test always makes sure that the number of words in the attribute value is the same as the number of words in the query string.
dragon INPATH(//TITLE[@LANGUAGE = "French"])
does not match any of these fragments:
<TITLE LANGUAGE="Canadian French">dragon</TITLE> <TITLE LANGUAGE="French Colloquial">dragon</TITLE> <TITLE LANGUAGE="Medieval French Colloquial">dragon</TITLE>
Although each
LANGUAGE attribute value has the word
French, there are extra words. These would match a contains in the attribute value, but they do not meet the "same number of words" equality criteria.
While docu-head people use a lot of attributes in their DTD's, data-heads prefer child tags. For instance, a docu-head might write:
<MOVIE YEAR="2001" TITLE="Moulin Rogue">...
While a data-head would prefer:
<MOVIE> <YEAR>2001</YEAR> <TITLE>Moulin Rogue</TITLE> ...
To match the data-head version, you can use equality testing on tag values:
moulin INPATH(//MOVIE[YEAR = "2001"])
Tag value equality uses contains-equality just like attribute value testing.
Inequality is also supported in both attribute and tag value equality, using the
!= operator:
moulin INPATH(//MOVIE[@YEAR != "2000"]) moulin INPATH(//MOVIE[YEAR != "2000"])
Note that inequality implies existence. The queries above do not match
<MOVIE>Moulin Rouge</MOVIE>
Because the
MOVIE tag does not have a
YEAR attribute or
YEAR child element. To test for non-existence, use the NOT operator.
You can use boolean
AND and
OR to combine existence or equality predicates in a test. Say you have documents like:
<MOVIE> <TITLE>Big Trouble in Little China</TITLE> <ACTORS> <ACTOR>Kurt Russell</ACTOR> <ACTOR>Kim Cattrall</ACTOR> </ACTORS> <DVD>2 DISCS</DVD> </MOVIE>
and you want to find movies with
china in the title starring Kurt Russell and Kim Cattrall that are available on DVD:
china INPATH(/MOVIE[DVD and .//ACTOR = "Kurt Russell" and .//ACTOR = "Kim Cattrall"]/TITLE)
You can use parentheses for precedence:
blue INPATH(/video[DVD and (discount or @rating = "4")])
AND and
OR are case-insensitive in our path query language. In XPath they must be lowercase.
Nested
INPATH operators are allowed, but the two are independent -- the default context of an
INPATH is always top level. For instance:
(perro INPATH(A)) INPATH(B)
will never hit any documents, because both
INPATH's are looking for top-level tags, and, except for invalid documents, a document cannot have two different top-level tags.
The
HASPATH operator is not a path query language operator; it's a ConText query language operator like
INPATH.
INPATH is used when you want to search for a text query within a path.
HASPATH is used when all you want to do is test for path existence; it takes a path as its only argument, and returns 100 for a document if the path exists, 0 otherwise.
select id from documents where contains(doc, 'HASPATH(/movie/dvd)')>0;
will return all documents where the top-level tag is a
movie element which has a
dvd element as a direct child.
HASPATH can also do tag value equality tests:
HASPATH(//A = "dog")
Attribute value equality tests and
AND and
OR operators are not currently supported. You can use the ConText query language
AND and
OR, with multiple
HASPATHs to achieve the same effect. Instead of:
HASPATH(A and B)
write:
HASPATH(A) and HASPATH(B)
HASPATH can return false hits when there are empty sections. Path sections are recorded with level information, but not true parentage. As a result, a document like:
<A> <B> <C></C> </B> <D> <E></E> </D> </A>
is matched by the query:
HASPATH(//B/E)
Since we do not have real parent information, we cannot detect that
E is not the child of
B. The index tells us only that
E and
B surround the same word offsets, and that
E is a third-level tag and
B is a second-level tag. Normally this indicates that
E is a child of
B. In this boundary case it does not. This limitation only applies to empty sections like this -- any words in the document would ensure correct behavior.
Highlighting with the
INPATH and
HASPATH operators is not supported in this version. You can still highlight and markup regular words, and
WITHIN queries, but use of the path operators will result in an error message. We are working on support for a future release.
Oracle 9i introduces a new datatype for storing XML -- the
XMLType. This is a core database feature, and you can find out about the type and its usage in the XML features manual.
You can create a ConText index on this type, but you need a few database privileges first:
1. the user creating the index must have
query rewrite:
grant query rewrite to <user>
Without this privilege, the create index will fail with:
ORA-01031: insufficient privileges
<user> should be the user creating the index. The schema that owns the index (if different) does not need the grant.
2.
query_rewrite_enabled should be
true, and
query_rewrite_integrity should be
trusted. You can add them to the
init.ora:
query_rewrite_enabled=true query_rewrite_integrity=trusted
or turn it on for the session:
alter session set query_rewrite_enabled=true; alter session set query_rewrite_integrity=trusted;
Without these, queries will fail with:
DRG-10599: column is not indexed
These privileges are needed because under the covers a ConText index on an
XMLType column is actually a function-based index on the
getclobval() method of the type. These are the standard grants you need to use function-based indexes, as covered in the general Oracle documentation. However, unlike function-based b-tree indexes, you do not need to calculate statistics.
When an
XMLType column is detected, and no section group is specified in the parameters string, the default system examines the new system parameter
DEFAULT_XML_SECTION, and uses the section group specified there. At install time this system parameter is set to
CTXSYS.PATH_SECTION_GROUP, which is the default path sectioner. The default filter system parameter for
XMLType is
DEFAULT_FILTER_TEXT, which probably means that the INSO filter is not engaged by default.
Other than the database privileges and the special default section group system parameter, indexes on
XMLType columns work like any other ConText index.
Here is a simple example:
connect ctxsys/ctxsys grant query rewrite to xtest; connect xtest/xtest create table xtest(doc sys.xmltype); insert into xtest values (sys.xmltype.createxml('<A>simple</A>')); create index xtestx on xtest(doc) indextype is ctxsys.context; alter session set query_rewrite_enabled = true; alter session set query_rewrite_integrity = trusted; select a.doc.getclobval() from xtest a where contains(doc, 'simple INPATH(A)')>0; | http://www.oracle.com/technetwork/database/enterprise-edition/overview/text-xml-901-093967.html | CC-MAIN-2014-35 | refinedweb | 3,719 | 52.19 |
Hide Forgot
python-pathlib2 failed to build from source in Fedora rawhide/f31
For details on the mass rebuild see:
Please fix python-pathlib2 at your earliest convenience and set the bug's status to
ASSIGNED when you start fixing it. If the bug remains in NEW state for 8 weeks,
python-pathlib2 will be orphaned. Before branching of Fedora 32,
python-pathlib2 will be retired, if it still fails to build.
For more details on the FTBFS policy, please visit:
Created attachment 1598817 [details]
build.log
file build.log too big, will only attach last 32768 bytes
Created attachment 1598819 [details]
root.log
file root.log too big, will only attach last 32768 bytes
Created attachment 1598820 [details]
state.log
python-pathlib2 fails to build without python3-test:
============================= test session starts ==============================
platform linux -- Python 3.8.0b3, pytest-4.6.4, py-1.8.0, pluggy-0.12.0 -- /usr/bin/python3
cachedir: .pytest_cache
rootdir: /builddir/build/BUILD/pathlib2-2.3.4
collecting ... collected 0 items / 1 errors
==================================== ERRORS ====================================
___________________ ERROR collecting tests/test_pathlib2.py ____________________
ImportError while importing test module '/builddir/build/BUILD/pathlib2-2.3.4/tests/test_pathlib2.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_pathlib2.py:43: in <module>
from test import support
E ModuleNotFoundError: No module named 'test'
During handling of the above exception, another exception occurred:
tests/test_pathlib2.py:45: in <module>
from test import test_support as support
E ModuleNotFoundError: No module named 'test'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.25 seconds ============================
The fix is at:
See
This blocks the Python 3.8 rebuild:
This bug appears to have been reported against 'rawhide' during the Fedora 31 development cycle.
Changing version to '31'.
This bug appears to have been reported against 'rawhide' during the Fedora 31 development cycle.
Changing version to 31.
Oops, sorry Miro. I stumbled across this issue myself and fixed it before looking up this bug. I didn't see you had a pull request.
Paulo has been absent from Fedora for well over a year now, so I've gotten into the habit of looking after his packages. I'll try to get in touch with him to see if he has plans to return to actively maintaining his packages.
No problem. Glad that it is fixed. | https://bugzilla.redhat.com/show_bug.cgi?id=1736520 | CC-MAIN-2021-21 | refinedweb | 387 | 59.9 |
Console Cat - Privacy-friendly CLI telemetry in less than five minutes - Interview with Matt Evenson
Web applications tend to grow big as features are developed. The longer it takes for your site to load, the more frustrating it's to the user. This problem is amplified in a mobile environment where the connections can be slow.
Even though splitting bundles can help a notch, they are not the only solution, and you can still end up having to download a lot of data. Fortunately, it's possible to do better thanks to code splitting as it allows loading code lazily when you need it.
You can load more code as the user enters a new view of the application. You can also tie loading to a specific action like scrolling or clicking a button. You could also try to predict what the user is trying to do next and load code based on your guess. This way, the functionality would be already there as the user tries to access it.
Incidentally, it's possible to implement Google's PRPL pattern using webpack's lazy loading. PRPL (Push, Render, Pre-cache, Lazy-load) has been designed with the mobile web in mind.
Philip Walton's idle until urgent technique complements code splitting and lets you optimize application loading performance further. The idea is to defer work to the future until it makes sense to perform.
Code splitting can be done in two primary ways in webpack: through a dynamic
import or
require.ensure syntax. The latter is so called legacy syntax.
The goal is to end up with a split point that gets loaded on demand. There can be splits inside splits, and you can structure an entire application based on splits. The advantage of doing this is that then the initial payload of your site can be smaller than it would be otherwise.
import#
Dynamic imports are defined as
Promises:
import(/* webpackChunkName: "optional-name" */ "./module").then( module => {...} ).catch( error => {...} );
Webpack provides extra control through a comment. In the example, we've renamed the resulting chunk. Giving multiple chunks the same name will group them to the same bundle. In addition
webpackMode,
webpackPrefetch, and
webpackPreload are good to know options as they let you define when the import will get triggered and how the browser should treat it.
Mode lets you define what happens on
import(). Out of the available options,
weak is suitable for server-side rendering (SSR) as using it means the
Promise will reject unless the module was loaded another way. In the SSR case, that would be ideal.
Prefetching tells the browser that the resource will be needed in the future while preloading means the browser will need the resource within the current page. Based on these tips the browser can then choose to load the data optimistically. Webpack documentation explains the available options in greater detail.
webpack.PrefetchPlugin allows you to prefetch but on the level of any module.
webpackChunkNameaccepts
[index]and
[request]placeholders in case you want to let webpack define the name or a part of it.
The interface allows composition, and you could load multiple resources in parallel:
Promise.all([import("lunr"), import("../search_index.json")]).then( ([lunr, search]) => { return { index: lunr.Index.load(search.index), lines: search.lines, }; } );
The code above creates separate bundles to a request. If you wanted only one, you would have to use naming or define an intermediate module to
import.
The syntax works only with JavaScript after configuring it the right way. If you use another environment, you may have to use alternatives covered in the following sections.
import#
The idea can be demonstrated by setting up a module that contains a string that replaces the text of the demo button:
src/lazy.js
export default "Hello from lazy";
You also need to point the application to this file, so the application knows to load it by binding the loading process to click. Whenever the user happens to click the button, you trigger the loading process and replace the content:
src/component.js
export default (text = "Hello world") => { const element = document.createElement("div"); element.className = "rounded bg-red-100 border max-w-md m-4 p-4"; element.innerHTML = text; element.onclick = () => import("./lazy") .then((lazy) => { element.textContent = lazy.default; }) .catch((err) => console.error(err)); return element; };
If you open up the application (
npm start) and click the button, you should see the new text in it.
After executing
npm run build, you should see something:
⬡ webpack: Build Finished ⬡ webpack: assets by status 7.95 KiB [compared for emit] asset main.css 7.72 KiB [compared for emit] (name: main) 1 related asset asset index.html 237 bytes [compared for emit] assets by status 3.06 KiB [emitted] asset main.js 2.88 KiB [emitted] [minimized] (name: main) 1 related asset asset 34.js 187 bytes [emitted] [minimized] 1 related asset ... webpack 5.5.0 compiled successfully in 3846 ms ...
That
34.js is your split point. Examining the file reveals webpack has processed the code.
If you want to adjust the name of the chunk, set
output.chunkFilename. For example, setting it to
"chunk.[id].js"would prefix each split chunk with the word "chunk".
If you are using TypeScript, make sure to set
compilerOptions.moduleto
esnextor
es2020for code splitting to work correctly.
Especially in a complex environment with third-party dependencies and an advanced deployment setup, you may want to control where split code is loaded from. webpack-require-from has been designed to address the problem, and it's able to rewrite the import paths.
See React's official documentation to learn about the code splitting APIs included out of the box. The most important ones are
React.lazy and
React.Suspense. Currently these don't support server-side rendering. Packages like @loadable/component wrap the idea behind an interface.
Although code splitting is a good behavior to have by default, it's not correct always, especially on server-side usage. For this reason, it can be disabled as below:
const config = { plugins: [ new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }), ], };
See Glenn Reyes' detailed explanation.
Often users use an application in a specific way. The fact means that it makes sense to load specific portions of the application even before the user has accessed them. guess-webpack builds on this idea of prediction based preloading. Minko Gechev explains the approach in detail in his article.
Code splitting is a feature that allows you to push your application a notch further. You can load code when you need it to gain faster initial load times and improved user experience especially in a mobile context where bandwidth is limited.
To recap:
In the next chapter, you'll learn how to split a vendor bundle without through webpack configuration.
The Searching with React appendix contains a complete example of code splitting. It shows how to set up a static site index that's loaded when the user searches information.
This book is available through Leanpub (digital), Amazon (paperback), and Kindle (digital). By purchasing the book you support the development of further content. A part of profit (~30%) goes to Tobias Koppers, the author of webpack. | https://survivejs.com/webpack/building/code-splitting/ | CC-MAIN-2022-40 | refinedweb | 1,196 | 57.67 |
Tutorial: Build a Full-Stack Reactive Chat App With Spring Boot
Learn how to connect a reactive Spring Boot back end to a reactive TypeScript front end to build a full-stack reactive chat app.
Join the DZone community and get the full member experience.Join For Free
What You Will Build
You will build a full-stack chat application with a Java Spring Boot back end, reactive data types from Project Reactor, and a Lit TypeScript front end. In addition, you will use the Hilla framework to build tools and client-server communication.
What You Will Need
- 20 minutes
- Java 11 or newer
- Node 16.14 or newer
- An IDE that supports both Java and TypeScript, such as VS Code.
Video Version
The video below walks you through this tutorial step-by-step, if you prefer to learn by watching.
Create a New Project
Begin by creating a new Hilla project. This will give you a Spring Boot project configured with a Lit front end.
- Use the Vaadin CLI to initialize the project:
npx @vaadin/cli init --hilla --empty hilla-chat
- Open the project in your IDE of choice.
- Start the application using the included Maven wrapper. The command will download Maven and npm dependencies and start the development server. Note: the initial start can take several minutes. Subsequent starts are almost instant.
./mvnw
Build the Chat View
Begin by creating the view for displaying and sending chat messages. Hilla includes the Vaadin component set, which has over 40 components. You will use the
<vaadin-message-list> and
<vaadin-message-input> components to build out the main chat UI. You will also use the
<vaadin-text-field> component to capture the current user's name.
Replace the contents of
frontend/views/empty/empty-view.ts with the following:
import { html } from 'lit'; import { customElement } from 'lit/decorators.js'; import { View } from '../../views/view'; import '@vaadin/vaadin-messages'; import '@vaadin/vaadin-text-field'; @customElement('empty-view') export class EmptyView extends View { render() { return html` <vaadin-message-list</vaadin-message-list> <div class="flex p-s gap-s items-baseline"> <vaadin-text-field</vaadin-text-field> <vaadin-message-input</vaadin-message-input> </div> `; } connectedCallback() { super.connectedCallback(); this.classList.add('flex', 'flex-col', 'h-full', 'box-border'); } }
Hilla uses Lit for creating views. Lit is conceptually similar to React: components consist of a state and a template. The template gets re-rendered any time the state changes.
In addition to the included Vaadin components, you are also using Hilla CSS utility classes for some basic layouting (
flex,
flex-grow,
flex-col).
You should see an empty window with inputs at the bottom when you save the file. (Start the server with
./mvnw if you don't have it running.)
Create a Reactive Server Endpoint
Next, you need a back end that can broker messages between clients. For this, you will use the reactive data types provided by Project Reactor.
Create a new Java class in the
com.example.application package called
ChatEndpoint.java and paste the following code into it:
package com.example.application; import java.time.ZonedDateTime; import com.vaadin.flow.server.auth.AnonymousAllowed; import dev.hilla.Endpoint; import dev.hilla.Nonnull; import reactor.core.publisher.Flux; import reactor.core.publisher.Sinks; import reactor.core.publisher.Sinks.EmitResult; import reactor.core.publisher.Sinks.Many; @Endpoint @AnonymousAllowed public class ChatEndpoint { public static class Message { public @Nonnull String text; public ZonedDateTime time; public @Nonnull String userName; } private Many<Message> chatSink; private Flux<Message> chat; ChatEndpoint() { chatSink = Sinks.many().multicast().directBestEffort(); chat = chatSink.asFlux().replay(10).autoConnect(); } public @Nonnull Flux<@Nonnull Message> join() { return chat; } public void send(Message message) { message.time = ZonedDateTime.now(); chatSink.emitNext(message, (signalType, emitResult) -> emitResult == EmitResult.FAIL_NON_SERIALIZED); } }
Here are the essential parts explained:
- The
@Endpointannotation tells Hilla to make all public methods available as TypeScript methods for the client.
@AnonymousAllowedturns off authentication for this endpoint.
- The Message class is a plain Java object for the data model. The
@Nonnullannotations tell the TypeScript generator that these types should not be nullable.
- The
chatSinkis a programmatic way to pass data to the system. It emits messages so that any client that has subscribed to the associated
chatFlux will receive them.
- The
join()-method returns the chat Flux, which you will subscribe to on the client.
- The
send()-method takes in a message, stamps it with the send time, and emits it to the
chatSink.
Sending and Receiving Messages in the Client
With the back end in place, the only thing that remains is connecting the front-end view to the server.
Replace the contents of
empty-view.ts with the following:
import { html } from 'lit'; import { customElement, state } from 'lit/decorators.js'; import { View } from '../../views/view'; import '@vaadin/vaadin-messages'; import '@vaadin/vaadin-text-field'; import Message from 'Frontend/generated/com/example/application/ChatEndpoint/Message'; import { ChatEndpoint } from 'Frontend/generated/endpoints'; import { TextFieldChangeEvent } from '@vaadin/vaadin-text-field'; @customElement('empty-view') export class EmptyView extends View { @state() messages: Message[] = []; @state() userName = ''; render() { return html` <vaadin-message-list <vaadin-text-field placeholder="Name" @change=${this.userNameChange}></vaadin-text-field> <vaadin-message-input class="flex-grow" @submit=${this.submit}></vaadin-message-input> </div> `; } userNameChange(e: TextFieldChangeEvent) { this.userName = e.target.value; } submit(e: CustomEvent) { ChatEndpoint.send({ text: e.detail.value, userName: this.userName, }); } connectedCallback() { super.connectedCallback(); this.classList.add('flex', 'flex-col', 'h-full', 'box-border'); ChatEndpoint.join().onNext( (message) => (this.messages = [...this.messages, message]) ); } }
Here are the essential parts explained:
- The
@state()decorated properties are tracked by Lit. Any time they change, the template gets re-rendered.
- The
Messagedata type is generated by Hilla based on the Java object you created on the server.
- The list of messages is bound to the message list component with
.items=${this.messages}. The period in front of items tells Lit to pass the array as a property instead of an attribute.
- The text field calls the
userNameChange-method whenever the value gets changed with
@change=${this.userNameChange}(the
@denotes an event listener).
- The message input component calls
ChatEndpoint.save()when submitted. Note that you are calling a TypeScript method. Hilla takes care of calling the underlying Java method on the server.
- Finally, call
ChatEndpoint.join()in
connectedCallbackto start receiving incoming chat messages.
When you save the file, you will notice a warning pop up in the lower-right corner of the browser window. Click on it to enable the push support feature flag in Hilla. This feature flag enables support for subscribing to Flux data types over a web socket connection.
Run the Completed Application
Once you have enabled the push support feature flag, stop the running server (
CTRL-C) and re-run it (
./mvnw). You now have a functional chat application. Try it out by opening a second browser or an incognito window as a second user.
Next Steps
- You can find the complete source code of the completed application on my GitHub.
- Visit the Hilla website for more tutorials and complete documentation.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/tutorial-build-a-full-stack-reactive-chat-app-with | CC-MAIN-2022-33 | refinedweb | 1,168 | 51.75 |
).
MeisterTask is an incredibly intuitive online task manager that uses smart integrations and task automations to make your team more productive.MeisterTask
MeisterTask + SlackSend Slack channel messages on new MeisterTask tasks
MeisterTask + Zoho ConnectCreate tasks in Zoho Connect for new MeisterTask tasks
MongoDB + {{item.actionAppName}}{{item.message}}
It's easy to connect MongoDB + MeisterTask a new attachment.
Creates a new label.
Creates a new task.
Creates a new task label.
Updates an existing task.
(30 seconds)
(10 seconds)
(30 seconds)
(10 seconds)
(2 minutes)
MongoDB is an open-source NoSQL database. MongoDB was initially released by 10gen, Inc in October 2009. It is a document-oriented database (aka NoSQL.
It uses JSON-like documents with dynamic schemas (i.e. schemas can be changed in the running system. and that are multi-dimensional (i.e. data is not stored in tables only but can be stored in multi-dimensional arrays.
Data in MongoDB is dynamic and schema-less. It stores data as BSON (binary JSON. It does not use SQL like syntax to interact with it. It is schema-less where there is no need for DDL or DML statements to define the schema of the database.
It supports multiple programming languages including Java, C++, .NET, Ruby, Python, PHP, Go and Node.js. It has a high level API called MongoDB C++ Driver (C++ Driver also known as “the C Driver”), which provides access to the full features of MongoDB including the GridFS filesystem and the ability to connect over SSL. There are other drivers available for different languages such as Java and Node.js.
MeisterTask is a task management software that allows users to manage tasks related to their work through the use of a shared calendar. Users can create tasks and assign them to other members of the team or to themselves. The tasks can be linked to one or more calendars, which allows users to create tasks from calendar events and vice versa. Tasks can be assigned to different categories, and they can be assigned to dates within a range of dates determined by the user. Users can add comments to tasks and attach files to them as well as set reminders, see when others are working on the same task, and cplaborate with them about what needs to be done and when it should be done by. Tasks are displayed on a calendar view.
There are two ways to integrate MongoDB and MeisterTask together:
MongoDB as a data store for MeisterTask data. Since MeisterTask is an application whose main function is to manage tasks and tasks are usually stored as separate entities in databases, we could integrate MongoDB into a project using MeisterTask as a data store for all the tasks in it. This would allow MeisterTask to use MongoDB only as a data store. MongoDB as a data store for a specific project that uses MeisterTask. We could do something similar to above by integrating MongoDB into MeisterTask as it is but this time we do not want our project to use MeisterTask as a data store for its data but instead we want to use some data stored on MongoDB as a data source for a specific project within MeisterTask so that we can use both the projects for different things and not have different instances of MeisterTask running. For instance, if we are building an online shop then we could store all the orders that have been placed online in MongoDB, which would mean we would not have to create any data on MeisterTask just for storing orders despite the fact that we could still use MeisterTask for something else such as managing employees' schedules or reporting sales figures etc…
Since we will be using MeisterTask just as a front-end top, we don’t need to write code that will allow us to save data on MeisterTask directly into MongoDB but rather we will use an API provided by MongoDB itself so that we can call one of its functions from within our code whenever we need to save something on it. In order to call one of its functions we need an API key which will enable us to make calls on it for free. You can request an API key from here once you have registered an account on the site or even if you haven't yet registered an account on the site but plan to register one later on. Here are instructions on how you can request an API key from here while still having an account on the site:
Open the profile page for your project by clicking the avatar icon next to your username at the top right corner of your dashboard. Then click "API Keys" under "Manage". On the "API Keys" page click "Request API Key". Fill out the form and click "Request Key". Once your api_key has been successfully created you can close the window saying "Thank you! Your api_key has been created." then click "Save Changes" at the bottom of the page. Once you have saved your changes you can close your dashboard and go hack away at your code!
Now let's get down to business... First thing's first... We'll start with getting some information about our database structure using MongoTop:
#include <iostream> #include <string> #include <sstream> #include <cstdlib> #include <time.h> #include <MongoTop/MongoTop.hpp> using namespace std; using namespace boost::program_options; int main(. { string dbName = "-"; string dbHost = "-"; string dbPort = "-"; string dbUser = "-"; string dbPass = "-"; int dbConnections = 1; int retries = 0; string mongodbUrl("mongodb://" + std::to_string(dbUser. + ":" + std::to_string(dbPass. + "@" + std::to_string(dbHost. + ":" + std::to_string(dbPort)); string mongodbOptions("ssl=true"); // Options for mongo->setServer(. mongodbOptions += "replSet=127.0.0.1:27017"; // Options for mongo->setDatabase(. mongodbOptions += dbName; mongodbOptions += "/"; mongodbUrl = mongodbUrl + mongodbOptions; int retval = 1; bop bSuccess = false; bop bConnectionFailed = false; while (retval != -1 && !bSuccess. { std::cout << "Enter paramters for connecting to your MongoDB server" << std::endl; std::cout << "Name. "; std::getline(std::cin, dbName); std::cout << "Host. "; std::getline(std::cin, dbHost); std::cout << "Port. "; std::getline(std::cin, dbPort); std::cout << "User ID. "; std::getline(std::cin, dbUser); std::cout << "Password. "; std::getline(std::cin, dbPass); std::cout << std::endl; bSuccess = false; bConnectionFailed = false; retval = pconfig->Configure("mongodb", dbName, dbHost, dbPort, dbUser, dbPass); // Set server options retval = pconfig->SetOptions("mongodb", mongodbUrl); // Set database options retval = pconfig->SetOptions("mongodb", mongodbUrl); // Set database connection options retval = pconfig->SetOptions("mongodb", mongodbUrl); // Save connection options retval = pconfig->Save(); // Connect retval = pconfig->Connect(); if (retval == -2. { time_t curTime = time(NULL); int curDate = curTime / 1000 * 3600; int curHour = curTime % 3600 / 60; int curMinute = curTime % 60; int curSecond = curTime % 60; time_t hour1 = curTime + 3600 * 24 * 24 * 3600; time_t hour2 = hour1 + 3600 * 3600 * 3600; time_t hour3 = hour2 + 3600 * 3600 * 3600; time_t hour4 = hour3 + 3600 * 3600 * 3600; string dateStr = IntToString(curDate); dateStr += ", "; dateStr += IntToString(curHour); dateStr += ", "; dateStr += IntToString(curMinute); dateStr += ", 00"; dateStr += IntToString(curSecond); std::cout << dateStr << std::endl; } } return 0; }
The above code contains everything that you will need to
The process to integrate MongoDB and MeisterTask may seem complicated and intimidating. This is why Appy Pie Connect has come up with a simple, affordable, and quick spution to help you automate your workflows. Click on the button below to begin. | https://www.appypie.com/connect/apps/mongodb/integrations/meistertask | CC-MAIN-2022-05 | refinedweb | 1,203 | 61.67 |
I just installed Debian 5 (Lenny) and I noticed that /lib/init/rw is reported as a RAM Disk (tmpfs). I've only had experience with Fedora so I'm curious what function does that directory serve in Debian. Can it be used by user written shell scripts to cache stuff or is it off-limits and only for use by the OS? Thanks.
As others point out (this would have been a comment on their replies, but grew too long to fit the comment box) this is used by some initscripts, generally during the boot process, when your other filesystems may be read-only or even not yet mounted at all.
The filesystem is left mounted after startup has completed as initscripts that write there may be run at other times (if you manually restart a service, or switch runlevels). You should not force it to unmount in case the device/filesystem /lib/init is on becomes readonly. It does not consume any appreciable resource when not actually storing data so is not a performance concern.
/lib/init
While I do not see any harm in using it for your own scripts if your scripts are well tested and can be guaranteed not to completely fill it such that initscripts can't write there when they need to, you would be safer to create your own tmpfs mount for this purpose (you can have as many as you like, in theory, and they only consume memory when actually storing data) or just use /tmp and have that mounted as a tmpfs filesystem instead of being on disk.
tmpfs
/tmp
If you do use a tmpfs filesystem for temporary data, be aware that this will consume memory and if you are low on memory to start with may induce swapping. This is why I generally use a separate mount instead of /tmp (which is where many processes will put stuff so it is more likely to use more memory long term than my scripts alone). If you have plenty of memory "spare" most of the time this is not an issue though. In the output of free, top and similar tools memory used by data held in tmpfs filesystems is usually counted in the "cached" count - see In Linux, what is the difference between "buffers" and "cache" reported by the free command? for more detail on that.
free
top
Edit: I forgot to add... The other reason for creating your own tmpfs based mount instead of using the one Debian creates for their standard scripts, is that you are making your scripts less reliant on a distribution specific property, meaning you have a little more to change if your scripts are migrated to other configurations.
Apparently it is used by initscripts at startup see this link
It is used by initscript requiring a writable namespace at the time /sbin/init is run. Remember, at that time your root partition might very well be readonly.
Anders
By posting your answer, you agree to the privacy policy and terms of service.
asked
5 years ago
viewed
6367 times
active
1 year ago | http://serverfault.com/questions/30819/what-is-the-use-of-lib-init-rw-in-debian?answertab=active | CC-MAIN-2015-11 | refinedweb | 520 | 61.19 |
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.
Changing selection field content
Hello,
I need to change my slection elements after change field1 .
this code doesn't work , who has an idea how to fix it ?
_columns = {
'field1': fields.selection([('1', 'A'), ('1', 'B')], 'my filed 1'),
'field2': fields.selection([('aa', 'C'), ('bb', 'D')], 'my filed 2'),
}
def onchange_field2(self, cr, uid, ids,field1,context=None):
lst= [('5', '5'), ('6', '6'), ('7', '7'), ('8', '8')]
try:
lst.remove([item for item in lst if item[0] == '5'][0])
except IndexError as e:
pass
v = {'field2': lst}
return {'value': v}
thank you
Sorry but selection fields doesn't allow you to change the values like you are doing, they are a kind of static collection of options/values to select just one. For doing something like that you need to change your field definition to a many2one and apply a domain to the field that restrict the results to the matching records and the domain could be build and returned from an on | https://www.odoo.com/forum/help-1/question/changing-selection-field-content-94320 | CC-MAIN-2017-09 | refinedweb | 193 | 68.81 |
#include <sql_optimizer.h>
A hook that secondary storage engines can use to override the executor completely.
State of execution plan. Currently used only for EXPLAIN.
Helper for JOIN::attach_join_conditions().
Attaches bits of 'join_cond' to each table in the range [first_inner, last_tab], with proper guards. If 'sj_mat_cond' is true, we do not see first_inner (and tables on the same level of it) as inner to anything, as they're at the top from the POV of the materialization of the tmp table. So, if the SJ-mat nest is A LJ B, A will get a part of condition without any guard; B will get another part with a guard on A->found_match. It's like pushing a WHERE.
Attach outer join conditions to generated table conditions in an optimal way.
Outer join conditions are attached to individual tables, but we can analyze those conditions only when reaching the last inner table of an outer join operation. Notice also that a table can be last within several outer join nests, hence the outer for() loop of this function.
Example: SELECT * FROM t1 LEFT JOIN (t2 LEFT JOIN t3 ON t2.a=t3.a) ON t1.a=t2.a
Table t3 is last both in the join nest (t2 - t3) and in (t1 - (t2 - t3)) Thus, join conditions for both join nests will be evaluated when reaching this table.
For each outer join operation processed, the join condition is split optimally over the inner tables of the outer join. The split-out conditions are later referred to as table conditions (but note that several table conditions stemming from different join operations may be combined into a composite table condition).
Example: Consider the above query once more. The predicate t1.a=t2.a can be evaluated when rows from t1 and t2 are ready, ie at table t2. The predicate t2.a=t3.a can be evaluated at table t3.
Each non-constant split-out table condition is guarded by a match variable that enables it only when a matching row is found for all the embedded outer join operations.
Each split-out table condition is guarded by a variable that turns the condition off just before a null-complemented row for the outer join operation is formed. Thus, the join condition will not be checked for the null-complemented row.
Tells what is the cheapest between IN->EXISTS and subquery materialization, in terms of cost, for the subquery's JOIN.
Input:
This plan choice has to happen before calling functions which set up execution structures, like JOIN::get_best_combination().
Overwrites one slice of ref_items with the contents of another slice.
In the normal case, dst and src have the same size(). However: the rollup slices may have smaller size than slice_sz.
Retrieve the cost model object to be used for this join.
Decides between EXISTS and materialization; performs last steps to set up the chosen strategy.
For each materialized derived table/view, informs every TABLE of the key it will (not) use, segregates used keys from unused keys in TABLE::key_info, and eliminates unused keys.
Remove redundant predicates and cache constant expressions.
Do a final round on pushed down table conditions and HAVING clause. Optimize them for faster execution by removing predicates being obsolete due to the access path selected for the table. Constant expressions are also cached to avoid evaluating them for each row being compared.
Check if FTS index only access is possible.
Add keys to derived tables'/views' result tables in a list.
This function generates keys for all derived tables/views of the query_block to which this join corresponds to with help of the TABLE_LIST:generate_keys function.
Returns the clone of fields_list which is appropriate for evaluating expressions at the current stage of execution; which stage is denoted by the value of current_ref_item_slice.
See enum_plan_state.
Initialize key dependencies for join tables.
TODO figure out necessity of this method. Current test suite passed without this intialization.
Fill in outer join related info for the execution plan structure.
For each outer join operation left after simplification of the original query the function set up the following pointers in the linear structure join->join_tab representing the selected execution plan. The first inner table t0 for the operation is set to refer to the last inner table tk through the field t0->last_inner. Any inner table ti for the operation are set to refer to the first inner table ti->first_inner. The first inner table t0 for the operation is set to refer to the first inner table of the embedding outer join operation, if there is any, through the field t0->first_upper. The on expression for the outer join operation is attached to the corresponding first inner table through the field t0->on_expr_ref. Here ti are structures of the JOIN_TAB type.
EXAMPLE. For the query:
given the execution plan with the table order t1,t2,t3,t4 is selected, the following references will be set; t4->last_inner=[t4], t4->first_inner=[t4], t4->first_upper=[t2] t2->last_inner=[t4], t2->first_inner=t3->first_inner=[t2], on expression (t1.a=t2.a AND t1.b=t3.b) will be attached to t2->on_expr_ref, while t3.a=t4.a will be attached to *t4->on_expr_ref.
Move const tables first in the position array.
Increment the number of const tables and set same basic properties for the const table. A const table looked up by a key has type JT_CONST. A const table with a single row has type JT_SYSTEM.
Function sets FT hints, initializes FT handlers and checks if FT index can be used as covered.
Update some values in keyuse for faster choose_table_order() loop.
Optimize rollup specification.
Allocate objects needed for rollup processing.
True if plan is const, ie it will return zero or one rows.
True if plan contains one non-const primary table (ie not including tables taking part in semi-join materialization).
Query expression referring this query block.
Refine the best_rowcount estimation based on what happens after tables have been joined: LIMIT and type of result sink.
Remove all constants and check if ORDER only contains simple expressions.
simple_order is set to true if sort_order only uses fields from head table and the head table is not a LEFT JOIN table.
Return whether the caller should send a row even if the join produced no rows if:
Overwrite the base slice of ref_items with the slice supplied as argument.
Set of tables contained in query.
True if plan search is allowed to use references to expressions outer to this JOIN (for example may set up a 'ref' access looking up an outer expression in the index, etc).
This is the result of join optimization.
The cost of best complete join plan found so far during optimization, after optimization phase - cost of picked join order (not taking into account the changes made by test_if_skip_sort_order()).
Array of plan operators representing the current (partial) best plan.
The array is allocated in JOIN::make_join_plan() and is valid only inside this function. Initially (*best_ref[i]) == join_tab[i]. The optimizer reorders best_ref.
The estimated row count of the plan with best read time (see above).
If true, calculate found rows for this query block.
True if, at this stage of processing, subquery materialization is allowed for children subqueries of this JOIN (those in the SELECT list, in WHERE, etc).
If false, and we have to evaluate a subquery at this stage, then we must choose EXISTS.
Set of tables found to be const.
Number of primary tables deemed constant.
The slice currently stored in ref_items[0].
Used to restore the base ref_items slice from the "save" slice after it has been overwritten by another slice (1-3).
This is the bitmap of all tables which are dependencies of lateral derived tables which are not (yet) part of the partial plan.
(The value is a logical 'or' of zero or more TABLE_LIST.map() values.)
When we are building the join order, there is a partial plan (an ordered sequence of JOIN_TABs), and an unordered set of JOIN_TABs not yet added to the plan. Due to backtracking, the partial plan may both grow and shrink. When we add a new table to the plan, we may wish to set up join buffering, so that rows from the preceding table are buffered. If any of the remaining tables are derived tables that depends on any of the predecessors of the table we are adding (i.e. a lateral dependency), join buffering would be inefficient. (
For this reason we need to maintain this table_map of lateral dependencies of tables not yet in the plan. Whenever we add a new table to the plan, we update the map by calling Optimize_table_order::recalculate_lateral_deps_incrementally(). And when we remove a table, we restore the previous map value using a Tabel_map_restorer object.
As an example, assume that we join four tables, t1, t2, t3 and d1, where d1 is a derived table that depends on t1:
SELECT * FROM t1 JOIN t2 ON t1.a=t2.b JOIN t3 ON t2.c=t3.d JOIN LATERAL (SELECT DISTINCT e AS x FROM t4 WHERE t4.f=t1.c) AS d1 ON t3.e=d1.x;
Now, if our partial plan is t1->t2, the map (of lateral dependencies of the remaining tables) will contain t1. This tells us that we should not use join buffering when joining t1 with t2. But if the partial plan is t1->d2->t2, the map will be empty. We may thus use join buffering when joining d2 with t2.
If true, send produced rows using query_result.
set in optimize(), exec(), prepare_result()
Set by exec(), reset by reset().
Note that this needs to be set during the query (not only when it's done executing), or the dynamic range optimizer will not understand which tables have been read.:
Const tables which are either:
If we have the GROUP BY statement in the query, but the group_list was emptied by optimizer, this flag is true.
It happens when fields in the GROUP BY are from constant table
Exec time only: true <=> current group has been sent.
If query contains GROUP BY clause.
If JOIN has lateral derived tables (is set at start of planning)
Incremented each time clear_hash_tables() is run, signaling to HashJoinIterators that they cannot keep their hash tables anymore (since outer references may have changed).
Optimized HAVING clause item tree (valid for one single execution).
Used in JOIN execution, as last "row filtering" step. With one exception: may be pushed to the JOIN_TABs of temporary tables used in DISTINCT / GROUP BY (see JOIN::make_tmp_tables_info()); in that case having_cond is set to NULL, but is first saved to having_for_explain so that EXPLAIN EXTENDED can still print it. Initialized by Query_block::get_optimizable_conditions().
Saved optimized HAVING for EXPLAIN.
True if aggregated but no GROUP BY.
Optimal query execution plan.
Initialized with a tentative plan in JOIN::make_join_plan() and later replaced with the optimal plan in get_best_combination().
Used and updated by JOIN::make_join_plan() and optimize_keyuse()
An access path you can read from to get all records for this query (after you create an iterator from it).
If this query block contains conditions synthesized during IN-to-EXISTS conversion: A second query plan with all such conditions removed.
See comments in JOIN::optimize().
If we have set up tmp tables for windowing,.
Any window definitions.
True if a window requires a certain order of rows, which implies that any order of rows coming out of the pre-window join will be disturbed.
mapping between table indexes and JOIN_TABs
mapping between table indexes and QEB_TABs
If true we need a temporary table on the result set before any windowing steps, e.g.
for DISTINCT or we have a query ORDER BY. See details in JOIN::optimize
flag to avoid double optimization in EXPLAIN
ORDER BY and GROUP BY lists, to transform with prepare,optimize and exec.
Final execution plan state. Currently used only for EXPLAIN.
Number of primary input tables in query block.
Array of QEP_TABs.
Query block that is optimized and executed using this JOIN.
Used only if this query block is recursive.
Contains count of all executions of this recursive query block, since the last this->reset().
ref_items is an array of 4+ slices, each containing an array of Item pointers.
ref_items is used in different phases of query execution.
slices 4 -> N are used by windowing: all the window's out tmp tables,
Two windows: 4: window 1's out table 5: window 2's out table
and so on.
Slice 0 is allocated for the lifetime of a statement, whereas slices 1-3 are associated with a single optimization. The size of slice 0 determines the slice size used when allocating the other slices.
At construction time, set if SELECT DISTINCT.
May be reset to false later, when we set up a temporary table operation that deduplicates for us.
Is set if we have a GROUP BY and we have ORDER BY on a constant or when sorting isn't required.
Expected cost of filesort.
Indicates that the data will be aggregated (typically GROUP BY), and that it is already processed in an order that is compatible with the grouping in use (e.g.
because we are scanning along an index, or because an earlier step sorted the data in a group-compatible order).
Note that this flag changes value at multiple points during optimization; if it's set when a temporary table is created, this means we aggregate into said temporary table (end_write_group is chosen instead of end_write), but if it's set later, it means that we can aggregate as we go, just before sending the data to the client (end_send_group is chosen instead of end_send).
Before plan has been created, "tables" denote number of input tables in the query block and "primary_tables" is equal to "tables".
After plan has been created (after JOIN::get_best_combination()), the JOIN_TAB objects are enumerated as follows:
Pointer set to query_block->get_table_list() at the start of optimization.
May be changed (to NULL) only if optimize_aggregated_query() optimizes tables away.
Thread handler.
Array of pointers to lists of expressions.
Each list represents the SELECT list at a certain stage of execution, and also contains necessary extras: expressions added for ORDER BY, GROUP BY, window clauses, underlying items of split items. This array is only used when the query makes use of tmp tables: after writing to tmp table (e.g. for GROUP BY), if this write also does a function's calculation (e.g. of SUM), after the write the function's value is in a column of the tmp table. If a SELECT list expression is the SUM, and we now want to read that materialized SUM and send it forward, a new expression (Item_field type instead of Item_sum), is needed. The new expressions are listed in JOIN::tmp_fields_list[x]; 'x' is a number (REF_SLICE_).
Describes a temporary table.
Each tmp table has its own tmp_table_param. The one here is transiently used as a model by create_intermediate_table(), to build the tmp table's own tmp_table_param.
Number of temporary tables used by query.
JOIN::having_cond is initially equal to query_block->having_cond, but may later be changed by optimizations performed by JOIN.
The relationship between the JOIN::having_cond condition and the associated variable query_block->having_value is so that having_value can be:
Expected cost of windowing;.
This will force tmp table to NOT use index + update for group operation as it'll cause [de]serialization for each json aggregated value and is very ineffective (times worse).
Server should use filesort, or tmp table + filesort to resolve GROUP BY with JSON aggregate functions.
<> NULL if optimization has determined that execution will produce an empty result before aggregation, contains a textual explanation on why result is empty.
Implicitly grouped queries may still produce an aggregation row. | https://dev.mysql.com/doc/dev/mysql-server/latest/classJOIN.html | CC-MAIN-2021-43 | refinedweb | 2,632 | 64.61 |
#include <sys/stream.h> int strqget(queue_t *q, qfields_t what, unsigned char pri, void *valp);
Architecture independent level 1 (DDI/DKI).
Pointer to the queue.
Field of the queue structure for (or the specified priority band) to return information about. Valid values are one of:
High water mark.
Low water mark.
Largest packet accepted.
Smallest packet accepted.
Approximate size (in bytes) of data.
First message.
Last message.
Status.
Priority band of interest.
The address of where to store the value of the requested field.
The strqget() function gives drivers and modules a way to get information about a queue or a particular band of a queue without directly accessing STREAMS data structures, thus insulating them from changes in the implementation of these data structures from release to release.
On success, 0 is returned and the value of the requested field is stored in the location pointed to by valp. An error number is returned on failure.
The strqget() function can be called from user, interrupt, or kernel context.
Writing Device Drivers for Oracle Solaris 11.2
STREAMS Programming Guide | http://docs.oracle.com/cd/E36784_01/html/E36886/strqget-9f.html | CC-MAIN-2017-22 | refinedweb | 179 | 60.41 |
A guest post by Matthew Beale, a web developer based in Brooklyn, New York. He is a JavaScript consultant and has contributed to projects such as: Ember.js, Ember-Data, SeedFu, and Facebooker.
In June, core team member Stefan Penner released Ember App Kit (EAK), a build pipeline for Ember.js apps created around a few unique ideas. EAK is not an “official” Ember tool or “finished” project, but it is far and away the best starting point for an ambitious app. Follow along in this post to get started with the EAK, and to better understand how its features can best serve you.
EAK is strongly opinionated, and it’s unique development workflow stems from several interesting facets:
- JavaScript linting of build files.
- Unit and acceptance testing.
- A development server with catch-all routing.
- A transpiler that allows the use of ES6 modules, in combination with a module-aware resolver for Ember.js.
“JavaScript linting” is a moderately technical term for static code analysis that tries to identify and flag bugs or syntax errors in code. As your site builds in EAK, bad syntax will be flagged and errors raised. Linting provides a good first-line of defense against common errors.
Getting a test harness put together for an Ember app can still be a little tricky. EAK is based upon the modules system, which I’ll discuss later, and it is quite well-built. QUnit, with it’s simple and reliable async testing strategy, provides the test runner. Tests can be run with Karma, or right in the browser at.
The latter two features, wildcard server-side routing and modules, are less trivial to understand. I’ll walk through how each of them helps you write Ember apps more quickly, and with better architecture.
An Introduction to Using Ember App Kit
Ember App Kit has a fantastic Getting Started document, covering how to enable and use CoffeeScript, SASS/LESS/Stylus/Compass, and even Emblem. Rehashing that guide isn’t necessary here, instead I’m going to demonstrate only the simplest of steps to get rolling with EAK.
EAK is an initial set of files to start your own app, and so is not installable via a package manager. To create a project using EAK, clone the repository and destroy the .git directory included in the clone.
The file structure of the app is straightforward. I’ll mention a few specific files and paths for an overview:
Code specific to your project lives in app/. So, nothing too surprising here.
EAK uses Node.js and the Grunt library for much of its functionality, and so has several npm dependencies. So,
cd into the
my_project directory and install those dependencies.
To start a server, run tests, or build files for distribution, you will often use the
grunt command. You likely want to install it globally:
And now your app is ready to roll;
grunt -h will display a list of tasks available. The most important of these is probably
server:
From here I suggest you review the Getting Started guide for more details about installation and usage. For this article, I’m going to move forward and talk about two of the more interesting features of Ember App Kit:
- A development server with catch-all routing.
- A transpiler that allows the use of ES6 modules, in combination with a module-aware resolver for Ember.js.
Catch-all Server Routing
Ember’s default routing uses a “hash” option, based on the hashchange event. When using this API, URLs have a “#” character:
.
Many apps unilaterally use the “history” option, which is powered by the history API. This is enabled by setting an option on the router:
With the “history” option, URLs appear as normal paths in the location bar. The “cars” route would be served as
.
With most build pipelines or servers, this requires that you handle the “/cars” route explicitly. For instance, in Rails, you must map it to a route.
In EAK, there is a default wildcard route handler. It serves up your
index.html file for any request of an HTML document, so long as that path is not already provided for by a file in the
public/ directory.
So with EAK, if you navigate to and reload the page, your app will still be served up. This removes lots of frustration when developing with the history API.
Modules Part 1: ES6 Modules
The most interesting and defining feature of Ember App Kit is its module system.
EAK uses ES6 modules. Each file is wrapped in a module, so for instance:
This will become a module when the file is built:
Module names are derived from file paths. Today, ES6 modules are not supported by any browser. To circumvent this, EAK uses the ES6 Module Transpiler to convert ES6 modules into AMD modules. It converts both the
import and
export statements, so you rarely see or write AMD syntax.
Modules ensure that nothing leaks into a global namespace, like
window. They also make it possible to express dependencies between files in JavaScript. In an asset pipeline like the Rails pipeline, you express dependencies in comments. In other pipelines, you may need to edit a file specifying what order files are concatenated in. In EAK, you can use ES6 module syntax:
Car itself is only imported to this local namespace, not leaked to any global. The dependencies of this JavaScript are expressed in JavaScript, and decided at runtime. The order that files are concatenated in bears no relevance.
Using modules is future-safe (you are already using ES6 syntax), involves less server-side complexity (the server does not know about dependencies), and encourages better code practices.
Modules Part 2: Module-aware Resolver
The explicit
import statements used in my previous example could easily become unruly. Because AMD module dependencies are run-time dependencies, EAK can teach Ember how to require them on-demand.
Ember has a container that delegates the responsibility of resolving factories to the aptly named
resolver. In easier terminology, there is a resolver which is responsible for finding the classes in your app. If your app is named
App, the resolver will find your application route at
App.ApplicationRoute.
One of our goals with ES6 modules is to avoid globals. This is why each EAK file uses
export default to expose it’s exported class. The application route is not set on the
App object, and the default resolver would not find it.
The resolver, however, is just a class than can be replaced with custom behavior. EAK does exactly this with a custom resolver. Instead of looking to
App.ApplicationRoute for the application route, and EAK Ember app will load the
appkit/routes/application module.
For instance, given that
App is configured to use the EAK resolver:
Modules are named according to their paths, so overriding a generated route, controller, view, or component is as easy as creating a file.
Writing JavaScript with private namespaces and automatic class-to-file resolution is just like working with a mature server-side language. Namespaces make app development less error-prone and brittle, and encourage you to write re-usable code.
The Future of EAK
I encourage you to try Ember App Kit today, and embrace it for your next project. When the pipeline does not fit your needs, I also encourage you to edit the Gruntfile and task configuration files. EAK is a starting point, and you should not shy from modifying it for a specific need. I’ve heard of module sharing between two projects with a git submodule and modified build process, and I’ve modified the pipeline myself to build two Ember apps in the same repo.
In the future, EAK will likely support per-environment configuration and a better way to include 3rd party assets (today you must edit more than one file). The changed-file watching will get faster and individual files may be rebuilt instead of the entire tree being compiled on each change. Bower may become a harder dependency that it is today. Ember App Kit may become part of the Ember.js Starter Kit.
But if you are a developer who still remembers what coding in a mature language with namespaces is like, Ember App Kit will get you excited to start a new project today.
Be sure to look at the Ember.js resources that you can find in Safari Books Online.
Not a subscriber? Sign up for a free trial.
Juarez P. A. Filho
Hey Matthew, nice article. I just heard about EAK yesterday in Ember SK Meetup in a presentation of Rose from Zendesk which is using Ember.js a lot. I am really convinced to use EAK, actually I need to migrate my actual project using Yeoman Ember.js generator to use EAK. Do you have any recommendation about it? Besides that I think you can write an article about Ember Data using an API with a different JSON expected by Ember Data like
Thanks a lot for share!
Matthew Beale
Howdy Juarez! I haven’t used Yeoman much myself, so I can’t give you any specific tips. EAK will support the same features as Yeoman, so the transition should go smoothly.
The Ember-Data 1.0 beta has really thrown many people for a loop- and I’m in the same boat of having had a bunch of my domain specific tossed out. I’m looking forward to an excuse to explore the new APIs though, and a post might be just the ticket.
Rose
Could you perchance briefly go over what you’re referring to by “you have to edit more than one file” when including 3rd party libraries?
You might start by bower-installing or adding to vendor/, but then what’s the best path for properly integrating it into the app?
For instance, to include Ember Data, what do you have to import before classes that use it? All I can guess is you need the resolver and perhaps to bring in the App global. docs are kinda skimpy on best practices for this.
Matthew Beale
To add a new asset in EAK, you’ll need to: 1) add the file, 2) add the file to public/index.html, 3) add the file to tests/index.html. This is more steps than any of us working on the pipeline would prefer to have. It’s easy to forget the tests file, or have an inconsistent order by mistake.
Ember-Data would need to be a script tag after jquery and Ember itself. The loader is only used by your application code, not by Ember or Ember-Data themselves. Today, the libraries still just add themselves to the global scope. | https://www.safaribooksonline.com/blog/2013/09/18/ember-app-kit/ | CC-MAIN-2016-36 | refinedweb | 1,788 | 64.91 |
#include <Wt/WTableRow>
A table row.
A WTableRow is returned by WTable::rowAt() and managing various properties of a single row in a table (it is however not a widget).
A table row corresponds to the HTML
<tr> tag.
Creates a new table row.
Table rows must be added to a table using WTable::insertRow() before you can access contents in it using elementAt().
Access the row element at the given column.
Like WTable::elementAt(), if the column is beyond the current table dimensions, then the table is expanded automatically.
The row must be inserted within a table first.
Returns the row height.
Hides the row.(). The auto-generated id is created by concatenating objectName() with a unique number.
Reimplemented from Wt::WObject.
Returns whether the rows is hidden.
Returns the row number of this row in the table.
Returns -1 if the row is not yet part of a table.
Sets the row height.
The default row height is WLength::Auto.
Sets the CSS Id.
Sets a custom Id. Note that the Id must be unique across the whole widget tree, can only be set right after construction and cannot be changed.
Sets the CSS style class for this row.
The style is inherited by all table cells in this row.
Shows the row.
Returns the CSS style class for this row.
Returns the table to which this row belongs. | https://webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1WTableRow.html | CC-MAIN-2021-31 | refinedweb | 231 | 79.26 |
>>.
Preparing for Text Messaging
When you're on the go and scheduled meeting times are approaching, receiving helpful text messages is often more useful than email reminders. I've always known that text (or SMS) messaging would play a useful part in Meeting Planner..
If you haven't yet, please try out Meeting Planner right now by scheduling your first meeting. Feel free to post feedback about your experience in the comments below.
I do participate in the comment threads, but you can also reach me @reifman on Twitter. I'm always open to new feature ideas and topic suggestions for future tutorials.
As a reminder, all the code for Meeting Planner is written in the Yii2 Framework for PHP. If you'd like to learn more about Yii2, check out my parallel series Programming With Yii2. The more I build out Meeting Planner, the more impressed I am with Yii2 and their team of volunteers.
Choosing an SMS Provider
The easiest way to send text messages from your application is to subscribe to a service. Just as I use Mailgun for Meeting Planner's inbound and outbound email, I'll need an SMS provider to deliver text messages.
The two most prominent services I looked at were Twilio and Plivo. Both seemed like competent providers, but Twilio had broader services, richer documentation, and top-level user experience.
Here's a screenshot from Twilio's SMS product page:
Twilio offers such an array of services that you do have to dive in a bit to find SMS:
Plivo also seemed like a good choice, but its website, documentation and API didn't seem to be quite as sophisticated as Twilio:
However, Plivo is a lot cheaper than Twilio; specifically, it offers free inbound SMS:
I decided to go with Twilio for my initial SMS implementation, but to modularize the features so I could easily switch them to a different provider.
I do have some concerns about the costs of texting in Meeting Planner as the audience scales. Will I offer SMS for free to all users even before there is a revenue stream or investors?
At the early alpha stage, this wasn't a top concern. Again, I'm still focused on delivering the best MVP I can for the beta release.
Getting Started With Twilio
Registering with Twilio is easy:
As a sophisticated communication services provider, they implement SMS verification in their registration process:
The SMS Dashboard
Once verified, you land on a friendly, well-designed dashboard:
Gathering Our Credentials
First, I accessed the account ID and token from the API Credentials page:
I made note of these for later integration with Meeting Planner.
Obtaining a Phone Number
Twilio provides you a phone number from which you can send SMS from your application:
I chose a number with a Seattle area code, where Meeting Planner is based:
Then, using Twilio, I sent my first test message:
The message arrived very quickly on my phone.
Thinking About Incoming Messages
Thinking beyond the MVP, incoming message capability would be great for Meeting Planner. For example, you could text that you're running late or need a convenient link to directions for your phone's navigation app. Currently, you have to click through to the web to the meeting invitation to do this.
Twilio offers a rich set of services for responding to inbound texts, including a texting markup language called TwiML.
For the moment, I'm not going to worry too much about inbound messages. However, anytime people text your Twilio number, you are charged; in other words, it's ripe for abuse.
Let's look at a couple of easy ways to manage costs.
Controlling Costs
For alpha and beta testing, I am limiting text support to North American phone numbers. This will keep costs a bit lower. Twilio offers a built-in way to filter by geography:
Twilio also provides Messaging Services which you can configure to behave in specific ways tailored for your application, including blocking all SMS:
As you can see, they also see inbound text spam and abuse as a weakness in the general SMS platform (not theirs) which they are thoughtful about.
Integrating Twilio Into Meeting Planner
Next, I wanted to get the basic SMS functionality operating within Meeting Planner.
Finding a Yii Extension for Twilio
It turns out there are several available extensions for Twilio with the Yii Framework. I decided to install Filip Ajdačić's YII2 wrapper for Twilio PHP SDK (GitHub) because his name was the most unusual (just kidding, his extension seemed to be regularly maintained).
I added the extension to composer.json. As it's technically in development mode, this worked better than directly requiring the extension:
"filipajdacic/yii2-twilio": "dev-master"
Then, I updated the environment:
$ composer update Loading composer repositories with package information Updating dependencies (including require-dev) - Removing ezyang/htmlpurifier (v4.7.0) - Installing ezyang/htmlpurifier (v4.8.0) Downloading: 100% - Installing twilio/sdk (4.10.0) Downloading: 100% - Installing filipajdacic/yii2-twilio (dev-master 7d547a0) Cloning 7d547a0a47c9864f2e8b5fb5f43748fbd24fc4b1 Writing lock file Generating autoload files
I wasn't too worried about its development status because it's a relatively simple, straightforward extension that just activates the Twilio API.
Adding the Credentials
First, I added the keys from above to my initialization files:
twilio_sid = "ACxxxxXXxxxxxXXxxxXXxxxxxxxxxxxe1" twilio_token = "d3xxxxXXxxxxxXXxxxXXxxxxxxxxxxx41" twilio_number = "1206XXXYYYY" # for next episode #twilio_service_sid = "MxxxxXXxxxxxXXxxxXXxxxxxxxxxxxGf6"
Then, I added registration of the component in /frontend/config/main.php:
return [ 'id' => 'mp-frontend', 'name' => 'Meeting Planner', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'controllerNamespace' => 'frontend\controllers', 'components' => [ ... 'Yii2Twilio' => [ 'class' => 'filipajdacic\yiitwilio\YiiTwilio', 'account_sid' => $config['twilio_sid'], 'auth_key' => $config['twilio_token'], ], 'log' => [ ...
I also found it best to place a few of the variables in common\config\params-local.php for easier access across the application:
<?php return [ ... 'sms_number' => '1206XXXYYYY', 'twilio_service_id' => 'MGXXXXXYYYYZZZZ11134446', 'twilio_test_number' => '1-206-NNN-QQQQ', ];
Building an SMS Model
Then I built an Sms.php model to use programmatically when texts were needed:
<?php namespace common\models; use Yii; use yii\base\Model; use frontend\models\UserContact; class Sms { private $sms; private $service_id; private $mp_number; private $test_number; function __construct() { $this->sms = Yii::$app->Yii2Twilio->initTwilio(); $this->mp_number = Yii::$app->params['sms_number']; $this->service_id = Yii::$app->params['twilio_service_id']; $this->test_number = Yii::$app->params['twilio_test_number']; } public function transmit($user_id,$body='') { // to do - lookup usercontact to sms // see if they have a usercontact entry that accepts sms // transmit $to_number = $this->test_number; $to_number = $this->findUserNumber($user_id); if (!$to_number) { return false; } try { $message = $this->sms->account->messages->create(array( "From" => $this->mp_number, "To" => $to_number, // Text this number 'MessagingServiceSid' => $this->service_id, "Body" => $body, )); } catch (\Services_Twilio_RestException $e) { echo $e->getMessage(); } }
Initially,
findUserNumber() was a stub, and
transmit() would only send to a test number in params-local.php, my personal cell phone.
Here's some test code which I used to send my first message from Meeting Planner:
$user_id = 1; $s = new \common\models\Sms(); $s->transmit($user_id,'First test from Meeting Planner codebase!');
Here are the results:
Note: yeah, I know I should charge my phone—but it's really the iPhone 6's poor battery life that's the problem.
So, that's how you get signed up for Twilio and implement basic functionality.
Looking Ahead
In the next episode, we'll explore actual integration of SMS with Meeting Planner. Here are some questions that will come up:
- How will people provide their phone numbers for texting?
- Which Meeting Planner features should use SMS for notifications and delivery?
- How will people decide what they want to receive texts from Meeting Planner for?
- Will Meeting Planner process inbound texts and respond to them?
- How will I control SMS costs and prevent abuse during the MVP stage of the startup?
- What would it take to switch to Plivo to lower costs?
As always, please stay tuned for more upcoming tutorials in the Building Your Startup With PHP series. As former Presidential candidate Donald Trump used to say, "We are going to win, win so much you'll get tired of winning. You'll say, 'Please Jeff, stop winning'. And I'll say, 'No, sorry, get comfortable, there will be more ongoing winning.'"
Have you scheduled a meeting via Meeting Planner yet? No? Go! Do it. Do it now! And as always, let me know what you think below or in the comments. I appreciate it. I can't keep winning without your help.
Related Links
><< | https://code.tutsplus.com/tutorials/building-your-startup-preparing-for-text-messaging--cms-26912 | CC-MAIN-2021-17 | refinedweb | 1,393 | 52.09 |
Today I've learned some concepts about Pointer in C++ and I have a confusion in this code snippet and its result.
Source Code:
And this is the result:And this is the result:Code:// Pointer array #include <iostream> using namespace std; void main () { char * say = "Hello"; // cout << "say = " << say << endl; cout << "&say = " << &say << endl; cout << "*say = " << *say << endl; cout << "say[1]=" << say[1] << endl; cout << "*(say+1)=" << *(say+1) << endl; // cout << endl << endl; for (int i=0; i<5; i++) { cout << "say["<< i <<"]=" << say[i] << endl; } // cout << endl << endl; for (int i=0; i<5; i++) { cout << "&say["<< i <<"]=" << &say[i] << endl; } }
I try to understand why it gave this result, but I cannot understand the section in bold.I try to understand why it gave this result, but I cannot understand the section in bold.Code:say = Hello &say = 0012F3A4 *say = H say[1]=e *(say+1)=e say[0]=H say[1]=e say[2]=l say[3]=l say[4]=o &say[0]=Hello &say[1]=ello &say[2]=llo &say[3]=lo &say[4]=o
Please explain it for me.
Thanks very much,
Nichya. | http://cboard.cprogramming.com/cplusplus-programming/123299-pointer-confusion-please-explain.html | CC-MAIN-2014-15 | refinedweb | 189 | 66.61 |
I came across Apache Tika a few weeks ago, a service that will tell you what pretty much any document type is based on it’s metadata, and will have a good go at extracting text from it.
With a prompt and a 101 from @IgorBrigadir, it was pretty easier getting started with it – sort of…
First up, I needed to get the Apache Tika server running. As there’s a containerised version available on dockerhub (logicalspark/docker-tikaserver), it was simple enough for me to fire up a server in a click using tutum (as described in this post on how to run OpenRefine in the cloud in just a couple of clicks and for a few pennies an hour; pretty much all you need to do is fire up a server, start a container based on logicalspark/docker-tikaserver, and tick to make the port public…)
As @IgorBrigadir described, I could ping the server on curl -X GET and send a document to it using curl -T foo.doc.
His suggested recipe for using python requests library borked for me – I couldn’t get python to open the file to get the data bits to send to the server (file encoding issues; one reason for using Tika is it’ll try to accept pretty much anything you throw at it…)
I had a look at pycurl:
!apt-get install -y libcurl4-openssl-dev
!pip3 install pycurl
but couldn’t make head or tail of how to use it: the pycurl equivalant of curl -T foo.doc can’t be that hard to write, can it? (Translations appreciated via the comments…;-)
Instead I took the approach of dumping the result of a curl request on the command line into a file:
!curl -T Text/foo.doc > tikatest.json
and then grabbing the response out of that:
import json
json.load(open('tikatest.json',encoding='utf-8'))[0]
Not elegant, and far from ideal, but a stop gap for now.
Part of the response from the Tika server is the text extracted from the document, which can then provide the basis for some style free text analysis…
I haven’t tried with any document types other than crappy old MS Word .doc formats, but this looks like it could be a really easy tool to use.
And with the containerised version available, and tutum and Digital Ocean to hand, it’s easy enough to fire up a version in the cloud, let alone my desktop, whenever I need it:-) | https://blog.ouseful.info/2015/02/06/quick-note-apache-tika-document-text-extraction-service/ | CC-MAIN-2020-50 | refinedweb | 419 | 60.08 |
On 15 June 2012 23:45, Johan Tibell <johan.tibell at gmail.com> wrote: > Hi, > >). +1 I like the idea of the vector-safe package. Are you also proposing to add this package to the HP? (I would also be +1 on that) I see that the trustworthiness of the .Safe modules is conditional on whether bound checking is enabled in vector: #if defined(VECTOR_BOUNDS_CHECKS) {-# LANGUAGE Trustworthy #-} #endif The VECTOR_BOUNDS_CHECKS pragma would not be directly available in vector-safe. But I guess, by using the install-includes cabal field, vector can export a header file that exports this symbol when bound checking is enabled. | http://www.haskell.org/pipermail/libraries/2012-June/018016.html | CC-MAIN-2014-35 | refinedweb | 104 | 67.65 |
Shawn Hargreaves Blog
Variants of the following question come up somewhat regularly on the XNA forums:
You already have the tools to answer this yourself. Here's how:
Fire up Visual Studio and create a new Console Application project.
Right-click on the References node, and add the Microsoft.Xna.Framework.Content.Pipeline assembly.
Add using declarations for the System.Xml and Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate namespaces.
Add a test class with the same layout as whatever data you want to serialize, but initialized with dummy test values. For instance:
namespace XmlTest
{
class MyTest
{
public int elf = 23;
public string hello = "Hello World";
}
}
Add this code to Main:
MyTest testData = new MyTest();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("test.xml", settings))
{
IntermediateSerializer.Serialize(writer, testData, null);
}
Run the program. Look in the bin\Debug folder, and open the test.xml output file. With the class shown above, this will look like:
<?xml version="1.0" encoding="utf-8"?>
<XnaContent>
<Asset Type="XmlTest.MyTest">
<elf>23</elf>
<hello>Hello World</hello>
</Asset>
</XnaContent>
Tada! That's how IntermediateSerializer represents this particular class in XML.
2011 update: as of XNA 4.0 you must change your project to target the full .NET Framework, as opposed to the Client Profile, before adding the Content Pipeline assembly reference. Nick has details.
I wanted to be able to build my spritesheets in my editor to do this I need a way to compile the spritesheet from a WinForms App into an .xnb file...
Any pointers would be good :-)
dna8088: have you looked at this sample?
Thanks for the link, But...
"Note also that the XNA Framework redistributable installer does not include the Content Pipeline."
That's a bit of a showstopper if I wanted to distribute my editor with image compiler feature :-(
That seems kinda odd, writing a class first with all the info you need in your app to convert it into xml and open the xml again
I would imagine that the point is you can load your class in-game then fill it with the neccessary data and serialise it after its all updated...
Justin: I think this was an exercise to get an idea of how the XML should be formed and not an example of how to build an app to write out the XML. Granted, you could do it just like this and just have your editor instantiate all of the objects before writing them out, but you can just as easily have your editor (or game designer) write out XML using a different method (such as Notepad).
I'm currently trying to do the exact opposite, and use my xml spriteSheets from the XNA sample with the Winforms content loader example to build a map editor. I can't get the program to recognise the custom processor.
Tried:
"SpriteSheetProcessor"
and
"Microsoft.Xna.Framework.Content.Pipeline.SpriteSheetProcessor" + xnaVersion
I've added the references but can't seem to make it work and can't find the any answer on the forums.
Is there an example of combining the Winforms Content Loader example with the spritesheets example? Is it possible?
Actually, I am trying to understand now the relevance of these codes and how to apply them on my own. I am a fresh computer science student and I am currently learning the basic programming languages like C. Also, our teacher wants us to give her an essay explaining the internal processes going on behind the programming language.
As a profession i am a dentist but i have a lot interest in web programming so i am start learning coding and other language to make my site more competent.
Hello! I would imagine that the point is you can load your class in-game then fill it with the necessary data and serialize it after its all updated.
For this to work, the full ".NET Framework 4.0" as target framework is needed. When using ".NET Framework 4.0 Client Profile" the code can't be compiled.
exactly what i was looking for! been struggling at making my data from scratch on my my own. cheers
This info is available in a million places and everyone who has an error "at all" seems to get pushed to one of the many blogs with this information. I have yet to see someones issue actually get solved by one of these blog posts...sorry to vent here, just sick of reading this exact same info on 20 different blogs...
Hi Blah,
I can assure you the technique described in this article absolutely does work to discover what format XML should be used to deserialize into any custom type using IntermediateSerializer.
If your problem is something other than that, obviously this article will not help you. Afraid there's not much I can do to help you there, since you don't say what problem you are having!
I didnt understand anything from this code, seems broken | http://blogs.msdn.com/b/shawnhar/archive/2008/08/12/teaching-a-man-to-fish.aspx | CC-MAIN-2015-14 | refinedweb | 833 | 64.71 |
Introduction: Amazon Echo Controlled IR Remote
The Amazon Echo system can control a lot of aspects of a smart home, but a smart outlet can only turn off and on. Many devices do not instantly turn on by simple being plugged in and require additional steps, such as pressing buttons on a remote or the physical device to power on or get the desired settings.
In this guide, a Raspberry Pi Zero W will be configured to act as a smart home device that can be controlled by Amazon Echo, and send any desired IR commands to a device when requested to power on or off.
In this specific case, the Pi will be configured to learn the IR commands of a remote provided with a "ClassicFlame 23II310GRA 23" Infrared Quartz Fireplace Insert". An IR LED will then be used to send out the IR commands on demand, and finally the Pi configured to emulate a Philips Hue device that can be control be Echo.
Step 1: Materials
Required:
- Raspberry Pi Zero Z
- 4 GB or greater Micro SDHC Class 10 memory card (16 GB Example)
- MicroUSB
- 1 IR LED
- MicroUSB Power Adapter (2.1 amps or higher recommended)
- IR LED
- IR Receiver VS/1838B
- 100 ohm resistor
- Misc. wire
Recommended:
- Headphone Jack
- 1/8 inch headphone/audio wire
- 2N2222 NPN Transistor
- 1k ohm resistor
- Rapsberry Pi Zero Case
To complete the initial configuration of a Raspberry Pi Zero W, a few additional peripherals will be required, but will not be in use full time by the completed project
- Mini HDMI to HDMI Adapter: Used to connect Pi Zero W to a TV or monitor with a full sized HDMI cable
- USB OTG Cable: Used to convert from micro-USB to full sized USB port(s) for connecting a keyboard and/or mouse
- HDMI Cable: Used to connect to TV or monitor along with an adapter to mini HDMI
The first two items as well as a case are included various Pi Zero starter kits, such as: MakerSpot Mega Kit
Step 2: Setup Raspberry Pi
The Raspberry Pi website has an excellent walkthrough for setting up Raspbian OS on a Raspberry Pi. If you wish to have more Operating System options in the future, or a more simple setup, following the instructions for NOOBS will get you up and running in no time. This guide is based on Raspbian, which is included with NOOBS...
Once Raspbian is running, enable SSH to allow remote connections to the device without needing a monitor/keyboard/mouse to be connected directly to the Pi. If you would like to optionally have remote access to the GUI, you can also enable VNC access...
It is also highly recommended you set a static IP on the wireless network configuration so it does not change over time. It is possible the IP may not change if new devices are not regularly connected to the wireless network, but configuring it as static will ensure it does not....
Step 3: Learning IR Codes
The following steps are highly based on the excellent guide found here:...
The Linux Infrared Remote Control (LIRC) library is used to handle receiving IR commands through the receiver module, saving them to a file, and then sending the commands when desired through the IR LED.
The first step is to record the IR signals from our existing remote using the IR Receiver and saving them to a file. The IR Receiver is only needed initially to learn the IR signals and then could be removed, so a temporary connection could be used.
Connect the IR Receiver to the Raspberry Pi. Use the attached picture to identify the VCC, GND, and Signal pins. Using a breadboard, hookup wires, or creative bending of the pins to the following connections
VCC connects to 5 volt pin
GND to a ground pin
Signal to Pin 23
Power on and connect to the Raspberry Pi through either by opening the terminal on the local device, or creating an SSH connection using a program such as Putty for Windows. The remaining steps will be typed into the command line interface
Install LIRC
sudo apt-get install lirc
Add required information to the modules file
sudo nano /etc/modules
Add the following lines to the end of the file
lirc_dev
lirc_rpi gpio_in_pin=23 gpio_out_pin=22
When finished, press CTRL+X, then Y, then Enter to exit and Save
Create/Modify the hardware.conf file with the following data
sudo nano /etc/lirc/hardware.conf
Copy and paste, or modify to contain the following lines:
# =""
When finished, press CTRL+X, then Y, then Enter to exit and Save
Modify config.txt so the LIRC kernel module is loaded on boot. Add to the end of the file.
sudo nano /boot/config.txt
dtoverlay=lirc-rpi,gpio_in_pin=23,gpio_out_pin=22
When finished, press CTRL+X, then Y, then Enter to exit and Save
Reboot RaspberryPi
sudo shutdown -r now
Test IR Receiver by stopping LIRC and monitoring the input. First LIRC will be stopped
Raspbian 8 Jessi: sudo /etc/init.d/lirc stop
Raspbian 9 Stretch: sudo systemctl stop lircd
Optional:Mount the LIRC device to confirm any input can be received. You may need to restart the Pi after this test is completed to make it available for later steps.
mode2 -d /dev/lirc0
Aim an IR remote control at the receiver and press a button and ensure data appears on the screen
CTRL+C to stop
At this point, the LIRC program is installed and we are able to view IR information. Now, either a remote profile can be downloaded from the LIRC website, or a custom profile can be created with your own remote.
During this process, you will enter the name of the key you are recording. Only valid names are allowed, so run the following command to view all available names
irrecord --list-namespace
Example: I used the name KEY_POWER when I recorded the Power button on my remote and KEY_TIME when recording the timer button.
If more than a few keys are being recorded, I recommend documenting the key names used and what button they map to, as there may not be a perfect name for the button being recorded. This will make it easier to reference in the future.
Generate a Remote Configuration file
# Stop lirc to free up /dev/lirc0
Raspbian 8 Jessi: sudo /etc/init.d/lirc stop
Raspbian 9 Stretch: sudo systemctl stop lircd
# Create a new remote control configuration file (using /dev/lirc0) and save the output to ~/lircd.conf
irrecord -d /dev/lirc0 ~/lircd.conf
Follow the directions on the screen. Once the record is initialize, enter the key name you are going to used, and then press the button on the remote while pointing it at the receiver until several dots appear. Repeat this step for each button on the remote you wish to record.
# Make a backup of the original lircd.conf file
sudo mv /etc/lirc/lircd.conf /etc/lirc/lircd_original.conf
# Copy over your new configuration file (Replace myremote with the name you gave during the configuration)
sudo cp ~/myremote.lircd.conf /etc/lirc/lircd.conf
# Start up lirc again
Raspbian 8 Jessi: sudo /etc/init.d/lirc start
Raspbian 9 Stretch: sudo systemctl start lircd
At this point, remote codes have been recorded to a file.
Step 4: Headphone Jack (Optional)
To make running wires and modifying the Raspberry Pi more modular, I hot glued a 1/8 inch headphone audio jack to the case and connected wires to the jack. Headphone wires with the matching plug were used to connect the IR LED, so this wire could be routed to an inconspicuous locate to point at the IR receiver of the device I wanted to connect, but could easily be unplugged from the Pi without needing to remove all of the wires.
This is purely optional, but has come in handy.
Step 5: Connecting IR LED (Quick)
Connecting the IR Emitting LED to the Raspberry Pi can be done multiple ways. This step shows the quick way I connected it, but which I found out later can exceed the current limit on the Pi's pins. So far I have not run into any problems, but a more ideal way of connecting is described in the next step
Calculate the resistor needed for your IR LED. can assist with determining the proper resistor value if you have all specifications of your LED. In this case, the voltage of pin 22 is 3.3 volts, the LED voltage drop is 1.2 volts, current rating is 20 ma, and 1 LED was used, resulting in a value of 110 ohm resistor needed. I used a single 100 ohm resistor.
Note: It was later brought to my attention that the max current of all pins at any given time is 16 ma, so this configuration could exceed that. A better configuration with a transistor and 5 volt supply is described in the next step, but after several weeks of running in this configuration, I have not encountered any problems yet.
Pin 22 on the Raspberry Pi will be connected to the anode of the IR LED, which is the longer leg by default.
The shorter pin of the LED connects to the resistor and then to the ground pin. I cut off most of the wire on the resistor and soldered it directly to a ground pin and to the ground wire going to the LED.
Step 6: Connecting IR LED (correct Method)
To properly connect the LED without exceeding the draw limit of the Raspberry Pi, connect the LEDs to the 5 volt supply with appropriate resistor, connect the cathode pin to the collector pin of a 2N2222 resistor, connect the Emitter pin of the transistor to ground, and connect pin 22 of the Pi to a 1K ohm resistor to the base pin of the transistor. This allow a very small current from pin 22 to connect the LED to ground, completing the circuit without over drawing the Pi.
In my example, I wired up 2 IR LEDs, so I could control ambient lighting as well as the electric fireplace.
Step 7: Testing Sending IR Commands
To send an IR command, the program irsend is used.
Syntax: irsend
Example: irsend SEND_ONCE Spectrafire KEY_POWER
This sends the power button command from the Spectrafire remote once. Replace Spectrafire with whatever you named your remote. Repeat with other key names used when recording the file.
At this stage, you are able to send any commands previously recorded using the IR LED connected to the Raspberry Pi.
Step 8: Installing Ha-bridge
To allow the Echo to be able to control our device, we will emulate a Philips Hue bulb using ha-bridge. Once configured, the Echo will be able to detect this device and send power on/off commands to it.
The website for ha-bridge clearly outlines the process for the current version and is highly recommended to review.
Install HA-Bridge
sudo apt-get install oracle-java8-jdk
mkdir /home/pi/habridge
cd /home/pi/habridge/
wget
Rename file and run HA-Bridge
mv ha-bridge-4.5.6.jar ha-bridge.jar
sudo java -jar /home/pi/habridge/ha-bridge.jar
To setup ha-bridge to run on startup using Systemctl
cd /etc/systemd/system
sudo nano habridge.service
Copy and paste the following lines
[Unit]
Description=HA Bridge
Wants=network.target
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/pi/habridge
ExecStart=/usr/bin/java -jar -Dconfig.file=/home/pi/habridge/data/habridge.config /home/pi/habridge/ha-bridge.jar
[Install]
WantedBy=multi-user.target
Save and Exit (CTRL+X then Y and Enter)
Reload system control
sudo systemctl daemon-reload
Start the service
sudo systemctl start habridge.service
Configure service to start on boot
sudo systemctl enable habridge.service
Step 9: Emulating a Philips Hue Bulb
With ha-bridge running, open a web browser and enter the IP address of the Raspberry Pi, and the interface for ha-bridge should appear.
Click the Add/Edit link at the top of the page
Name: Enter the name you want to use when speaking commands
At the section labeled "On Items" set the type "Execute Command/Script/Program and enter the command in the Target Item box. If multiple commands are desired, click the Add button to save the current line and enter another command. It is also possible to set a delay and repeat a command a certain number of times. In this case, the power button needed pressed first, then the Timer button pressed 3 times to set the auto-off timer for 3 hours.
Repeat the same idea for the "Off Items" area, clicking Add when finished.
At the top of the page, click "Add Bridge Device" to save it as a new item, or Update Bridge Device if modifying an existing one.
Aim the IR LED at the device. On the Bridge Devices page, click the Test ON or Test OFF button to verify it is acting as desired.
Step 10: Connecting to Amazon Echo
The last step is to allow the Amazon Echo to communicate with this device. Note: Both devices must be the same network.
Option 1) say "Alexa, discover smart home devices"
Option 2) Open the Alexa app, tap on Menu>Smart Home and click the "Discover Devices" link
After a few moment, the device should be recognized.
Speak, "Alexa, turn the bedroom fireplace on" and verify that the device turns on as expected. Replace Bedroom Fireplace with whatever you name your device in ha-bridge. Repeat the process to turn off the device.
If you haven't mounted the IR LED yet, find an inconspicuous place to mount it while allowing it to point in the general direction of the IR receiver in the device. You may need to move it around to point at different areas to find the best location.
Recommendations
We have a be nice policy.
Please be positive and constructive.
Tips
Questions
This project is exactly what I'm looking for. I want to control an ir remote for my fan and have Alexa turn my Xbox "on" as part of my morning routine. Forgive my noobiness, but would you please either post or email a complete schematic of the project (including the transistor powered ir transmitters)? I appreciate the pictures in the project but I'm not clear on what I'm looking at, and I don't understand what the transister is "doing" in the circuit. Thanks so much for posting this project - I have the parts - just hoping for a little more assurance! Thanks again!
Nice controller design. You've got my vote. | http://www.instructables.com/id/Amazon-Echo-Controlled-IR-Remote/ | CC-MAIN-2018-17 | refinedweb | 2,462 | 58.32 |
The previous post showed that the bits of prime powers look kinda chaotic. When you plot them, they form a triangular shape because the size of the numbers is growing. The numbers are growing geometrically, so their binary representations are growing linearly. Here’s the plot for powers of 5:
You can crop the triangle so that you just see a rectangular portion of it, things look less regular. If we look at powers of p modulo a power of 2, say 232, then we’re chopping off the left side of the triangle.
Suppose we don’t start with 1, but start with some other number, call it a seed, and multiply by 5 every time. Would we get a chaotic pattern? Yes, and we have just invented the congruential random number generator. These RNGs have the form
xn+1 = a xn mod m
The RNG we implicitly described above would have a = 5 and m = 232. This is not a good choice of a and m, but it’s on to something. We can use different values of multiplier and modulus to make a decent RNG.
The RANDU random number generator, commonly used in the 1960’s, used a = 65539 and m = 231. This turned out to have notoriously bad statistical properties. We can see this with a small modification of the code used to produce the plot above.
def out(s): s = s.replace('1', chr(0x2588)) s = s.replace('0', ' ') print(s) a, m = 65539, 2**31 x = 7 for i in range(32): x = a * x % m s = format(x, '32b') out(s)
Here’s the plot.
The pattern on the right side looks like a roll of film. This shows that the lowest order bits are very regular. You can also see that we need to start with a large seed: starting with 7 created the large triangular holes at the top of the image. There are other patterns in the image that are hard to describe, but you get the sense something is not right, especially when you compare this image to a better alternative.
A much better choice of parameters is multiplier a = 48271 and modulus m = 231 -1. These are the parameters in the MINSTD random number generator. Here’s a plot of its bits, also starting with seed 7.
The MINSTD generator is much better than RANDU, and adequate for some applications, but far from state of the art. You could do better by using a much larger multiplier and a modulus on the order of 264 or 2128.
You could do even better by adding a permutation step to your congruential generator. That’s the idea behind the PCG (permuted congruential generator) family of random number generators. These generators pass all the standard statistical tests with flying colors.
There are many other approaches to random number generation, but this post shows one thread of historical development, how hypothetically someone could go from noticing that prime powers have chaotic bit patterns to inventing PCG. | https://www.johndcook.com/blog/2021/04/29/reinventing-rng/ | CC-MAIN-2021-31 | refinedweb | 504 | 63.59 |
In last week’s tutorial we set up the Model layer of this registration flow, which included the
User,
Role, and
Assignment models, as well as Unit Tests to assert that the correct business logic was being enforced correctly.
Registration is a unique aspect of building an application that involves processes and rules that only apply when the user is first signing up to your application.
A good way of encapsulating these special types of processes is through Form Objects. We’ve previously looked at Form Objects in Rails in Using Form Objects in Ruby on Rails and Using Form Objects in Ruby on Rails with Reform.
In today’s tutorial we’re going to pick up where we left off last week by adding a Form Object for encapsulating the registration flow. If you missed last week’s post, I would encourage you to read that post before continuing with this post.
What are we going to build?
Before we get into the code, first I will quickly outline what we’re going to be building in today’s tutorial.
The registration process is a unique part of your application in that it will probably have validation rules that only apply in this one circumstance.
For example, you might require that the user confirms their password by typing it twice, or that they have checked the box to agree to your terms and conditions.
You might also want to create additional models when the user is created for an account or subscription. In my case, I want to automatically assign the user to the
guest role.
A naive approach to trying to solve this problem is to add this functionality to the
User model. But as you can see, we will end up adding extraneous validation rules and additional responsibility to the
User Model where it shouldn’t be concerned.
Instead, we can encapsulate this functionality in a Form Object. The Form Object will deal with the business rules of registering as a new user, and will handle creating any additional models and relationships. This will also make it very easy to come back to this process at some point in the future because it will be immediately obvious where the responsibility for the registration process lies.
So with that brief introduction out of the way, lets get down to building the registration Form Object!
Adding the Reform Gem
As I mentioned in Using Form Objects in Ruby on Rails with Reform, I prefer to use Reform as the base of my Form Objects instead of rolling my own. I tend to find that Open Source projects have already dealt with the edge-cases I’m inevitably going to stumble across at some point in the future.
So the first thing to do is to add Reform to the project. Add the following two Gems to your
Gemfile:
gem "reform" gem "reform-rails"
And then run the following command in Terminal to install them:
bundle install [/bash] ## Setting up the Form Object Next we need to add the Form Object and the associated Unit Test files. Create a new directory called `forms` under `app` and then create a new file called `register_form.rb`: ```ruby class RegisterForm < Reform::Form end
As you can see, this class should inherit from
Reform::Form.
Next create a new directory called
forms under the
test director and then create a new file called
register_form_test.rb:
require "test_helper" class RegisterFormTest < ActiveSupport::TestCase def setup @user = User.new @form = RegisterForm.new(@user) end end
Dealing with validation
The first responsibility of the register form is to ensure that the correct properties have been sent via the request. In this example we’re only going to be requiring an email address and a password.
So first up we can write a test to ensure that those properties are required:
require "test_helper" class RegisterFormTest < ActiveSupport::TestCase def setup @user = User.new @form = RegisterForm.new(@user) end test "email should be required" do @form.validate({}) assert_includes(@form.errors[:email], "can’t be blank") end test "password should be required" do @form.validate({}) assert_includes(@form.errors[:password], "can’t be blank") end end
Now if you run the following command in Terminal, you will see both of those tests fail:
bin/rake test test/forms/register_form_test.rb [/bash] To make these tests pass, we can tell the `RegisterForm` class to require these properties: ```ruby class RegisterForm < Reform::Form property :email property :password validates :email, presence: true validates :password, presence: true end
Here I’ve added the two properties to the form and then I’ve added validation rules to both to ensure that they are both required.
Now if you run those tests again, you should see them pass.
Next we need to assert that the value that has been provided for the email property is in fact a valid email address.
To make this assertion, we can add the following test:
test "email should be a valid email address" do @form.validate(email: "invalid") assert_includes(@form.errors[:email], "is not an email") end
And once again, we can run this test to watch it fail. With a failing test in place, we can add the validation rule to make it pass:
class RegisterForm < Reform::Form property :email property :password validates :email, presence: true, email: true validates :password, presence: true end
Here I’m using the
And finally we can add a test to assert that the email address that has been provided is unique:
test "email should be unique" do create(:user, email: "name@domain.com") @form.validate(email: "name@domain.com") assert_includes(@form.errors[:email], "has already been taken") end
As you can see, first I create a new user in the database with a given email address by using the Factory Girl
create method.
Next I pass the same email into the form and then assert that the correct error has been set.
To make this test pass we can add the
unique validation rule to the Form Object:
require "reform/form/validation/unique_validator.rb" class RegisterForm < Reform::Form property :email property :password validates :email, presence: true, email: true, unique: true validates :password, presence: true end
Notice how I’m requiring Reform’s unique validator? This provides a better way to check for uniqueness than the default Active Record method.
Dealing with the save process
Now that we’ve got those basic validation rules out of the way, we can turn our attention to the actual process of saving the new user.
Normally if you didn’t have to deal with any other business rules you would be done with the Form Object. But in this case, I want to automatically assign the user to the
guest role.
A good way of dealing with this is to override the
save method on the form to provide our own custom behaviour.
But first, we will write a test that asserts the behaviour we’re looking for:
test "should create new unconfirmed guest user" do @form.validate(email: "name@domain.com", password: "password") assert(@form.save) assert_not(@user.confirmed?) end
If you run the tests again, you will see them all pass. By default Reform will take the supplied parameters and call save on the Model for us, therefore everything in this test should pass.
But we also need to assert that the user has a given role. To make this assertion we can add the following extra line to this test:
test "should create new unconfirmed guest user" do @form.validate(email: "name@domain.com", password: "password") assert(@form.save) assert_not(@user.confirmed?) assert(@user.role?(:guest), "user does not have the role of :guest") end
Here I’m asserting that the user has a role of
:guest. If you run these tests again you should see this assertion fail.
With the failing assertion in place we can now add the code to make it pass.
First we can add our own
save method to the
RegisterForm:
def save sync model.save end
In this method first I’m calling the
sync method to sync the properties of the form to the
model instance.
Next I’m calling
save on the
model to save the properties.
Here we’ve effectively replicated what was going on in the form before we overide the
save method. If you run the tests again you should get the same error as before.
So now we’ve overridden the
save method, we now have a place to assign the role to the user:
require "reform/form/validation/unique_validator.rb" class RegisterForm < Reform::Form property :email property :password validates :email, presence: true, email: true, unique: true validates :password, presence: true def save sync model.roles << Role.find_by(name: :guest) model.save end end
Now if you run the tests again, you should see them still fail! The reason why the test is still failing is because we need to seed the database with the
guest role.
First create a new file under
test/factories called
role.rb:
FactoryGirl.define do factory :role do name Faker::Lorem.word end end
Here I’m just setting the default name of the Role to a random work from
Faker.
Next we can create the
guest role during the test:
test "should create new unconfirmed guest user" do create(:role, name: "guest") @form.validate(email: "name@domain.com", password: "password") assert(@form.save) assert_not(@user.confirmed?) assert(@user.role?(:guest), "user does not have the role of :guest") end
Now if you run those tests again you should see them all pass!
Conclusion
In today’s tutorial we’ve encapsulated the registration process in a Form Object. This gives us a single place to deal with specific registration validation, as well as setting up any additional models or associations that will need to be created at the same time.
I find the Form Object pattern a really nice way to encapsulate these important processes.
Alternative methods would be to crowbar this functionality into the
User model, or into the Controller, but both of those methods have a lot of negatives with not very much in the way of positives.
Next week we will be continuing with this registration flow mini-series by looking at adding the Controller and View for registering, as well as the Functional Tests to assert everything is working as it should.
You can find the code for this week’s tutorial on Github. | https://www.culttt.com/2016/03/30/creating-sign-form-flow-ruby-rails-part-2/ | CC-MAIN-2018-51 | refinedweb | 1,739 | 59.94 |
Introduction to Python Subprocess
The process is defined as a running program, each process has its own different states like its memory, list of open files, etc. As we know that every process executes one statement at a time. In Python versions 2 and 3 there are several different ways to run the process externally to interact with the operating system. Earlier versions had os modules to do this but now in the latest versions, these os modules are replaced by subprocess modules to call external commands from Python code. Subprocess modules are independent because they run completely independent entities in their private system state and execute the main thread concurrently with the original process.
Working of Python Subprocess with Syntax and Example
In the latest versions of Python as it supports the subprocess module instead of the old os modules. The process that creates the subprocess work with other things where the subprocess carries out its work even though the process is working with something else. The subprocess module is used to run new programs through Python code by creating a new process that helps to gain input or output or error pipes and also helps to gain exit codes of various commands.
The Subprocess provides a high-level interface than the older os modules like os.system(), os.spawn(), os.popen(), etc these all are replaced with a new spawn process, connect to their input or output or error pipes and also to gain their return codes.
Syntax:
subprocess.call (args, *, stdin=None, stdout=None, stderr=None, shell=False)
- args: this is used when you want the commands to be executed.
- stdin: it carries the value of standard input to be passed.
- stdout: it carries the value of output which is obtained by standard output stream.
- stderr: this carries the error obtained from the standard error stream.
- shell: It returns a Boolean value. True when commands get executed.
So you can run the command using args parameter, wait until the command gets executed and then it will return the returncode attribute if its zero then it returns the function else it raises CalledProcessError.
Example #1
Let us take that we want to execute echo command which is UNIX command in the Python script, but this will give us an error saying its syntax error as the echo is not a built-in command in Python. Echo is a UNIX command to print the value or statement whereas in Python we have printed as a command to print the value or statement.
So to run these UNIX commands in Python we have to create a new process that can be done using subprocess modules. This was earlier done using os.system() but this was only for the older versions instead we can use subprocess.call() which executes a program as a child process in which we cannot complete our needs. So we need to use open in advanced cases as popen is a class and not just a method.
It is as shown below:
import subprocess
subprocess.Popen(‘ls –la’, shell = True)
The above program can also use a subprocess.call() but this executes the program as a child process which is executed by the operating system as a separate process so as per the Python documentation it is recommended to use popen class. It can be written as
import subprocess
subprocess.call(‘ls –la’, shell =True)
In the above both the programs shell argument will take ‘false’ as default but we want the commands to be executed then we have to assign shell argument as ‘True’.
If the subprocess is not imported then as discussed earlier no commands can be executed externally in Python codes so to do this we need to use subprocess modules. To do this we need to first import the subprocess else you will get the error saying no such file is available which means the ls command cannot be executed in Python as its UNIX command. It is shown in the below screenshot.
In subprocess documentation, you get a list of methods of popen class few of them are popen.wait() which will wait for the child process to get terminate, popen.kill() to kill the child process, popen.terminate() stops the child process, popen.communicate() this is the most commonly used method which helps to interact with the process. Let us consider about communicate() method which allows reading and sending data from and to the standard input and standard output respectively.
Example #2
Let us take an example to execute windows commands like dir and sort. So there are two commands to execute these commands we have to create two subprocesses as we want the directories to be sorted in reverse order in which we use ‘\R’ option in sort call. In the below program we use stdout of p1 as input to p2 so we declare PIPE in stdout for p1. So we have to close p1 as we have used it as input to p2. And as usual, the communication is done using the communicate() method.
import subprocess
p1 = subprocess.Popen(‘dir’, shell =True, stdin = None, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
p2 = subprocess.Popen('sort /R', shell=True, stdin=p1.stdout)
p1.stdout.close()
out, err = p2.communicate()
Output:
From the above example, it has two subprocess dir and sort commands to be executed through Python script as given above and the dir command process is an input to the sort command process to sort the obtained directories in reverse order.
Conclusion
In Python, versions 2 and 3 have separated ways of calling commands externally through the Python code. In Python 2 we had operating system (os) methods as a better way to call the child process of other languages through the Python script. However, in the present version, it uses the subprocess module which has several methods. Popen is one of the most used classes in both versions but in the latest versions, it again has many other methods in it to make it very efficient. Subprocess also has a call(), check_stdout(), check_stdin() are also some of the methods of a subprocess which are used instead of Popen class’s method communicate().
Recommended Articles
This is a guide to Python Subprocess. Here we discuss the Working of Python Subprocess with appropriate syntax and respective example. You may also have a look at the following articles to learn more – | https://www.educba.com/python-subprocess/ | CC-MAIN-2020-34 | refinedweb | 1,070 | 61.77 |
Hi,
I'm just getting started and found a strange issue with asynchronous code. Try this in an iOS project:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MonoTouch.Foundation; using MonoTouch.UIKit; using Portable; namespace AsyncAwaitTest { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { UIWindow window; AsyncAwaitTestViewController viewController; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { Test ().Wait (); window = new UIWindow (UIScreen.MainScreen.Bounds); viewController = new AsyncAwaitTestViewController (); window.RootViewController = viewController; window.MakeKeyAndVisible (); return true; } public static async Task Test() { await Task.FromResult (true); await Task.Delay (1000); await Task.FromResult (true); } } }
It seems that the
await Task.Delay immediately returns without delay and causes control to pass back to the caller - the second call to
await Task.FromResult is never even executed! I've tried both via the debugger and by doing
Console.WriteLines to see which statement successfully execute. In both cases, it's clear something very wrong is happening when awaiting the delay. No exceptions, no weird application output.
Any ideas?
Thanks
The problem is that you're calling
Wait()on the Task. That is a synchronous call, which means it blocks until the Task is complete. But that won't work in that case. To understand why you need to understand how async/await works. When you call
Task.Delay(1000)it does not actually "wait" 1 second. It just creates a task that represents a 1 second delay. When you "await" that task you are saying "I want to continue this function only after that task completes". The result is that the function returns to the caller, but only after registering the rest of the function as a "continuation". When the delay task is complete it will take its continuation and schedule it on the thread that originally called it (in this case the UI thread) so that the rest of the function can execute. Here's where the problem is: your
Wait()call is blocking that thread. So you have set up a deadlock.
In general you should avoid calling
Wait()unless you really know what you're doing. Use await instead. Normally that means just making your function an
async Taskor
async voidfunction, but sine this is FinishedLaunching you need some special consideration. iOS insists that after FinishedLaunching is called you need to have an active window with a RootViewController. You're only doing that after your task. You will have to do something a bit different here.
My suggestion is that you have two view controllers: one is a temporary splash/loading screen, and then the other is the real one. Your code would look something like this:
Usual warning: I haven't tested this, but I think it will work.
Thanks Adam. Of course, you're right - that'll teach me for throwing together quick tests without sufficient thought. I was getting confused because the behavior of XS differs from VS. In VS, attempting to step over the
await Task.Delayjust blocks and its evident in the stack, whereas in XS it appears to continue execution.
Cheers
I have a problem in this case.
While LoadViewControllers do his job (for me it's check existing password with server), FinishedLaunching returns true and there will be a Black Screen on mobile ! what can I do?
@dash_alireza - This thread is from 2014, and by posting on it you've notified everyone on it.
In addition, your post does not have sufficient information for anyone to help you. It also sounds like you are on iOS (Mobile) and this is the Xamarin.Mac forum.
Please create a new post in the correct section, with an example or sufficient information.
@adamkemp Thanks for your response. I'll check it
@ChrisHamons Thanks for you notice.
If you just want to delay your Splash screen (Launch Screen) then you can do the following: | https://forums.xamarin.com/discussion/comment/358807 | CC-MAIN-2020-29 | refinedweb | 641 | 60.21 |
I have run into problems that I’m really not sure about how to solve.
Throughout my code I want some things to work differently if my plugin is standalone, I thought it would be a case of wrapping with
#if JUCE_STANDALONE_APPLICATION but that seems to always evaluate false in XCode 9.2
I tried even adding JUCE_STANDALONE_APPLICATION=1 to the preprocessor macros and it still not working, so I’m wondering if I have misunderstood something fundamental about how to achieve slightly different behaviour in standalone as opposed to AU/VST in a host.
[SOLVED] Standalone plugin conditional compilation
I have run into problems that I’m really not sure about how to solve.
I think you need to do the check at run time. The AudioProcessor has the public member wrapperType to check that.
But it doesn’t help if the check is going to be done in the “shared code” portion of the project…That is compiled only once and then just linked in for the builds with the various wrappers.
OK, this was one of the things that I was going to investigate. I was wondering if I could move the relevant items out of the shared code into each target, and if that would then build those bits 4 times (VST/3/AU/Standalone). But it sounds like runtime check for which environment might be easier.
I managed to get it working thusly :
- remove the code that has the conditional checks form the Shared Code target
- add that same code to each plugin target
- add JUCE_STANDALONE_APPLICATION=1 to the preprocessor macros
Point 3 really shouldn’t have been necessary, but my guess is it’s because this section of code in
AppConfig.h is appearing before any of the
defines it relies on :
#ifndef JUCE_STANDALONE_APPLICATION #if defined(JucePlugin_Name) && defined(JucePlugin_Build_Standalone) #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone #else #define JUCE_STANDALONE_APPLICATION 0 #endif #endif
It would be incredibly useful if the Projucer had some way to choose under which target any given source file is compiled, because as soon as I re-save from there I will lose any of those edits I’ve made as detailed above. Unless of course I’ve missed this somewhere.
This is a bit OT but if you’re testing juce definitions, never use #ifdef. Always use #if.
We treat our macros as tri-state: undefined means “default”, 1 means true, and 0 means false. #ifdef will return true if the value is actually 0
I had meant to mention that
#ifdef JUCE_STANDALONE_APPLICATION would evaluate true regardless, thanks for pointing that out.
Was my thinking correct about point 3 above, that because
JucePlugin_Name is not yet defined
JUCE_STANDALONE_APPLICATION is always going to be assigned
0?
I’m guessing the Projucer change would be a bit too specific for plugins and likely something that won’t be added?
The
JucePlugin_Name is defined in your generated
AppConfig.h, which is the first header included in the
JuceHeader.h, that comes usually first in all your files, so I can’t see how
JucePlugin_Name would end up undefined…
In my generated
AppConfig.h the
JUCE_STANDALONE_APPLICATION define is on line 290, where as
JucePlugin_Name is defined on line 324. I’m using Projucer 5.3.2 (not compiling myself or anything).
I expect that I am misunderstanding something, but certainly as my
AppConfig.h is generated by the Projucer and used in my code,
JUCE_STANDALONE_APPLICATION always evaluates false.
Here’s an
AppConfig.h as from a fresh audio plugin generated by my Projucer :
Sorry, that was my bad, I missed that part when I skimmed through the AppConfig.h…
You are totally right, it needs to be the other way round.
I seem to be having the opposite problem (Xcode 10.0);
JUCE_STANDALONE_APPLICATION is always true, as is
JucePlugin_Build_Standalone. I’ve double checked in the Preprocessor Macros section of the VST target and its
0. I wonder if AppConfig.h is overriding the Xcode Preprocessor Macros section?
I tested this by manually adding a preprocessor macro to the “Standalone Plugin” target in Xcode, which worked as expected.
Just for the records, if a check at runtime is an option, there is the static JUCEApplicationBase::isStandaloneApp()…
Thanks, I saw that, and I am using
#if. I might be able to use the runtime check but its for setting channel configuration so I think better suited to compile time.
Here’s what I did…
AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new MyAudioProcessor (JUCEApplicationBase::isStandaloneApp()); }
and have two MyAudioProcessor constructors for the different channel configs.
Rail | https://forum.juce.com/t/solved-standalone-plugin-conditional-compilation/30131 | CC-MAIN-2019-04 | refinedweb | 753 | 52.9 |
PROBLEM LINK:
Author: Mohammed Ehab
Tester: Данило Мочернюк
Editorialist: Ritesh Gupta
DIFFICULTY:
HARD
PREREQUISITES:
DFS, Matching, Link-Cut Tree
PROBLEM:
You are given undirected simple graph with N vertices (numbered 1 through N) and M edges (numbered 1 through M). You want to colour the edges in red, green and yellow so that the graph would be perfectly balanced, which means that for each vertex, the number of red edges incident to it must be equal to the number of green edges incident to it.
Since you hate the colour yellow, his satisfaction with the graph will be greater when he uses fewer yellow edges. Can you help him choose how to colour the edges so that you remain in the surviving half of humanity?
QUICK EXPLANATION:
If in the given graph, each component has an even number of edges and each node has an even degree, then it is always possible to paint the edges in only two colours (Red and Green) such that the condition mentioned in the problem is satisfied. Now, we can achieve this graph by deleting some edges from the graph given in input (painting them in yellow) :
- If we encounter a node x with odd degree, we delete the edge between x and the neighbour of x with the minimum degree. Doing this greedily gives 20 points.
- Instead of removing the edge with the neighbour with the minimum degree, choose a neighbour y randomly and delete the edge between x and y. Keep doing this unless R becomes less than 2. This approach gives 40 points.
- For 100 points, create another graph, G’ with N disjoint nodes initially. Move edges from input graph G to G’ as long as G is not matching. Whenever we find an even circuit in G’, color it with Red and Green alternately and remove it from G’. It is easy to show that if G is matching, all the edges in G should be colored in Yellow.
EXPLANATION:
Lemma 1: If G is a matching, all its edges will be covered in yellow.
Proof: If a graph is matching, each of its nodes will have degree at most 1. Now, if a node has degree 1 and we paint the only edge associated with Red, we will have to compensate for this action by painting another edge associated with this node in Green, but this won’t be possible since this node has a degree 1. Therefore, this edge must be painted in Yellow. This holds for all the edges in a matching graph.
Lemma 2: If there exists an even circuit, we can color its edges in Red and Green alternately.
Proof: For any particular vertex in the circuit, there will be two edges. Simply put, if we traverse the circuit once, we enter each node once and leave each node once. So if we paint the entering edge and leaving edge in opposite colors, it evens out the net effect for that particular vertex, or that vertex is still perfectly balanced.
Lemma 3: Even if an even circuit is removed, the graph’s balance won’t be affected.
Proof: If an even circuit is removed, it certainly means that the degree of each vertex in the circuit is reduced by 2. It has zero net effect on the balance of the graph because out of the 2 removed edges for each node, we can paint one in Red and the other in Green, which would help keep the balance same as before for that vertex, and in turn for the entire graph.
Consider the graph given in input as G. Create another graph (which would be a forest at any point of time) G’ with all the vertices as in G, but has no edges in it initially.
Let’s process the edges from a particular vertex (say x) one by one in the following manner :
- If both the endpoints of the edge belong to different components in G’, move this edge from G to G’. Formally, connect these endpoints in G’ as well, so that both are in the same component in G’ now and delete this edge from G.
- If both endpoints of this edge belong to the same component :
- If the distance between both of them in G’ is odd, then connecting this edge will make this an even circuit. So now we can remove the even circuit from G’ and color its edges with Red and Green alternately. If there exists an edge x to y which we previously retained for later usage, and both endpoints of the retained edge are not in the same component in G’, then we connect them in G’ and remove this edge from G, thereby deleting the retained edge.
- If the distance between both the endpoints in G’ is not odd, we will keep this edge (say x to y) for later use if we are not retaining an edge already. Note that connecting the endpoints of this edge in G’ forms an odd length cycle, which is not suitable for painting.
- If we are retaining an edge already, and both endpoints of the current edge are in the same component such that the distance between them is even, then we can say that we can have another odd length cycle in G’ if we connect the endpoints of the current edge. Now, we have one odd length cycle formed due to the current edge, say C_1, and another odd length cycle formed due to the previously retained edge, say C_2. Also, there exists one common vertex x among the two cycles, C_1 and C_2. So, we can say that both the odd length cycles C_1 and C_2 meet at x to form an even length cycle. Once we have found this even length cycle in G’, we can simply paint its edges in Red and Green alternately, and remove it from G’.
If we do these steps for all vertices from 1 through N, in such a manner that G’ is a forest at any point of time, we will certainly end up with G as a matching, i.e., each vertex has a degree less than or equal to 1.
At the end of these steps, we will end up with G as a matching, and it can be said with the help of Lemma 1 that the edges remaining in G will be colored in Yellow.
Note that since G is always a forest, we can speed up the operations to O(mlog(n)) by using Link/Cut tree.
TIME COMPLEXITY:
TIME: O(N logN)
SPACE: O(N)
SOLUTIONS:
Setter's Solution
#include <bits/stdc++.h> using namespace std; vector<int> v[100005]; map<pair<int,int>,int> idx; int p[100005],ch[2][100005]; bool flip[100005],del[300005]; int sz[100005],ans[300005]; void push(int node) { if (flip[node]) { flip[node]=0; swap(ch[0][node],ch[1][node]); if (ch[0][node]) flip[ch[0][node]]^=1; if (ch[1][node]) flip[ch[1][node]]^=1; } } void recalc(int node) { push(ch[0][node]); push(ch[1][node]); sz[node]=1+sz[ch[0][node]]+sz[ch[1][node]]; } int side(int node) { if (!p[node]) return -2; if (ch[0][p[node]]==node) return 0; if (ch[1][p[node]]==node) return 1; return -1; } void attach(int par,int node,int s) { if (node) p[node]=par; if (s>=0) ch[s][par]=node; } void rotate(int node) { int s=side(node),par=p[node]; attach(p[par],node,side(par)); attach(par,ch[!s][node],s); attach(node,par,!s); recalc(par); recalc(node); } void splay(int node) { while (side(node)>=0 && side(p[node])>=0) { push(p[p[node]]); push(p[node]); push(node); rotate((side(node)==side(p[node]))? p[node]:node); rotate(node); } if (side(node)>=0) { push(p[node]); push(node); rotate(node); } push(node); } void access(int node) { int o=node,cur=0; while (node) { splay(node); ch[1][node]=cur; recalc(node); cur=node; node=p[node]; } splay(o); } void reroot(int node) { access(node); flip[node]^=1; access(node); } int dep(int node) { access(node); return sz[ch[0][node]]; } int find(int node) { access(node); while (ch[0][node]) { node=ch[0][node]; push(node); } access(node); return node; } void link(int x,int y) { reroot(x); access(y); attach(x,y,0); recalc(x); } void cut(int x,int y) { reroot(x); access(y); p[ch[0][y]]=0; ch[0][y]=0; recalc(y); } int parent(int node) { access(node); node=ch[0][node]; push(node); while (ch[1][node]) { node=ch[1][node]; push(node); } access(node); return node; } int go(int a,int b,int c2) { int c1=1,d1=dep(a),d2=dep(b); vector<pair<int,int> > c; while (a!=b) { if (d1<d2) { swap(a,b); swap(c1,c2); swap(d1,d2); } int p=parent(a); ans[idx[{p,a}]]=c1; c1*=-1; c.push_back({a,p}); a=p; d1--; } for (auto e:c) cut(e.first,e.second); } int main() { int t; scanf("%d",&t); while (t--) { int n,m; scanf("%d%d",&n,&m); idx.clear(); for (int i=1;i<=n;i++) { v[i].clear(); p[i]=0; ch[0][i]=ch[1][i]=0; flip[i]=0; sz[i]=1; } for (int i=0;i<m;i++) { int a,b; scanf("%d%d",&a,&b); v[a].push_back(b); v[b].push_back(a); idx[{a,b}]=i; idx[{b,a}]=i; ans[i]=0; del[i]=0; } for (int a=1;a<=n;a++) { int b=-1; for (int c:v[a]) { int i=idx[{a,c}]; if (!del[i] && !ans[i]) { if (find(a)!=find(c)) { link(a,c); del[i]=1; } else if (dep(a)%2!=dep(c)%2) { ans[i]=-1; go(a,c,1); if (b!=-1 && find(a)!=find(b)) { link(a,b); del[idx[{a,b}]]=1; b=-1; } } else if (b==-1) b=c; else { ans[idx[{a,b}]]=-1; ans[i]=1; go(b,c,-1); b=-1; } } } } for (int i=0;i<m;i++) printf("%d\n",ans[i]); } }
Tester's Solution
#include<bits/stdc++.h> #define pb push_back #define x first #define y second #define sz(a) (int)(a.size()) using namespace std; const int MAX = 100005; int occ[MAX][2]; int banned[3 * MAX]; int color[3 * MAX]; int ptr[MAX]; vector<pair<int , int> > g[MAX]; pair<int, int> getNext(int u) { while(ptr[u] < sz(g[u])) { if(banned[g[u][ptr[u]].y]) { ptr[u]++; continue; } banned[g[u][ptr[u]].y] = 1; return g[u][ptr[u]]; } return {-1 , -1}; } void dfs(int u) { vector<int> stV = {u}; vector<int> stE; occ[u][0] = 0; while(!stV.empty()) { int u = stV.back(); pair<int, int> edge = getNext(u); if(edge.x == -1) { stV.pop_back(); if(sz(stE)) stE.pop_back(); occ[u][sz(stV) % 2] = -1; continue; } if(occ[edge.x][sz(stV) % 2] != -1) { color[edge.y] = (((sz(stE) + 1) % 2) == 1) ? 1 : -1; int oc = occ[edge.x][sz(stV) % 2] + 1; while(sz(stV) > oc) { int v = stV.back(); stV.pop_back(); occ[v][sz(stV) % 2] = -1; color[stE.back()] = ((sz(stE) % 2) == 1) ? 1 : -1; stE.pop_back(); } continue; } occ[edge.x][sz(stV) % 2] = sz(stV); stV.pb(edge.x); stE.pb(edge.y); } occ[u][0] = -1; } int main() { memset(occ, -1 , sizeof occ); int T; cin >> T; int sumN = 0 , sumM = 0; while(T--) { int n, m; cin >> n >> m; assert(1 <= n && n <= 1e5); assert(0 <= m && m <= 3e5); sumN += n;sumM += m; assert(sumN <= 3e5); assert(sumM <= 9e5); set<pair<int,int> > edges; for(int i = 0; i < m; i++) { int u , v; cin >> u >> v; if(u > v) swap(u , v); assert(u != v); assert(1 <= u && u <= n); assert(1 <= v && v <= n); edges.insert({u , v}); u--;v--; g[u].pb({v , i}); g[v].pb({u , i}); } assert(sz(edges) == m); for(int i = 0; i < n; i++) { dfs(i); } for(int i = 0; i < m; i++) { cout << color[i] << endl; banned[i] = color[i] = 0; } for(int i = 0; i < n; i++) { g[i].clear(); ptr[i] = 0; } } return 0; } | https://discuss.codechef.com/t/rgy-editorial/76068 | CC-MAIN-2020-40 | refinedweb | 2,050 | 68.91 |
Overview
Working with APIs is both fun and educational.
Many companies like Google, Reddit and Twitter releases it’s API to the public
so that developers can develop products that are powered by its service.
Working with APIs learns you the nuts and bolts beneath the hood.
In this post, we will work the Weather Underground API.
Weather Underground (Wunderground)
We will build an app that will connect to ‘Wunderground‘ and retrieve.
Weather Forecasts etc.
Wunderground provides local & long range Weather Forecast, weather reports,
maps & tropical weather conditions for locations worldwide.
API
An API is a protocol intended to be used as an interface by software components
to communicate with each other. An API is a set of programming instructions and
standards for accessing web based software applications (such as above).
With API’s applications talk to each other without any user knowledge or
intervention.
Getting Started
The first thing that we need to do when we want to use an API, is to see if the
company provides any API documentation. Since we want to write an application for
Wunderground, we will go to Wundergrounds website
At the bottom of the page, you should see the “Weather API for Developers”.
The API Documentation
Most of the API features require an API key, so let’s go ahead and sign up for
a key before we start to use the Weather API.
In the documentation we can also read that the API requests are made over HTTP
and that Data features return JSON or XML.
To read the full API documentation, see this link.
Before we get the key, we need to first create a free account.
The API Key
Next step is to sign up for the API key. Just fill in your name, email address,
project name and website and you should be ready to go.
Recommended Python Training
For Python training, our top recommendation is DataCamp.
Many services on the Internet (such as Twitter, Facebook..) requires that you
have an “API Key”.
An application programming interface key (API key) is a code passed in by
computer programs calling an API to identify the calling program, its developer,
or its user to the Web site.
API keys are used to track and control how the API is being used, for example
to prevent malicious use or abuse of the API.
The API key often acts as both a unique identifier and a secret token for
authentication, and will generally have a set of access rights on the API
associated with it.
Current Conditions in US City
Wunderground provides an example for us in their API documentation.
Current Conditions in US City
If you click on the “Show response” button or copy and paste that URL into your
browser, you should something similar to this:
{ "response": { "version": "0.1" ,"termsofService": "" ,"features": { "conditions": 1 } } , "current_observation": { "image": { "url":"", "title":"Weather Underground", "link":"" }, "display_location": { "full":"San Francisco, CA", "city":"San Francisco", "state":"CA", "state_name":"California", "country":"US", "country_iso3166":"US", "zip":"94101", "magic":"1", "wmo":"99999", "latitude":"37.77500916", "longitude":"-122.41825867", "elevation":"47.00000000" }, .....
Current Conditions in Cedar Rapids
On the “Code Samples” page we can see the whole Python code to retrieve the
current temperature in Cedar Rapids.
Copy and paste this into your favorite editor and save it as anything you like.
Note, that you have to replace “0def10027afaebb7” with your own API key.
import urllib2 import json f = urllib2.urlopen('') json_string = f.read() parsed_json = json.loads(json_string) location = parsed_json['location']['city'] temp_f = parsed_json['current_observation']['temp_f'] print "Current temperature in %s is: %s" % (location, temp_f) f.close()
To run the program in your terminal:
python get_current_temp.py
Your program will return the current temperature in Cedar Rapids:
Current temperature in Cedar Rapids is: 68.9
What is next?
Now that we have looked at and tested the examples provided by Wunderground,
let’s create a program by ourselves.
The Weather Underground provides us with a whole bunch of “Data Features” that
we can use.
It is important that you read through the information there, to understand how
the different features can be accessed.
Standard Request URL Format
“Most API features can be accessed using the following format.
Note that several features can be combined into a single request.”
where:
0def10027afaebb7: Your API key
features: One or more of the following data features
settings (optional): Example: lang:FR/pws:0
query: The location for which you want weather information
format: json, or xml
What I want to do is to retrieve the forecast for Paris.
The forecast feature returns a summary of the weather for the next 3 days.
This includes high and low temperatures, a string text forecast and the conditions.
Forecast for Paris
To retrieve the forecast for Paris, I will first have to find out the country
code for France, which I can find here:
Next step is to look for the “Feature: forecast” in the API documentation.
The string that we need can be found here:
By reading the documentation, we should be able to construct an URL.
Making the API call
We now have the URL that we need and we can start with our program.
Now its time to make the API call to Weather Underground.
Note: Instead of using the urllib2 module as we did in the examples above,
we will in this program use the “requests” module.
Making the API call is very easy with the “requests” module.
r = requests.get(" Paris.json")
Now, we have a Response object called “r”. We can get all the information we need
from this object.
Creating our Application
Open your editor of choice, at the first line, import the requests module.
Note, the requests module comes with a built-in JSON decoder, which we can use
for the JSON data. That also means, that we don’t have to import the JSON
module (like we did in the previous example when we used the urllib2 module)
import requests
To begin extracting the information that we need, we first have to see
what keys that the “r” object returns to us.
The code below will return the keys and should return [u’response’, u’forecast’]
import requests r = requests.get(" Paris.json") data = r.json() print data.keys()
Getting the data that we want
Copy and paste the URL (from above) into a JSON editor.
I use but any JSON editor should do the work.
This will show an easier overview of all the data.
Note, the same information can be gained via the terminal, by typing:
r = requests.get(" Paris.json") print r.text
After inspecting the output given to us, we can see that the data that we are
interested in, is in the “forecast” key. Back to our program, and print out the
data from that key.
import requests r = requests.get(" Paris.json") data = r.json() print data['forecast']
The result is stored in the variable “data”.
To access our JSON data, we simple use the bracket notation, like this:
data[‘key’].
Let’s navigate a bit more through the data, by adding ‘simpleforecast’
import requests r = requests.get(" Paris.json") data = r.json() print data['forecast']['simpleforecast']
We are still getting a bit to much output, but hold on, we are almost there.
The last step in our program is to add [‘forecastday’] and instead of printing
out each and every entry, we will use a for loop to iterate through the dictionary.
We can access anything we want like this, just look up what data you are
interested in.
In this program I wanted to get the forecast for Paris.
Let’s see how the code looks like.
import requests r = requests.get("") data = r.json() for day in data['forecast']['simpleforecast']['forecastday']: print day['date']['weekday'] + ":" print "Conditions: ", day['conditions'] print "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C", ' '
Run the program.
$ python get_temp_paris.py
Monday: Conditions: Partly Cloudy High: 23C Low: 10C Tuesday: Conditions: Partly Cloudy High: 23C Low: 10C Wednesday: Conditions: Partly Cloudy High: 24C Low: 14C Thursday: Conditions: Mostly Cloudy High: 26C Low: 15C
The forecast feature is just one of many. I will leave it up to you to explore
the rest.
Once you get the understanding of an API and it’s output in JSON, you understand
how most of them work.
More Reading
A comprehensive list of Python APIs
Weather Underground
Recommended Python Training
For Python training, our top recommendation is DataCamp. | https://www.pythonforbeginners.com/scraping/scraping-wunderground | CC-MAIN-2021-31 | refinedweb | 1,410 | 63.8 |
Hey everyone,
I have a small question, but I can’t get the solution.
I want to only delete the points on the blue curve with python code.
I have already got these points with x/y/z coordinate.
with rs.DeleteObjects() to delete the objects need the GUID of the point.
But how can I get the GUID of an existing Point?
Here is my code and the GH,Rhino document.
delete points.gh (2.7 KB)
delete points.3dm (31.1 KB)
import rhinoscriptsyntax as rs
import Rhino
from scriptcontext import doc
filter = Rhino.DocObjects.ObjectType.Curve
rc, objref = Rhino.Input.RhinoGet.GetOneObject(“Select curve to delete points”, False, filter)
c = objref.Curve()
allObjects = rs.AllObjects()
for i in allObjects:
p = rs.IsPoint(i)
if p == True:
param = rs.CurveClosestPoint(c, i)
point = rs.EvaluateCurve(c, param)
print(point)
#rs.DeleteObjects(point)
could someone give some advice? | https://discourse.mcneel.com/t/delete-the-points-on-a-curve-with-only-x-y-z-coordinate/105165 | CC-MAIN-2020-34 | refinedweb | 149 | 63.76 |
[:
Changelog:
I haven't used the plugin because I have written my own, but I want to encourage someone to release an officially supported one (I have too many plugins right now as is and am not looking to release another one right now).
I did want to give some suggestions that may or may not help you. Feel free to disregard any of my suggestions .
Even though the theme file is not defining seconds, it is easy to convert this to a time object with in python, and even convert it to just seconds (which is what I do as well). Here is an example:[pre=#2D2D2D] 1 from datetime import datetime, timedelta
...
12 def total_seconds(t): 13 return (t.microseconds + (t.seconds + t.days * 24 * 3600) * 10 ** 6) / 10 ** 6
22 def translate_time(t): 23 # Translate a string from format "H:M" into seconds 24 tm = time.strptime(t + ":00", '%H:%M:%S') 25 return total_seconds(timedelta(hours=tm.tm_hour, minutes=tm.tm_min, seconds=tm.tm_sec))[/pre]
153 # Reset the theme scheduler object if the settings file has changed 154 SETTINGS.add_on_change('reload', ThemeScheduler.init)[/pre]
Maybe these suggestions will help, anyways, good luck with your plugin.
Thanks for the suggestions.I'm quite new to python and the ST2 API so at least thanks for suggestion 3, this is a way more efficient way than I'm using right now!
And to combine suggestion 1 and 2. I like to give people full control over the time so I'll include seconds, but you have a valid point that using the way you format time is more user friendly.So I'll make it that you can decide whether you want to define it with (08:30:15) or without (08:30) seconds.
I'm quite busy at the moment but I'll commit the changes to the plugin either today or tomorrow
Thanks again for these great suggestions!
Update!
Version Beta 0.2
What's changed? | https://forum.sublimetext.com/t/beta-themechanger-ideas-needed/7685 | CC-MAIN-2017-09 | refinedweb | 330 | 71.95 |
Interop
Routing and Event System for UI5
This is a library for UI5 that allows many instances of UI5 applications to run simultaneously, integrated or independently of each other in sub-containers (side by side, or embedded)
Container applications can register their container locations so that any app can navigate to a chosen container (eg: Left/Right/Header/Footer/Main/Master/Other)
It also provides methods for communicating between those applications (simplified version of EventBus, for ease of use)
What can you use it for?
Use your imagination! but here’s a few examples, you can use this to compare two client records (instantiate the same fiori view twice, side by side, with different route params) Or even run completely different applications independently in the same window (for example, your Inbox in a side or top panel, so you can keep track of your job queue at all times)
Why not just use ComponentContainers?
Flexibility, Simplicity, and Routing.
Even if you were to use ComponentContainers, how do you route them? how do you maintain two route url’s on the one page? these problems are solved in my Interop solution.
And all apps that run this way, can be built in the usual UI5 way with standard routers. So all of your existing UI5 apps can be run in containers, and any new apps you build using Interop can still run as standalone applications when necessary. (aka: no dependency or tight coupling!)
Why did I build this?
I’ve seen a few attempts at building ‘frameworks’ that could dynamically call upon different UI5 applications, and I thought I could do better, so I gave it a shot. What bugged me most about these solutions I saw, was that any app or view used in them would follow a very custom pattern and was usually tightly-coupled. I wanted to do it in a reliable way, a standardised way, one that didn’t require re-training of staff to be able to use it, so any ui developer could write a standard app and it would work within it.
I also thought it would be a very cool thing, to be able to run an Inbox application as a slide in panel, while also being able to compare two records side-by-side, and have process flows tracked in a header, etc etc. So… here we are.
Limitations / Assumptions
It it assumed that all applications using Interop use two word namespaces. eg: “product.app” if this isn’t the case you will run into trouble. This is the namespace convention I’m used to working with and have personally seen the most, which is why I’ve built it in this way. It could be made configurable, but you’d still need to at least be consistent (eg: 3 names is fine, but ALL apps would need to be 3 names)
Download
The Interop Library can be found on GitHub:
Now, Let’s jump right in…
Ok, so that’s the introduction / text-book stuff out of the way! I’ll show you what this little thing can do.
I’ve created a sample container application, which is included in the Git repository. It is fully featured, I’ve not even utilised all the panels I’ve setup in it, so it should serve well as a starting point for most use cases.
In my example I’ve created a split-app, and one other additional app, and am demonstrating how views from the split-app can be instantiated multiple times side by side for record comparisons.
Here’s a few screenshots of me playing around with the panels.
select a record
expand the right hand panel
click ‘move’ button on the right hand panel
tick duplicate and apply (so that content on the main panel will be duplicated into the right side as a new instance)
select a different record in the master list (which will update just our main content panel)
click an action that performs a navigation, and see that only the relevant panel is affected
I could go on and on, but I think this is enough to demonstrate what’s going on.
Additionally to what i’ve done here, it should be noted that demoapp1 (this master/detail app) can be run in standalone mode, from its own index page. Even the inter-app routing has fallback routines to facilitate this. Try it for yourself.
Live copy (HCP account required)
How it works
Merged URL Route Patterns
You may not have noticed it at first, but the URL in this app has a querystring of “?nav=”
This parameter is generated by Interop, and is a combined version of every panels current route pattern (for example, there’s two client records, so each instance of that view needs different parameters fed into its onRouteMatched event handler).
You’ll also notice that it’s hard to read… that’s because I’ve implemented string compression, to keep it from getting too long. It also has the added advantage of discouraging users from messing with the url. However, if you would like it to be more readable, you can turn off Url Compression.
These constructed URL’s allow the users session to be maintained, so if they hit F5 to refresh the page, it will remember what to load. Likewise they can copy&paste the URL into an e-mail and the correct configuration of views will be loaded when the recipient clicks it.
While this could’ve been done automatically, I have designed this to be triggered by the container application, for reasons that will become obvious soon..
In the container app you’ll notice these little pieces of code for maintaining sessions
//this allows the Interop system to manage browser history Interop.setRestoreOnBrowserBack(true);
var sessionResult = Interop.restoreSession(); if(!sessionResult.restored) { //no existing route info, this is a blank run
updateUrl: function() { if(this._loaded) { //save the session, and add additional session states (the state of expansion of the panels) //by doing this, we enable the page to be refreshed with f5 or the url to be copied & pasted into another browser, without losing track of what's in each panel Interop.saveSession({ me: window._masterOpen || false, re: this.oLayoutData.RightPanelOpen, rw: this.oLayoutData.RightPanelBig }); } },
You may have already gathered, that the container gets the opportunity to add its own custom session variables, these will be encoded into the ?nav= URL string along with the base information. (in this sample, it is used to remember the expanded state of the master and right hand panels)
The container also controls what to do if a session isn’t present (in this case, my sample container looks for normal ui5 route parameters to see if an app has been specified, and load it, if not, it defaults to demoapp1)
The setRestoreOnBrowserBack(true) is simply a necessity because browser events will be hooked when this is called. This allows the user to press the back button in their browser and have their session restored automatically by Interop
Virtual Router Objects
To allow legacy routing (apps running standalone OR within containers) without further development effort inside the app, virtual (or proxy) routers are created on the fly by Interop to simulate commonly used functionality of the standard SAP router classes.
This means that when you call this.getRouter() you are getting a dummy object, that will simply translate your standard .navTo requests into Interop navigateContainer calls automatically.
These virtual routers also handle onRouteMatch events, and will parse in all the same parameters you would usually expect, along with a few new ones (like “container”, telling you which container you’re in)
To use virtual routers, simply inherit the dalrae.ui5.BaseController in all your view controllers. Or, copy its .getRouter function into your own base.
onBeforeRendering: function() { //fallback routing support (allows apps to run standalone and still call .navigateContainer) -PhillS if(dalrae.ui5.routing.Interop.UseFallbackRouting) { dalrae.ui5.routing.Interop.mFallbackRouter = this.getRouter(); } }, // supports our Interop component containers method of routing -PhillS getRouter: function() { //UPDATED to work with manifest style apps -PhillS var router = sap.ui.core.UIComponent.getRouterFor(this); if(!router || dalrae.ui5.routing.Interop._cc ) { if(dalrae.ui5.routing.Interop._cc[dalrae.ui5.routing.Interop.StandardContainer.Main] || !router) { var router2 = dalrae.ui5.routing.Interop.getRouterFor(this); if(router2) { return router2; } } } if(dalrae.ui5.routing.Interop.UseFallbackRouting) { //fallback routing support (allows apps to run standalone and still call .navigateContainer) -PhillS dalrae.ui5.routing.Interop.mFallbackRouter = router; } return router; },
Essentially, the standard routers are totally overwritten by Interops own routing code, which is designed to emulate the sap router as closely as possible. Of course, some methods might be missing from my version of the router, and if this is an issue for your implementation you may need to extend the class yourself (or let me know).
Globally Registered Containers
Each area of the screen that is route-able, is registered as a container.
This means that the container app, and the contained app, do not need to know each other.
They simply need to know container id’s, such as “main” and “master” to interact, so neither are coupled or dependant upon each other to operate.
The easiest way to do this is to just use the dalrae.ui5.routing.Container element in your XML view and assign it one of the standard id’s.
However, you can use any UI element that has a <content> aggregation. To do so, you can call Interop.registerContainer()
Interop.registerContainer( Interop.StandardContainer.Main , oPanel );
or
<mvc:View xmlns: <routing:Container
Container Navigation
Inter-app navigation is highly simplified. rather than constructing deeplink urls, you can navigate a container to a completely different applications view by simply using the navTo parameters for that view.
//demonstrating an Interop cross app navigation. Interop.navigateContainer( Interop.StandardContainer.Main , { app: "sample.demoapp2", nav: [ "main", { example: "an example parameter" } ] });
The only addition is the container ID, and the app namespace.
Although it is also worth noting, that namespaces must be registered before being used.
This is needed in Gateway/Launchpad systems, which use SemanticObjects. But in Hana you’ll still need to do it (until I come up with a clever way to autodetect Hana systems that is)
//Registering a namespace in Hana Interop.registerNamespace("sample.demoapp1"); //Registering a namespace in Gateway Interop.registerNamespace("sample.demoapp1","ZDEMOAPP1");
The added perk of doing this, is that the master list can remain loaded as app1, while the main content panel can navigate off to app2, so the user doesn’t need to go back a screen in order to access another record from app1, which is far less disruptive to the user flow of the program.
Global Event System
As mentioned, a replacement to the EventBus system is provided. It works in basically the same way. My main motivation for doing this was to make the event signatures consistent with all other elements of UI5, which the event bus isn’t.
To use it, you can register event handlers in any view of any app, and fire those events from anywhere as well.
I haven’t really used much of these in my sample, but they are useful for when you’d like your applications to actually be able to talk to each other. There’s plenty of things you can achieve by having panels communicate. You could for example, have an event fired each time the main panel opens a client record, and have the header panel pop down with alerts or available actions for that client number, regardless of which app that client is being viewed in.
Also, the Interop navigation fires off a few inbuilt events that you can take advantage of, and these, are in fact being used in my Sample so you can see them in action.
OnNavigate: This event is fired when any container is navigated anywhere. So any program listening to this event will see the navigation of every other program. This is good for container applications which may want to show or hide certain panels.
Parameters:
app : app namespace (eg: “sample.demoapp1”)
name : route name
arguments : routing parameters
container : ID of the container (eg: “main”)
sessionRestore : true/false
OnContainerCleared: This event is fired when any container has its content cleared via clearContainer, clearAllContainers, or a session restore.
Parameters:
container : ID of the container (eg: “main”)
sessionRestore : true/false
OnSessionRestored: This event is fired when a route pattern is successfully or unsuccessfully restored from a URL or custom source via the restoreSession() call
Parameters:
restored : true/false
navs : internal data of the session
extraStateInfo : custom values included in the session
Flexible Layout
Just to re-iterate… you can create any container application layout you like.
Just be sure to use the standard container id’s (or if making your own, be consistent) and it will work just fine. You can even have multiple container apps if you like. The sample I have provided is precisely that, a sample, and I haven’t even used it to it’s full potential in this example.
It actually has many active panels ready to go (diagram below)
But as stated, just a sample, so go nuts, make your own, go crazy!
Conclusion
I don’t know how many of you will utilise this system, but I thought it was worth sharing, as it’s the kind of functionality I’d like to see available out-of-the-box.
Being able to compare two client records, and giving users the choice to move content around, is something I’m eager to see, there’s many cool things I can think of that become possible. Additionally, the applications I’ve tried running in this way, have (in my opinion) run much smoother, since you never need to reload the entire screen.
I’ve uploaded the code to GitHub with an MIT license, so you are free to use it yourself
Download
The Interop Library can be found on GitHub:
Phillip, great blog. It’s exactly what I need.
Just trying to understand how to implement interop. May need is a one container in which I can start serveral different applications depending on say for example which button I press in the container app. Is it possible to point me in the right direction.
Regards Erik
Hi Erik,
I’m not sure exactly what scenario you’re talking about so I’m sorry if I miss the mark here. I assume you have an application already running in the main area (within a container) and when you perform an action (press button A), you want to open another application in another panel?
There’s a few ways, the simplest way which seems adequate in your case is to just call the navigateContainer function, and have the container automatically open the target panel when it detects something navigated there (onNavigate)
So for example:
Then in the container app, you’ll see in the sample that there’s a handler of onNavigate, this will fire globally, when anything is navigated anywhere, so we use this to know that something has navigated that Right hand panel, and do something about it (expand it out so it’s visible, presumably)
In more complex scenarios, you might want to setup custom events for your applications to fire, and let global logic in your controller completely handle what to do about those events.
I hope that helps
Phillip Thanks that worked.:)
Iam now trying to start an app that is deployed on a abap stack. The question i have is it possible to navigate by using the semanticObject.
As the app that i want to start is used on the FioriLaunchpad.
Below you see how we now navigate from one app to the another one.
var hash = oCrossAppNavigator.hrefForExternal({
target: {
semanticObject: “PMApplication”,
action: “CreateOrder”
},
params: {
“Guid”: oData.Guid
}
});
The downside is it opens in a new tab of the browser.
We would like to open it within the current application as you do with the interop libs.
Any ideas what we are doing wrong.
Thanks Erik
Hi Erik,
Glad to hear it!
I haven’t written up a navigate function to read semantic objects yet (it was something I thought I might do in future as an enhancement). Though it isn’t actually necessary for running on the abap stack. I have run this solution on a CRM system successfully, the navigation doesn’t change, all that changes is the registerNamespace call you make.
What I mean is, when you want to navigate to your new app, you will still just use its namespace “your.app1” and not its semantic object. What you will have to setup beforehand though, is its BSP name. The reason for this, is Interop looks directly at the internal addresses of the BSP’s rather than the launchpad generated alias.
so when your app starts (preferably in a common base class somewhere), you need to register all the applications you might possibly navigate to, doing so links their BSP and Namespace for Interop, like so
Now when you ask Interop to load “your.app1” it knows how to construct a url to find it, because you’ve registered the BSP name
So now you just do the navigateContainer the same as before.
Now what this doesn’t solve for you, is your use of an action “CreateOrder”. Interop currently does not parse action/intent. Personally I avoid using them but obviously it’s what you’ve implemented so you’d need to either move that to a parameter of your route, or enhance Interop to facilitate parsing action through somehow. I no longer have easy access to an abap system so I can’t be of much more assistance I’m sorry.
Hey Phillip,
By implementing it as you said before(see code below) it works
The navigation works and when debuggen I see that the second application “plannus” is loaded and Iam walking through the component of the app which then loads the appropriate view as stated in the manifest.
I enter the controller of the view where the existing code doesn’t find the component any more.
this statement errors as the ownerid is undefined
this._oComponent = sap.ui.component(sap.ui.core.Component.getOwnerIdFor(this.getView()));
How do i locate the correct component
cheers Erik Thanks for you’re Help
Hi Erik,
Take a look at the BaseController I’ve setup, it has methods for getting the router and component (which will work inside Interop as well as Standalone), implementing these functions in your own base controller would be the fastest way to get up and running I believe, and use this.getComponent().
It is unfortunate that you will have to change that line of code in your application, since the idea is to not have to change any apps, but this is the exception to the rule. As long as everything is utilising a base controller you should be able to keep everything tidy and neutral
Hope that helps
Hi Phillip,
Thanks for the reply. That worked for me.
I agree it is a shame to change the app that is called but as you mentioned the change is minor.
cheers Erik | https://blogs.sap.com/2018/06/14/interop-a-system-for-running-multiple-ui5-application-instances-simultaneously/ | CC-MAIN-2020-50 | refinedweb | 3,205 | 58.42 |
import numpy as no import gym from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam from rl.agents.dqn import DQNAgent from rl.agents.ddpg import DDPGAgent from rl.policy import BoltzmannQPolicy , LinearAnnealedPolicy , EpsGreedyQPolicy from rl.memory import SequentialMemory
/Library/Frameworks/Python.framework/Versions/3.6.
ENV_NAME_2 = 'Asteroids-v0'
# Get the environment and extract the number of actions env = gym.make(ENV_NAME_2) nb_actions = env.action_space.n nb_actions
14
# Next, we build a neural network model model = Sequential() model.add(Flatten(input_shape=(1,) + env.observation_space.shape)) model.add(Dense(3, activation= 'tanh')) # One layer of 3 units with tanh activation function model.add(Dense(nb_actions)) model.add(Activation('sigmoid')) # one layer of 1 unit with sigmoid activation function print(model.summary())
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= flatten_1 (Flatten) (None, 100800) 0 _________________________________________________________________ dense_1 (Dense) (None, 3) 302403 _________________________________________________________________ dense_2 (Dense) (None, 14) 56 _________________________________________________________________ activation_1 (Activation) (None, 14) 0 ================================================================= Total params: 302,459 Trainable params: 302,459 Non-trainable params: 0 _________________________________________________________________ None
#DQN -- Deep Reinforcement Learning #Configure and compile the agent. #Use every built-in Keras optimizer and metrics! memory = SequentialMemory(limit=20000, window_length=1) policy = BoltzmannQPolicy() dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10, target_model_update=1e-2, policy=policy) dqn.compile(Adam(lr=1e-3), metrics=['mae', 'acc'])
## Visualize the training during 500000 steps dqn.fit(env, nb_steps=500000, visualize=True, verbose=2)
Training for 100000 steps ...
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/rl/memory.py:29: UserWarning: Not enough entries to sample without replacement. Consider increasing your warm-up phase to avoid oversampling! warnings.warn('Not enough entries to sample without replacement. Consider increasing your warm-up phase to avoid oversampling!')
1455/100000: episode: 1, duration: 46.233s, episode steps: 1455, steps per second: 31, episode reward: 1350.000, mean reward: 0.928 [0.000, 100.000], mean action: 6.509 [0.000, 13.000], mean observation: 2.139 [0.000, 240.000], loss: 21.742520, mean_absolute_error: 0.748284, acc: 0.079748, mean_q: 0.865032 2423/100000: episode: 2, duration: 30.502s, episode steps: 968, steps per second: 32, episode reward: 630.000, mean reward: 0.651 [0.000, 100.000], mean action: 6.411 [0.000, 13.000], mean observation: 2.337 [0.000, 240.000], loss: 36.164433, mean_absolute_error: 0.916387, acc: 0.075252, mean_q: 0.964510 3192/100000: episode: 3, duration: 23.303s, episode steps: 769, steps per second: 33, episode reward: 780.000, mean reward: 1.014 [0.000, 100.000], mean action: 6.113 [0.000, 13.000], mean observation: 1.996 [0.000, 240.000], loss: 32.863270, mean_absolute_error: 0.941716, acc: 0.073716, mean_q: 0.978775 4037/100000: episode: 4, duration: 25.042s, episode steps: 845, steps per second: 34, episode reward: 880.000, mean reward: 1.041 [0.000, 100.000], mean action: 6.650 [0.000, 13.000], mean observation: 2.124 [0.000, 240.000], loss: 33.935211, mean_absolute_error: 0.961146, acc: 0.068861, mean_q: 0.984799 4472/100000: episode: 5, duration: 12.989s, episode steps: 435, steps per second: 33, episode reward: 330.000, mean reward: 0.759 [0.000, 50.000], mean action: 6.377 [0.000, 13.000], mean observation: 2.465 [0.000, 240.000], loss: 31.147161, mean_absolute_error: 0.964446, acc: 0.073851, mean_q: 0.988034 6292/100000: episode: 6, duration: 56.351s, episode steps: 1820, steps per second: 32, episode reward: 1180.000, mean reward: 0.648 [0.000, 100.000], mean action: 6.511 [0.000, 13.000], mean observation: 1.940 [0.000, 240.000], loss: 31.117493, mean_absolute_error: 0.973881, acc: 0.072373, mean_q: 0.991440 7098/100000: episode: 7, duration: 24.283s, episode steps: 806, steps per second: 33, episode reward: 780.000, mean reward: 0.968 [0.000, 100.000], mean action: 6.561 [0.000, 13.000], mean observation: 2.627 [0.000, 240.000], loss: 28.760992, mean_absolute_error: 0.976429, acc: 0.070720, mean_q: 0.994323 8897/100000: episode: 8, duration: 53.421s, episode steps: 1799, steps per second: 34, episode reward: 1180.000, mean reward: 0.656 [0.000, 100.000], mean action: 6.430 [0.000, 13.000], mean observation: 1.981 [0.000, 240.000], loss: 27.216291, mean_absolute_error: 0.976294, acc: 0.074833, mean_q: 0.996801 10784/100000: episode: 9, duration: 56.207s, episode steps: 1887, steps per second: 34, episode reward: 1320.000, mean reward: 0.700 [0.000, 100.000], mean action: 6.379 [0.000, 13.000], mean observation: 1.796 [0.000, 240.000], loss: 31.204847, mean_absolute_error: 0.985795, acc: 0.070830, mean_q: 0.998568 11988/100000: episode: 10, duration: 35.985s, episode steps: 1204, steps per second: 33, episode reward: 1180.000, mean reward: 0.980 [0.000, 100.000], mean action: 6.602 [0.000, 13.000], mean observation: 1.731 [0.000, 240.000], loss: 30.669523, mean_absolute_error: 0.986347, acc: 0.074517, mean_q: 0.999281 13541/100000: episode: 11, duration: 46.164s, episode steps: 1553, steps per second: 34, episode reward: 1080.000, mean reward: 0.695 [0.000, 100.000], mean action: 6.574 [0.000, 13.000], mean observation: 1.633 [0.000, 240.000], loss: 28.269192, mean_absolute_error: 0.983127, acc: 0.073487, mean_q: 0.999560 14309/100000: episode: 12, duration: 23.052s, episode steps: 768, steps per second: 33, episode reward: 580.000, mean reward: 0.755 [0.000, 100.000], mean action: 6.793 [0.000, 13.000], mean observation: 2.165 [0.000, 240.000], loss: 28.651321, mean_absolute_error: 0.982694, acc: 0.075562, mean_q: 0.999704 14855/100000: episode: 13, duration: 16.280s, episode steps: 546, steps per second: 34, episode reward: 430.000, mean reward: 0.788 [0.000, 100.000], mean action: 6.255 [0.000, 13.000], mean observation: 2.600 [0.000, 240.000], loss: 25.917961, mean_absolute_error: 0.979710, acc: 0.075321, mean_q: 0.999771 15676/100000: episode: 14, duration: 24.421s, episode steps: 821, steps per second: 34, episode reward: 780.000, mean reward: 0.950 [0.000, 100.000], mean action: 6.279 [0.000, 13.000], mean observation: 2.161 [0.000, 240.000], loss: 29.796518, mean_absolute_error: 0.985070, acc: 0.073196, mean_q: 0.999817 17303/100000: episode: 15, duration: 48.080s, episode steps: 1627, steps per second: 34, episode reward: 1320.000, mean reward: 0.811 [0.000, 100.000], mean action: 6.373 [0.000, 13.000], mean observation: 1.493 [0.000, 240.000], loss: 31.838648, mean_absolute_error: 0.989215, acc: 0.072065, mean_q: 0.999859 18249/100000: episode: 16, duration: 27.618s, episode steps: 946, steps per second: 34, episode reward: 880.000, mean reward: 0.930 [0.000, 150.000], mean action: 6.580 [0.000, 13.000], mean observation: 1.984 [0.000, 240.000], loss: 33.025875, mean_absolute_error: 0.990334, acc: 0.072509, mean_q: 0.999892 21461/100000: episode: 17, duration: 93.989s, episode steps: 3212, steps per second: 34, episode reward: 1880.000, mean reward: 0.585 [0.000, 100.000], mean action: 6.588 [0.000, 13.000], mean observation: 1.762 [0.000, 240.000], loss: 30.154207, mean_absolute_error: 0.987160, acc: 0.070809, mean_q: 0.999936 22917/100000: episode: 18, duration: 42.662s, episode steps: 1456, steps per second: 34, episode reward: 1180.000, mean reward: 0.810 [0.000, 100.000], mean action: 6.620 [0.000, 13.000], mean observation: 1.905 [0.000, 240.000], loss: 28.899130, mean_absolute_error: 0.983624, acc: 0.068402, mean_q: 0.999970 23238/100000: episode: 19, duration: 9.459s, episode steps: 321, steps per second: 34, episode reward: 430.000, mean reward: 1.340 [0.000, 100.000], mean action: 6.533 [0.000, 13.000], mean observation: 2.253 [0.000, 240.000], loss: 26.920767, mean_absolute_error: 0.980413, acc: 0.075058, mean_q: 0.999978 23586/100000: episode: 20, duration: 10.229s, episode steps: 348, steps per second: 34, episode reward: 160.000, mean reward: 0.460 [0.000, 50.000], mean action: 6.871 [0.000, 13.000], mean observation: 2.307 [0.000, 240.000], loss: 25.303034, mean_absolute_error: 0.980627, acc: 0.065823, mean_q: 0.999980 26189/100000: episode: 21, duration: 78.370s, episode steps: 2603, steps per second: 33, episode reward: 1320.000, mean reward: 0.507 [0.000, 100.000], mean action: 6.503 [0.000, 13.000], mean observation: 1.784 [0.000, 240.000], loss: 27.165476, mean_absolute_error: 0.981853, acc: 0.070652, mean_q: 0.999986 27369/100000: episode: 22, duration: 34.425s, episode steps: 1180, steps per second: 34, episode reward: 980.000, mean reward: 0.831 [0.000, 100.000], mean action: 6.385 [0.000, 13.000], mean observation: 1.941 [0.000, 240.000], loss: 27.088072, mean_absolute_error: 0.980287, acc: 0.067505, mean_q: 0.999992 28548/100000: episode: 23, duration: 35.070s, episode steps: 1179, steps per second: 34, episode reward: 980.000, mean reward: 0.831 [0.000, 100.000], mean action: 6.528 [0.000, 13.000], mean observation: 2.060 [0.000, 240.000], loss: 24.597326, mean_absolute_error: 0.977471, acc: 0.068119, mean_q: 0.999994 28919/100000: episode: 24, duration: 11.016s, episode steps: 371, steps per second: 34, episode reward: 480.000, mean reward: 1.294 [0.000, 100.000], mean action: 6.625 [0.000, 13.000], mean observation: 2.276 [0.000, 240.000], loss: 30.021408, mean_absolute_error: 0.985281, acc: 0.075219, mean_q: 0.999995 30695/100000: episode: 25, duration: 52.892s, episode steps: 1776, steps per second: 34, episode reward: 1300.000, mean reward: 0.732 [0.000, 100.000], mean action: 6.465 [0.000, 13.000], mean observation: 1.728 [0.000, 240.000], loss: 26.489769, mean_absolute_error: 0.980855, acc: 0.071087, mean_q: 0.999996 32084/100000: episode: 26, duration: 41.220s, episode steps: 1389, steps per second: 34, episode reward: 930.000, mean reward: 0.670 [0.000, 100.000], mean action: 6.603 [0.000, 13.000], mean observation: 1.972 [0.000, 240.000], loss: 28.961477, mean_absolute_error: 0.984377, acc: 0.070082, mean_q: 0.999997 33770/100000: episode: 27, duration: 50.046s, episode steps: 1686, steps per second: 34, episode reward: 1350.000, mean reward: 0.801 [0.000, 100.000], mean action: 6.718 [0.000, 13.000], mean observation: 1.699 [0.000, 240.000], loss: 30.137896, mean_absolute_error: 0.985636, acc: 0.070192, mean_q: 0.999998 35502/100000: episode: 28, duration: 51.162s, episode steps: 1732, steps per second: 34, episode reward: 1760.000, mean reward: 1.016 [0.000, 100.000], mean action: 6.483 [0.000, 13.000], mean observation: 1.864 [0.000, 240.000], loss: 29.654802, mean_absolute_error: 0.986030, acc: 0.069302, mean_q: 0.999999 36281/100000: episode: 29, duration: 23.153s, episode steps: 779, steps per second: 34, episode reward: 610.000, mean reward: 0.783 [0.000, 100.000], mean action: 6.589 [0.000, 13.000], mean observation: 2.412 [0.000, 240.000], loss: 27.241671, mean_absolute_error: 0.980745, acc: 0.069480, mean_q: 0.999999 37151/100000: episode: 30, duration: 25.850s, episode steps: 870, steps per second: 34, episode reward: 830.000, mean reward: 0.954 [0.000, 100.000], mean action: 6.493 [0.000, 13.000], mean observation: 2.012 [0.000, 240.000], loss: 28.615261, mean_absolute_error: 0.984251, acc: 0.071480, mean_q: 0.999999 38717/100000: episode: 31, duration: 46.353s, episode steps: 1566, steps per second: 34, episode reward: 1180.000, mean reward: 0.754 [0.000, 100.000], mean action: 6.408 [0.000, 13.000], mean observation: 1.558 [0.000, 240.000], loss: 27.654753, mean_absolute_error: 0.983781, acc: 0.072777, mean_q: 0.999999 39922/100000: episode: 32, duration: 35.704s, episode steps: 1205, steps per second: 34, episode reward: 1080.000, mean reward: 0.896 [0.000, 100.000], mean action: 6.408 [0.000, 13.000], mean observation: 1.722 [0.000, 240.000], loss: 27.877979, mean_absolute_error: 0.982937, acc: 0.068361, mean_q: 0.999999 41911/100000: episode: 33, duration: 58.841s, episode steps: 1989, steps per second: 34, episode reward: 1560.000, mean reward: 0.784 [0.000, 100.000], mean action: 6.626 [0.000, 13.000], mean observation: 2.046 [0.000, 240.000], loss: 27.723555, mean_absolute_error: 0.982845, acc: 0.071220, mean_q: 0.999999 42709/100000: episode: 34, duration: 23.760s, episode steps: 798, steps per second: 34, episode reward: 880.000, mean reward: 1.103 [0.000, 100.000], mean action: 6.267 [0.000, 13.000], mean observation: 2.308 [0.000, 240.000], loss: 27.761700, mean_absolute_error: 0.982930, acc: 0.071429, mean_q: 0.999999 43787/100000: episode: 35, duration: 32.243s, episode steps: 1078, steps per second: 33, episode reward: 780.000, mean reward: 0.724 [0.000, 100.000], mean action: 6.662 [0.000, 13.000], mean observation: 2.266 [0.000, 240.000], loss: 27.965694, mean_absolute_error: 0.983301, acc: 0.072182, mean_q: 0.999999 46754/100000: episode: 36, duration: 88.179s, episode steps: 2967, steps per second: 34, episode reward: 2080.000, mean reward: 0.701 [0.000, 100.000], mean action: 6.551 [0.000, 13.000], mean observation: 2.167 [0.000, 240.000], loss: 30.416687, mean_absolute_error: 0.986695, acc: 0.070147, mean_q: 1.000000 48099/100000: episode: 37, duration: 40.026s, episode steps: 1345, steps per second: 34, episode reward: 1130.000, mean reward: 0.840 [0.000, 100.000], mean action: 6.546 [0.000, 13.000], mean observation: 1.729 [0.000, 240.000], loss: 32.340946, mean_absolute_error: 0.989692, acc: 0.068425, mean_q: 1.000000 48561/100000: episode: 38, duration: 13.956s, episode steps: 462, steps per second: 33, episode reward: 530.000, mean reward: 1.147 [0.000, 100.000], mean action: 6.578 [0.000, 13.000], mean observation: 2.210 [0.000, 240.000], loss: 25.409176, mean_absolute_error: 0.980768, acc: 0.071361, mean_q: 1.000000 done, took 1479.706 seconds
<keras.callbacks.History at 0x12150b908>
#Plot loss variations import matplotlib.pyplot as plt episodes = [1455,2423,3192,4037,4472,6292,7098,8897, 10784,11988,13541,14309,14855,15676,17303,18249, 21461,22917,23238,23586,26189,27369,28548,28919, 30695,32084,33770,35502,36281,37151,38717,39922, 41911,42709,43787,46754,48099,48561] loss = [21.74,36.16,32.86,33.93,31.62,31.17,28.76,27.21,31.20, 30.66,28.269,28.651,25.91,29.79,31.83,33.02,30.15,28.89, 26.92,25.30,27.16,27.08,24.59,30.02,26.48,28.96,30.13, 29.65,27.24,28.61,27.87,27.72,26.7,27.76,27.96,30.41,32.34,25.04] plt.plot(episodes, loss, 'r--') plt.axis([0, 50000, 0, 40]) plt.show()
## Save the model dqn.save_weights('dqn_{}_weights.h5f'.format(ENV_NAME_2), overwrite=True)
# Evaluate the algorithm for 10 episodes dqn.test(env, nb_episodes=10, visualize=True)
Testing for 10 episodes ... Episode 1: reward: 110.000, steps: 726 Episode 2: reward: 130.000, steps: 604 Episode 3: reward: 210.000, steps: 613 Episode 4: reward: 110.000, steps: 922 Episode 5: reward: 110.000, steps: 622 Episode 6: reward: 260.000, steps: 571 Episode 7: reward: 130.000, steps: 612 Episode 8: reward: 260.000, steps: 567 Episode 9: reward: 260.000, steps: 576 Episode 10: reward: 260.000, steps: 578
<keras.callbacks.History at 0x14961b860>
### Another Policy with dqn
policy = LinearAnnealedPolicy(EpsGreedyQPolicy(), attr="eps", value_max=.8, value_min=.01, value_test=.0, nb_steps=100000) dqn = DQNAgent(model=model, nb_actions=nb_actions, nb_steps_warmup=10, policy=policy, test_policy=policy, memory = memory, target_model_update=1e-2)
dqn.compile(Adam(lr=1e-3), metrics=['mae', 'acc'])
dqn.fit(env, nb_steps=50000, visualize=True, verbose=2)
Training for 50000 steps ... 2647/50000: episode: 1, duration: 78.745s, episode steps: 2647, steps per second: 34, episode reward: 1180.000, mean reward: 0.446 [0.000, 100.000], mean action: 5.080 [0.000, 13.000], mean observation: 1.496 [0.000, 240.000], loss: 29.992819, mean_absolute_error: 0.987530, acc: 0.366749, mean_q: 1.000000, mean_eps: 0.789505 5062/50000: episode: 2, duration: 70.523s, episode steps: 2415, steps per second: 34, episode reward: 1390.000, mean reward: 0.576 [0.000, 100.000], mean action: 4.961 [0.000, 13.000], mean observation: 2.056 [0.000, 240.000], loss: 29.211633, mean_absolute_error: 0.985632, acc: 0.362526, mean_q: 1.000000, mean_eps: 0.769553 6988/50000: episode: 3, duration: 56.540s, episode steps: 1926, steps per second: 34, episode reward: 1410.000, mean reward: 0.732 [0.000, 100.000], mean action: 4.895 [0.000, 13.000], mean observation: 2.147 [0.000, 240.000], loss: 30.044086, mean_absolute_error: 0.987133, acc: 0.360965, mean_q: 1.000000, mean_eps: 0.752406 7721/50000: episode: 4, duration: 21.421s, episode steps: 733, steps per second: 34, episode reward: 430.000, mean reward: 0.587 [0.000, 100.000], mean action: 4.943 [0.000, 13.000], mean observation: 2.584 [0.000, 240.000], loss: 26.033418, mean_absolute_error: 0.980401, acc: 0.356114, mean_q: 1.000000, mean_eps: 0.741903 9006/50000: episode: 5, duration: 37.220s, episode steps: 1285, steps per second: 35, episode reward: 1280.000, mean reward: 0.996 [0.000, 100.000], mean action: 4.936 [0.000, 13.000], mean observation: 1.588 [0.000, 240.000], loss: 26.786589, mean_absolute_error: 0.981151, acc: 0.347811, mean_q: 1.000000, mean_eps: 0.733932 9489/50000: episode: 6, duration: 14.189s, episode steps: 483, steps per second: 34, episode reward: 460.000, mean reward: 0.952 [0.000, 100.000], mean action: 4.818 [0.000, 13.000], mean observation: 2.550 [0.000, 240.000], loss: 27.920443, mean_absolute_error: 0.983796, acc: 0.344591, mean_q: 1.000000, mean_eps: 0.726949 10482/50000: episode: 7, duration: 29.064s, episode steps: 993, steps per second: 34, episode reward: 930.000, mean reward: 0.937 [0.000, 100.000], mean action: 4.862 [0.000, 13.000], mean observation: 2.175 [0.000, 240.000], loss: 32.332520, mean_absolute_error: 0.988627, acc: 0.349100, mean_q: 1.000000, mean_eps: 0.721118 11303/50000: episode: 8, duration: 24.297s, episode steps: 821, steps per second: 34, episode reward: 580.000, mean reward: 0.706 [0.000, 100.000], mean action: 4.653 [0.000, 13.000], mean observation: 2.164 [0.000, 240.000], loss: 25.372195, mean_absolute_error: 0.978653, acc: 0.348432, mean_q: 1.000000, mean_eps: 0.713953 12967/50000: episode: 9, duration: 49.121s, episode steps: 1664, steps per second: 34, episode reward: 1180.000, mean reward: 0.709 [0.000, 100.000], mean action: 4.603 [0.000, 13.000], mean observation: 1.855 [0.000, 240.000], loss: 26.680792, mean_absolute_error: 0.980070, acc: 0.343675, mean_q: 1.000000, mean_eps: 0.704137 14767/50000: episode: 10, duration: 52.906s, episode steps: 1800, steps per second: 34, episode reward: 2050.000, mean reward: 1.139 [0.000, 100.000], mean action: 4.512 [0.000, 13.000], mean observation: 2.010 [0.000, 240.000], loss: 26.146817, mean_absolute_error: 0.980223, acc: 0.340104, mean_q: 1.000000, mean_eps: 0.690455 17088/50000: episode: 11, duration: 68.414s, episode steps: 2321, steps per second: 34, episode reward: 1880.000, mean reward: 0.810 [0.000, 100.000], mean action: 4.256 [0.000, 13.000], mean observation: 2.131 [0.000, 240.000], loss: 28.392949, mean_absolute_error: 0.984508, acc: 0.342996, mean_q: 1.000000, mean_eps: 0.674177 17370/50000: episode: 12, duration: 8.740s, episode steps: 282, steps per second: 32, episode reward: 160.000, mean reward: 0.567 [0.000, 50.000], mean action: 4.316 [0.000, 13.000], mean observation: 2.853 [0.000, 240.000], loss: 33.064301, mean_absolute_error: 0.992362, acc: 0.329455, mean_q: 1.000000, mean_eps: 0.663895 17887/50000: episode: 13, duration: 15.122s, episode steps: 517, steps per second: 34, episode reward: 580.000, mean reward: 1.122 [0.000, 100.000], mean action: 4.555 [0.000, 13.000], mean observation: 2.274 [0.000, 240.000], loss: 24.594645, mean_absolute_error: 0.978975, acc: 0.335529, mean_q: 1.000000, mean_eps: 0.660739 18599/50000: episode: 14, duration: 20.679s, episode steps: 712, steps per second: 34, episode reward: 630.000, mean reward: 0.885 [0.000, 100.000], mean action: 3.958 [0.000, 13.000], mean observation: 2.229 [0.000, 240.000], loss: 26.505238, mean_absolute_error: 0.981136, acc: 0.337166, mean_q: 1.000000, mean_eps: 0.655884 19641/50000: episode: 15, duration: 30.318s, episode steps: 1042, steps per second: 34, episode reward: 1080.000, mean reward: 1.036 [0.000, 100.000], mean action: 4.361 [0.000, 13.000], mean observation: 1.825 [0.000, 240.000], loss: 30.079884, mean_absolute_error: 0.988954, acc: 0.330824, mean_q: 1.000000, mean_eps: 0.648956 20361/50000: episode: 16, duration: 20.884s, episode steps: 720, steps per second: 34, episode reward: 830.000, mean reward: 1.153 [0.000, 100.000], mean action: 4.181 [0.000, 13.000], mean observation: 2.156 [0.000, 240.000], loss: 30.022883, mean_absolute_error: 0.986804, acc: 0.341710, mean_q: 1.000000, mean_eps: 0.641996 20921/50000: episode: 17, duration: 16.383s, episode steps: 560, steps per second: 34, episode reward: 280.000, mean reward: 0.500 [0.000, 50.000], mean action: 4.029 [0.000, 13.000], mean observation: 2.809 [0.000, 240.000], loss: 32.525301, mean_absolute_error: 0.990283, acc: 0.343750, mean_q: 1.000000, mean_eps: 0.636940 22419/50000: episode: 18, duration: 43.820s, episode steps: 1498, steps per second: 34, episode reward: 1080.000, mean reward: 0.721 [0.000, 100.000], mean action: 4.009 [0.000, 13.000], mean observation: 1.739 [0.000, 240.000], loss: 29.147020, mean_absolute_error: 0.986433, acc: 0.338722, mean_q: 1.000000, mean_eps: 0.628811 23198/50000: episode: 19, duration: 22.840s, episode steps: 779, steps per second: 34, episode reward: 930.000, mean reward: 1.194 [0.000, 100.000], mean action: 4.067 [0.000, 13.000], mean observation: 2.250 [0.000, 240.000], loss: 28.683109, mean_absolute_error: 0.986974, acc: 0.344071, mean_q: 1.000000, mean_eps: 0.619817 24514/50000: episode: 20, duration: 38.692s, episode steps: 1316, steps per second: 34, episode reward: 1360.000, mean reward: 1.033 [0.000, 100.000], mean action: 4.226 [0.000, 13.000], mean observation: 2.471 [0.000, 240.000], loss: 30.828469, mean_absolute_error: 0.991295, acc: 0.365715, mean_q: 1.000000, mean_eps: 0.611542 26366/50000: episode: 21, duration: 53.995s, episode steps: 1852, steps per second: 34, episode reward: 1320.000, mean reward: 0.713 [0.000, 100.000], mean action: 4.002 [0.000, 13.000], mean observation: 1.992 [0.000, 240.000], loss: 30.103927, mean_absolute_error: 0.989485, acc: 0.372182, mean_q: 1.000000, mean_eps: 0.599028 27983/50000: episode: 22, duration: 47.561s, episode steps: 1617, steps per second: 34, episode reward: 1490.000, mean reward: 0.921 [0.000, 100.000], mean action: 3.993 [0.000, 13.000], mean observation: 1.986 [0.000, 240.000], loss: 31.202262, mean_absolute_error: 0.990682, acc: 0.369086, mean_q: 1.000000, mean_eps: 0.585325 29873/50000: episode: 23, duration: 55.033s, episode steps: 1890, steps per second: 34, episode reward: 1480.000, mean reward: 0.783 [0.000, 100.000], mean action: 3.815 [0.000, 13.000], mean observation: 1.960 [0.000, 240.000], loss: 33.852708, mean_absolute_error: 0.996705, acc: 0.380539, mean_q: 1.000000, mean_eps: 0.571473 30851/50000: episode: 24, duration: 29.198s, episode steps: 978, steps per second: 33, episode reward: 780.000, mean reward: 0.798 [0.000, 100.000], mean action: 3.757 [0.000, 13.000], mean observation: 2.426 [0.000, 240.000], loss: 30.200397, mean_absolute_error: 0.990111, acc: 0.375991, mean_q: 1.000000, mean_eps: 0.560144 31931/50000: episode: 25, duration: 31.562s, episode steps: 1080, steps per second: 34, episode reward: 1180.000, mean reward: 1.093 [0.000, 100.000], mean action: 3.903 [0.000, 13.000], mean observation: 1.719 [0.000, 240.000], loss: 35.342483, mean_absolute_error: 0.997397, acc: 0.402402, mean_q: 1.000000, mean_eps: 0.552015 32370/50000: episode: 26, duration: 12.899s, episode steps: 439, steps per second: 34, episode reward: 230.000, mean reward: 0.524 [0.000, 50.000], mean action: 3.752 [0.000, 13.000], mean observation: 3.075 [0.000, 240.000], loss: 31.779249, mean_absolute_error: 0.992009, acc: 0.407247, mean_q: 1.000000, mean_eps: 0.546015 34069/50000: episode: 27, duration: 49.556s, episode steps: 1699, steps per second: 34, episode reward: 1370.000, mean reward: 0.806 [0.000, 100.000], mean action: 3.727 [0.000, 13.000], mean observation: 1.739 [0.000, 240.000], loss: 32.917870, mean_absolute_error: 0.994308, acc: 0.397752, mean_q: 1.000000, mean_eps: 0.537570 35248/50000: episode: 28, duration: 34.380s, episode steps: 1179, steps per second: 34, episode reward: 930.000, mean reward: 0.789 [0.000, 100.000], mean action: 3.759 [0.000, 13.000], mean observation: 2.046 [0.000, 240.000], loss: 31.251266, mean_absolute_error: 0.990669, acc: 0.407125, mean_q: 1.000000, mean_eps: 0.526202 36460/50000: episode: 29, duration: 35.646s, episode steps: 1212, steps per second: 34, episode reward: 1080.000, mean reward: 0.891 [0.000, 100.000], mean action: 3.340 [0.000, 13.000], mean observation: 1.672 [0.000, 240.000], loss: 32.289888, mean_absolute_error: 0.991152, acc: 0.403208, mean_q: 1.000000, mean_eps: 0.516757 38501/50000: episode: 30, duration: 59.686s, episode steps: 2041, steps per second: 34, episode reward: 1350.000, mean reward: 0.661 [0.000, 100.000], mean action: 3.484 [0.000, 13.000], mean observation: 1.783 [0.000, 240.000], loss: 30.293467, mean_absolute_error: 0.990134, acc: 0.409343, mean_q: 1.000000, mean_eps: 0.503908 39551/50000: episode: 31, duration: 30.607s, episode steps: 1050, steps per second: 34, episode reward: 980.000, mean reward: 0.933 [0.000, 100.000], mean action: 3.148 [0.000, 13.000], mean observation: 1.775 [0.000, 240.000], loss: 32.976856, mean_absolute_error: 0.992399, acc: 0.419137, mean_q: 1.000000, mean_eps: 0.491699 40200/50000: episode: 32, duration: 18.901s, episode steps: 649, steps per second: 34, episode reward: 380.000, mean reward: 0.586 [0.000, 100.000], mean action: 3.661 [0.000, 13.000], mean observation: 2.205 [0.000, 240.000], loss: 29.077991, mean_absolute_error: 0.986476, acc: 0.389686, mean_q: 1.000000, mean_eps: 0.484988 42374/50000: episode: 33, duration: 63.338s, episode steps: 2174, steps per second: 34, episode reward: 1300.000, mean reward: 0.598 [0.000, 100.000], mean action: 9.507 [0.000, 13.000], mean observation: 1.670 [0.000, 240.000], loss: 31.056681, mean_absolute_error: 0.986676, acc: 0.079836, mean_q: 0.999999, mean_eps: 0.473837 43610/50000: episode: 34, duration: 36.134s, episode steps: 1236, steps per second: 34, episode reward: 880.000, mean reward: 0.712 [0.000, 100.000], mean action: 9.278 [0.000, 13.000], mean observation: 2.080 [0.000, 240.000], loss: 28.141218, mean_absolute_error: 0.981980, acc: 0.117440, mean_q: 1.000000, mean_eps: 0.460367 45651/50000: episode: 35, duration: 59.989s, episode steps: 2041, steps per second: 34, episode reward: 1480.000, mean reward: 0.725 [0.000, 100.000], mean action: 9.611 [0.000, 13.000], mean observation: 1.897 [0.000, 240.000], loss: 27.262516, mean_absolute_error: 0.981316, acc: 0.158623, mean_q: 1.000000, mean_eps: 0.447423 48137/50000: episode: 36, duration: 72.982s, episode steps: 2486, steps per second: 34, episode reward: 2150.000, mean reward: 0.865 [0.000, 100.000], mean action: 9.624 [0.000, 13.000], mean observation: 2.096 [0.000, 240.000], loss: 26.563936, mean_absolute_error: 0.980988, acc: 0.219831, mean_q: 1.000000, mean_eps: 0.429541 49183/50000: episode: 37, duration: 30.598s, episode steps: 1046, steps per second: 34, episode reward: 980.000, mean reward: 0.937 [0.000, 100.000], mean action: 9.748 [0.000, 13.000], mean observation: 2.036 [0.000, 240.000], loss: 30.250379, mean_absolute_error: 0.987904, acc: 0.271481, mean_q: 1.000000, mean_eps: 0.415590 done, took 1484.830 seconds
<keras.callbacks.History at 0x15bfc3b38>
episodes_p2 = [2647,5062,6988,7721,9006,9489, 10482,11303,12967,14767,17088,17370,17887,18599,19641, 20361,20921,22419,23198,24514,26366,27983,29873, 30851,31931,32370,34069,35248,36460,38501,39551, 40200,42374,43610] loss_p2 = [29.99,29.21,30.04,26.03,26.04,26.78,27.92,32.33,25.37,26.68,26.14,28.39, 33.06,24.59,26.5,30.07,30.02,32.05,25.4,29.14,28.68,30.82, 30.10,31.20, 33.85,30.20,35.34,31.25,32.28,30.29,32.97,29.07,31.01,28.14] plt.plot(episodes_p2, loss_p2, 'r--') plt.axis([0, 50000, 0, 40]) plt.show()
dqn.test(env, nb_episodes=10, visualize=True)
#SARSA Agent -- Reinforcement Learning from rl.agents.sarsa import SARSAAgent sarsa = SARSAAgent(model, nb_actions, policy=None, test_policy=None, gamma=0.99, nb_steps_warmup=10, train_interval=1) sarsa.compile(Adam(lr=1e-3), metrics=['mae', 'acc']) sarsa.fit(env, nb_steps=50000, visualize=True, verbose=2) sarsa.test(env, nb_episodes=10, visualize=True) | https://nbviewer.jupyter.org/github/SoyGema/OpenAI/blob/master/QLearning/dqn_asteroids_gym.ipynb | CC-MAIN-2019-13 | refinedweb | 4,942 | 84.03 |
Changelog¶
Python next¶
Release date: XXXX-XX-XX
Library¶
Documentation¶
gh-91207: Fix stylesheet not working in Windows CHM htmlhelp docs. Contributed by C.A.M. Gerlach.
bpo-47115: The documentation now lists which members of C structs are part of the Limited API/Stable ABI.
IDLE¶
Python 3.10.6 final¶
Release date: 2022-08-01
Security¶
gh-87389:
http.server: Fix an open redirection vulnerability in the HTTP server when an URI path starts with
//. Vulnerability discovered, and initial fix proposed, by Hamza Avvan.
gh-92888: Fix
memoryviewuse after free when accessing the backing buffer in certain cases.
Core and Builtins¶
gh-95355:
_PyPegen_Parser_Newnow properly detects token memory allocation errors. Patch by Honglin Zhu.
gh-94938: Fix error detection in some builtin functions when keyword argument name is an instance of a str subclass with overloaded
__eq__and
__hash__. Previously it could cause SystemError or other undesired behavior.
gh-94949:
ast.parse()will no longer parse parenthesized context managers when passed
feature_versionless than
(3, 9). Patch by Shantanu Jain.
gh-94947:
ast.parse()will no longer parse assignment expressions when passed
feature_versionless than
(3, 8). Patch by Shantanu Jain.
gh-94869: Fix the column offsets for some expressions in multi-line f-strings
astnodes. Patch by Pablo Galindo.
gh-91153: Fix an issue where a
bytearrayitem assignment could crash if it’s resized by the new value’s
__index__()method.
gh-94329: Compile and run code with unpacking of extremely large sequences (1000s of elements). Such code failed to compile. It now compiles and runs correctly.
gh-94360: Fixed a tokenizer crash when reading encoded files with syntax errors from
stdinwith non utf-8 encoded text. Patch by Pablo Galindo
gh-94192: Fix error for dictionary literals with invalid expression as value.
gh-93964: Strengthened compiler overflow checks to prevent crashes when compiling very large source files.
gh-93671: Fix some exponential backtrace case happening with deeply nested sequence patterns in match statements. Patch by Pablo Galindo
gh-93021: Fix the
__text_signature__for
__get__()methods implemented in C. Patch by Jelle Zijlstra.
gh-92930: Fixed a crash in
_pickle.cfrom mutating collections during
__reduce__or
persistent_id.
gh-92914: Always round the allocated size for lists up to the nearest even number.
gh-92858: Improve error message for some suites with syntax error before ‘:’
Library¶
gh-95339: Update bundled pip to 22.2.1.
gh-95045: Fix GC crash when deallocating
_lsprof.Profilerby untracking it before calling any callbacks. Patch by Kumar Aditya.
gh-95087: Fix IndexError in parsing invalid date in the
gh-95199: Upgrade bundled setuptools to 63.2.0.
gh-95194: Upgrade bundled pip to 22.2.
gh-93899: Fix check for existence of
os.EFD_CLOEXEC,
os.EFD_NONBLOCKand
os.EFD_SEMAPHOREflags on older kernel versions where these flags are not present. Patch by Kumar Aditya.
gh-95166: Fix
concurrent.futures.Executor.map()to cancel the currently waiting on future on an error - e.g. TimeoutError or KeyboardInterrupt.
gh-93157: Fix
fileinputmodule didn’t support
errorsoption when
inplaceis true.
gh-94821: Fix binding of unix socket to empty address on Linux to use an available address from the abstract namespace, instead of “0”.
gh-94736: Fix crash when deallocating an instance of a subclass of
_multiprocessing.SemLock. Patch by Kumar Aditya.
gh-94637:
SSLContext.set_default_verify_paths()now releases the GIL around
SSL_CTX_set_default_verify_pathscall. The function call performs I/O and CPU intensive work.
gh-94510: Re-entrant calls to
sys.setprofile()and
sys.settrace()now raise
RuntimeError. Patch by Pablo Galindo.
gh-92336: Fix bug where
linecache.getline()fails on bad files with
UnicodeDecodeErroror
SyntaxError. It now returns an empty string as per the documentation.
gh-89988: Fix memory leak in
pickle.Picklerwhen looking up
dispatch_table. Patch by Kumar Aditya.
gh-94254: Fixed types of
structmodule to be immutable. Patch by Kumar Aditya.
gh-94245: Fix pickling and copying of
typing.Tuple[()].
gh-94207: Made
_struct.StructGC-tracked in order to fix a reference leak in the
_structmodule.
gh-94101: Manual instantiation of
ssl.SSLSessionobjects is no longer allowed as it lead to misconfigured instances that crashed the interpreter when attributes where accessed on them.
gh-84753:
inspect.iscoroutinefunction(),
inspect.isgeneratorfunction(), and
inspect.isasyncgenfunction()now properly return
Truefor duck-typed function-like objects like instances of
unittest.mock.AsyncMock.
This makes
inspect.iscoroutinefunction()consistent with the behavior of
asyncio.iscoroutinefunction(). Patch by Mehdi ABAAKOUK.
gh-83499: Fix double closing of file description in
tempfile.
gh-79512: Fixed names and
__module__value of
weakrefclasses
ReferenceType,
ProxyType,
CallableProxyType. It makes them pickleable.
gh-90494:
copy.copy()and
copy.deepcopy()now always raise a TypeError if
__reduce__()returns a tuple with length 6 instead of silently ignore the 6th item or produce incorrect result.
gh-90549: Fix a multiprocessing bug where a global named resource (such as a semaphore) could leak when a child process is spawned (as opposed to forked).
gh-79579:
sqlite3now correctly detects DML queries with leading comments. Patch by Erlend E. Aasland.
gh-93421: Update
sqlite3.Cursor.rowcountwhen a DML statement has run to completion. This fixes the row count for SQL queries like
UPDATE ... RETURNING. Patch by Erlend E. Aasland.
gh-91810: Suppress writing an XML declaration in open files in
ElementTree.write()with
encoding='unicode'and
xml_declaration=None.
gh-93353: Fix the
importlib.resources.as_file()context manager to remove the temporary file if destroyed late during Python finalization: keep a local reference to the
os.remove()function. Patch by Victor Stinner.
gh-83658: Make
multiprocessing.Poolraise an exception if
maxtasksperchildis not
Noneor a positive int.
gh-74696:
shutil.make_archive()no longer temporarily changes the current working directory during creation of standard
.zipor tar archives.
gh-91577: Move imports in
SharedMemorymethods to module level so that they can be executed late in python finalization.
bpo-47231: Fixed an issue with inconsistent trailing slashes in tarfile longname directories.
bpo-46755: In
QueueHandler, clear
stack_infofrom
LogRecordto prevent stack trace from being written twice.
bpo-46053: Fix OSS audio support on NetBSD.
bpo-46197: Fix
ensurepipenvironment isolation for subprocess running
pip.
bpo-45924: Fix
asyncioincorrect traceback when future’s exception is raised multiple times. Patch by Kumar Aditya.
bpo-34828:
sqlite3.Connection.iterdump()now handles databases that use
AUTOINCREMENTin one or more tables.
Documentation¶
gh-94321: Document the PEP 246 style protocol type
sqlite3.PrepareProtocol.
gh-86128: Document a limitation in ThreadPoolExecutor where its exit handler is executed before any handlers in atexit.
gh-61162: Clarify
sqlite3behavior when Using the connection as a context manager.
gh-87260: Align
sqlite3argument specs with the actual implementation.
gh-86986: The minimum Sphinx version required to build the documentation is now 3.2.
gh-88831: Augmented documentation of asyncio.create_task(). Clarified the need to keep strong references to tasks and added a code snippet detailing how to to this.
bpo-47161: Document that
pathlib.PurePathdoes not collapse initial double slashes because they denote UNC paths.
Tests¶
gh-95280: Fix problem with
test_ssl
test_get_cipherson systems that require perfect forward secrecy (PFS) ciphers.
gh-95212: Make multiprocessing test case
test_shared_memory_recreateparallel-safe.
gh-91330: Added more tests for
dataclassesto cover behavior with data descriptor-based fields.
# Write your Misc/NEWS entry below. It should be a simple ReST paragraph. # Don’t start with “- Issue #<n>: ” or “- gh-issue-<n>: ” or that sort of stuff. ###########################################################################
gh-94208:
test_sslis now checking for supported TLS version and protocols in more tests.
gh-93951: In test_bdb.StateTestCase.test_skip, avoid including auxiliary importers.
gh-93957: Provide nicer error reporting from subprocesses in test_venv.EnsurePipTest.test_with_pip.
gh-57539: Increase calendar test coverage for
calendar.LocaleTextCalendar.formatweekday().
gh-92886: Fixing tests that fail when running with optimizations (
-O) in
test_zipimport.py
bpo-47016: Create a GitHub Actions workflow for verifying bundled pip and setuptools. Patch by Illia Volochii and Adam Turner.
Build¶
gh-94841: Fix the possible performance regression of
PyObject_Free()compiled with MSVC version 1932.
bpo-45816: Python now supports building with Visual Studio 2022 (MSVC v143, VS Version 17.0). Patch by Jeremiah Vivian.
Windows¶
gh-90844: Allow virtual environments to correctly launch when they have spaces in the path.
gh-92841:
asynciono longer throws
RuntimeError: Event loop is closedon interpreter exit after asynchronous socket activity. Patch by Oleg Iarygin.
bpo-42658: Support native Windows case-insensitive path comparisons by using
LCMapStringExinstead of
str.lower()in
ntpath.normcase(). Add
LCMapStringExto the
_winapimodule.
IDLE¶
gh-95511: Fix the Shell context menu copy-with-prompts bug of copying an extra line when one selects whole lines.
gh-95471: In the Edit menu, move
Select Alland add a new separator.
gh-95411: Enable using IDLE’s module browser with .pyw files.
gh-89610: Add .pyi as a recognized extension for IDLE on macOS. This allows opening stub files by double clicking on them in the Finder.
Tools/Demos¶
C API¶
gh-94930: Fix
SystemErrorraised when
PyArg_ParseTupleAndKeywords()is used with
#in
(...)but without
PY_SSIZE_T_CLEANdefined.
gh-94864: Fix
PyArg_Parse*with deprecated format units “u” and “Z”. It returned 1 (success) when warnings are turned into exceptions.
Python 3.10.5 final¶
Release date: 2022-06-06
Core and Builtins¶
gh-93418: Fixed an assert where an f-string has an equal sign ‘=’ following an expression, but there’s no trailing brace. For example, f”{i=”.
gh-91924: Fix
__ltrace__debug feature if the stdout encoding is not UTF-8. Patch by Victor Stinner.
gh-93061: Backward jumps after
async forloops are no longer given dubious line numbers.
gh-93065: Fix contextvars HAMT implementation to handle iteration over deep trees.
The bug was discovered and fixed by Eli Libman. See MagicStack/immutables#84 for more details.
gh-92311: Fixed a bug where setting
frame.f_linenoto jump over a list comprehension could misbehave or crash.
gh-92112: Fix crash triggered by an evil custom
mro()on a metaclass.
gh-92036: Fix a crash in subinterpreters related to the garbage collector. When a subinterpreter is deleted, untrack all objects tracked by its GC. To prevent a crash in deallocator functions expecting objects to be tracked by the GC, leak a strong reference to these objects on purpose, so they are never deleted and their deallocator functions are not called. Patch by Victor Stinner.
gh-91421: Fix a potential integer overflow in _Py_DecodeUTF8Ex.
bpo-47212: Raise
IndentationErrorinstead of
SyntaxErrorfor a bare
exceptwith no following indent. Improve
SyntaxErrorlocations for an un-parenthesized generator used as arguments. Patch by Matthieu Dartiailh.
bpo-47182: Fix a crash when using a named unicode character like
"\N{digit nine}"after the main interpreter has been initialized a second time.
bpo-46775: Some Windows system error codes(>= 10000) are now mapped into the correct errno and may now raise a subclass of
OSError. Patch by Dong-hee Na.
bpo-47117: Fix a crash if we fail to decode characters in interactive mode if the tokenizer buffers are uninitialized. Patch by Pablo Galindo.
bpo-39829: Removed the
__len__()call when initializing a list and moved initializing to
list_extend. Patch by Jeremiah Pascual.
bpo-46962: Classes and functions that unconditionally declared their docstrings ignoring the
--without-doc-stringscompilation flag no longer do so.
The classes affected are
ctypes.UnionType,
pickle.PickleBuffer,
testcapi.RecursingInfinitelyError, and
types.GenericAlias.
The functions affected are 24 methods in
ctypes.
Patch by Oleg Iarygin.
bpo-36819: Fix crashes in built-in encoders with error handlers that return position less or equal than the starting position of non-encodable characters.
Library¶
gh-93156: Accessing the
pathlib.PurePath.parentssequence of an absolute path using negative index values produced incorrect results.
gh-89973: Fix
re.errorraised in
fnmatchif the pattern contains a character range with upper bound lower than lower bound (e.g.
[c-a]). Now such ranges are interpreted as empty ranges.
gh-93010: In a very special case, the email package tried to append the nonexistent
InvalidHeaderErrorto the defect list. It should have been
InvalidHeaderDefect.
gh-92839: Fixed crash resulting from calling bisect.insort() or bisect.insort_left() with the key argument not equal to None.
gh-91581:
utcfromtimestamp()no longer attempts to resolve
foldin the pure Python implementation, since the fold is never 1 in UTC. In addition to being slightly faster in the common case, this also prevents some errors when the timestamp is close to
datetime.min. Patch by Paul Ganssle.
gh-92530: Fix an issue that occurred after interrupting
threading.Condition.notify().
gh-92049: Forbid pickling constants
re._constants.SUCCESSetc. Previously, pickling did not fail, but the result could not be unpickled.
bpo-47029: Always close the read end of the pipe used by
multiprocessing.Queueafter the last write of buffered data to the write end of the pipe to avoid
BrokenPipeErrorat garbage collection and at
multiprocessing.Queue.close()calls. Patch by Géry Ogam.
gh-91401: Provide a fail-safe way to disable
subprocessuse of
vfork()via a private
subprocess._USE_VFORKattribute. While there is currently no known need for this, if you find a need please only set it to
False. File a CPython issue as to why you needed it and link to that from a comment in your code. This attribute is documented as a footnote in 3.11.
gh-91910: Add missing f prefix to f-strings in error messages from the
multiprocessingand
asynciomodules.
gh-91810:
ElementTreemethod
write()and function
tostring()now use the text file’s encoding (“UTF-8” if not available) instead of locale encoding in XML declaration when
encoding="unicode"is specified.
gh-91832: Add
requiredattribute to
argparse.Actionrepr output.
gh-91734: Fix OSS audio support on Solaris.
gh-91700: Compilation of regular expression containing a conditional expression
(?(group)...)now raises an appropriate
re.errorif the group number refers to not defined group. Previously an internal RuntimeError was raised.
gh-91676: Fix
unittest.IsolatedAsyncioTestCaseto shutdown the per test event loop executor before returning from its
runmethod so that a not yet stopped or garbage collected executor state does not persist beyond the test.
gh-90568: Parsing
\Nescapes of Unicode Named Character Sequences in a
regular expressionraises now
re.errorinstead of
TypeError.
gh-91595: Fix the comparison of character and integer inside
Tools.gdb.libpython.write_repr(). Patch by Yu Liu.
gh-90622: Worker processes for
concurrent.futures.ProcessPoolExecutorare no longer spawned on demand (a feature added in 3.9) when the multiprocessing context start method is
"fork"as that can lead to deadlocks in the child processes due to a fork happening while threads are running.
gh-91575: Update case-insensitive matching in the
remodule to the latest Unicode version.
gh-91581: Remove an unhandled error case in the C implementation of calls to
datetime.fromtimestampwith no time zone (i.e. getting a local time from an epoch timestamp). This should have no user-facing effect other than giving a possibly more accurate error message when called with timestamps that fall on 10000-01-01 in the local time. Patch by Paul Ganssle.
bpo-47260: Fix
os.closerange()potentially being a no-op in a Linux seccomp sandbox.
bpo-39064:
zipfile.ZipFilenow raises
zipfile.BadZipFileinstead of
ValueErrorwhen reading a corrupt zip file in which the central directory offset is negative.
bpo-47151: When subprocess tries to use vfork, it now falls back to fork if vfork returns an error. This allows use in situations where vfork isn’t allowed by the OS kernel.
bpo-27929: Fix
asyncio.loop.sock_connect()to only resolve names for
socket.AF_INETor
socket.AF_INET6families. Resolution may not make sense for other families, like
socket.AF_BLUETOOTHand
socket.AF_UNIX.
bpo-43323: Fix errors in the
bpo-47101:
hashlib.algorithms_availablenow lists only algorithms that are provided by activated crypto providers on OpenSSL 3.0. Legacy algorithms are not listed unless the legacy provider has been loaded into the default OSSL context.
bpo-46787: Fix
concurrent.futures.ProcessPoolExecutorexception memory leak
bpo-45393: Fix the formatting for
await xand
not xin the operator precedence table when using the
help()system.
bpo-46415: Fix ipaddress.ip_{address,interface,network} raising TypeError instead of ValueError if given invalid tuple as address parameter.
bpo-28249: Set
doctest.DocTest.linenoto
Nonewhen object does not have
__doc__.
bpo-45138: Fix a regression in the
sqlite3trace callback where bound parameters were not expanded in the passed statement string. The regression was introduced in Python 3.10 by bpo-40318. Patch by Erlend E. Aasland.
bpo-44493: Add missing terminated NUL in sockaddr_un’s length
This was potentially observable when using non-abstract AF_UNIX datagram sockets to processes written in another programming language.
bpo-42627: Fix incorrect parsing of Windows registry proxy settings
bpo-36073: Raise
ProgrammingErrorinstead of segfaulting on recursive usage of cursors in
sqlite3converters. Patch by Sergey Fedoseev.
Documentation¶
gh-86438: Clarify that
-Wand
PYTHONWARNINGSare matched literally and case-insensitively, rather than as regular expressions, in
warnings.
gh-92240: Added release dates for “What’s New in Python 3.X” for 3.0, 3.1, 3.2, 3.8 and 3.10
gh-91888: Add a new
ghrole to the documentation to link to GitHub issues.
gh-91783: Document security issues concerning the use of the function
shutil.unpack_archive()
gh-91547: Remove “Undocumented modules” page.
bpo-44347: Clarify the meaning of dirs_exist_ok, a kwarg of
shutil.copytree().
bpo-38668: Update the introduction to documentation for
os.pathto remove warnings that became irrelevant after the implementations of PEP 383 and PEP 529.
bpo-47138: Pin Jinja to a version compatible with Sphinx version 3.2.1.
bpo-46962: All docstrings in code snippets are now wrapped into
PyDoc_STR()to follow the guideline of PEP 7’s Documentation Strings paragraph. Patch by Oleg Iarygin.
bpo-26792: Improve the docstrings of
runpy.run_module()and
runpy.run_path(). Original patch by Andrew Brezovsky.
bpo-40838: Document that
inspect.getdoc(),
inspect.getmodule(), and
inspect.getsourcefile()might return
None.
bpo-45790: Adjust inaccurate phrasing in Defining Extension Types: Tutorial about the
ob_basefield and the macros used to access its contents.
bpo-42340: Document that in some circumstances
KeyboardInterruptmay cause the code to enter an inconsistent state. Provided a sample workaround to avoid it if needed.
bpo-41233: Link the errnos referenced in
Doc/library/exceptions.rstto their respective section in
Doc/library/errno.rst, and vice versa. Previously this was only done for EINTR and InterruptedError. Patch by Yan “yyyyyyyan” Orestes.
bpo-38056: Overhaul the Error Handlers documentation in
codecs.
bpo-13553: Document tkinter.Tk args.
Tests¶
gh-92886: Fixing tests that fail when running with optimizations (
-O) in
test_imaplib.py.
gh-92670: Skip
test_shutil.TestCopy.test_copyfile_nonexistent_dirtest on AIX as the test uses a trailing slash to force the OS consider the path as a directory, but on AIX the trailing slash has no effect and is considered as a file.
gh-91904: Fix initialization of
PYTHONREGRTEST_UNICODE_GUARDwhich prevented running regression tests on non-UTF-8 locale.
gh-91607: Fix
test_concurrent_futuresto test the correct multiprocessing start method context in several cases where the test logic mixed this up.
bpo-47205: Skip test for
sched_getaffinity()and
sched_setaffinity()error case on FreeBSD.
bpo-47104: Rewrite
asyncio.to_thread()tests to use
unittest.IsolatedAsyncioTestCase.
bpo-29890: Add tests for
ipaddress.IPv4Interfaceand
ipaddress.IPv6Interfaceconstruction with tuple arguments. Original patch and tests by louisom.
Build¶
Windows¶
gh-92984: Explicitly disable incremental linking for non-Debug builds
bpo-47194: Update
zlibto v1.2.12 to resolve CVE-2018-25032.
bpo-46785: Fix race condition between
os.stat()and unlinking a file on Windows, by using errors codes returned by
FindFirstFileW()when appropriate in
win32_xstat_impl.
bpo-40859: Update Windows build to use xz-5.2.5
Tools/Demos¶
Python 3.10.4 final¶
Release date: 2022-03-23
Core and Builtins¶
bpo-46968: Check for the existence of the “sys/auxv.h” header in
faulthandlerto avoid compilation problems in systems where this header doesn’t exist. Patch by Pablo Galindo
Library¶
bpo-23691: Protect the
re.finditer()iterator from re-entering.
bpo-42369: Fix thread safety of
zipfile._SharedFile.tell()to avoid a “zipfile.BadZipFile: Bad CRC-32 for file” exception when reading a
ZipFilefrom multiple threads.
bpo-38256: Fix
binascii.crc32()when it is compiled to use zlib’c crc32 to work properly on inputs 4+GiB in length instead of returning the wrong result. The workaround prior to this was to always feed the function data in increments smaller than 4GiB or to just call the zlib module function.
bpo-39394: A warning about inline flags not at the start of the regular expression now contains the position of the flag.
bpo-47061: Deprecate the various modules listed by PEP 594:
aifc, asynchat, asyncore, audioop, cgi, cgitb, chunk, crypt, imghdr, msilib, nntplib, nis, ossaudiodev, pipes, smtpd, sndhdr, spwd, sunau, telnetlib, uu, xdrlib
bpo-2604: Fix bug where doctests using globals would fail when run multiple times.
bpo-45997: Fix
asyncio.Semaphorere-aquiring FIFO order.
bpo-47022: The
asynchat,
asyncoreand
smtpdmodules have been deprecated since at least Python 3.6. Their documentation and deprecation warnings and have now been updated to note they will removed in Python 3.12 (PEP 594).
bpo-46421: Fix a unittest issue where if the command was invoked as
python -m unittestand the filename(s) began with a dot (.), a
ValueErroris returned.
bpo-40296: Fix supporting generic aliases in
pydoc.
Python 3.10.3 final¶
Release date: 2022-03-16
Core and Builtins¶
bpo-46940: Avoid overriding
AttributeErrormetadata information for nested attribute access calls. Patch by Pablo Galindo.
bpo-46852: Rename the private undocumented
float.__set_format__()method to
float.__setformat__()to fix a typo introduced in Python 3.7. The method is only used by test_float. Patch by Victor Stinner.
bpo-46794: Bump up the libexpat version into 2.4.6
bpo-46820: Fix parsing a numeric literal immediately (without spaces) followed by “not in” keywords, like in
1not in x. Now the parser only emits a warning, not a syntax error.
bpo-46762: Fix an assert failure in debug builds when a ‘<’, ‘>’, or ‘=’ is the last character in an f-string that’s missing a closing right brace.
bpo-46724: Make sure that all backwards jumps use the
JUMP_ABSOLUTEinstruction, rather than
JUMP_FORWARDwith an argument of
(2**32)+offset.
bpo-46732: Correct the docstring for the
__bool__()method. Patch by Jelle Zijlstra.
bpo-46707: Avoid potential exponential backtracking when producing some syntax errors involving lots of brackets. Patch by Pablo Galindo.
bpo-40479: Add a missing call to
va_end()in
Modules/_hashopenssl.c.
bpo-46615: When iterating over sets internally in
setobject.c, acquire strong references to the resulting items from the set. This prevents crashes in corner-cases of various set operations where the set gets mutated.
bpo-45773: Remove two invalid “peephole” optimizations from the bytecode compiler.
bpo-43721: Fix docstrings of
getter,
setter, and
deleterto clarify that they create a new copy of the property.-46339: Fix a crash in the parser when retrieving the error text for multi-line f-strings expressions that do not start in the first line of the string. Patch by Pablo Galindo
bpo-46240: Correct the error message for unclosed parentheses when the tokenizer doesn’t reach the end of the source when the error is reported. Patch by Pablo Galindo
bpo-46091: Correctly calculate indentation levels for lines with whitespace character that are ended by line continuation characters. Patch by Pablo Galindo
Library¶
bpo-43253: Fix a crash when closing transports where the underlying socket handle is already invalid on the Proactor event loop.
bpo-47004: Apply bugfixes from importlib_metadata 4.11.3, including bugfix for EntryPoint.extras, which was returning match objects and not the extras strings.
bpo-46985: Upgrade pip wheel bundled with ensurepip (pip 22.0.4)
bpo-46968:
faulthandler: On Linux 5.14 and newer, dynamically determine size of signal handler stack size CPython allocates using
getauxval(AT_MINSIGSTKSZ). This changes allows for Python extension’s request to Linux kernel to use AMX_TILE instruction set on Sapphire Rapids Xeon processor to succeed, unblocking use of the ISA in frameworks.
bpo-46955: Expose
asyncio.base_events.Serveras
asyncio.Server. Patch by Stefan Zabka.
bpo-23325: The
signalmodule no longer assumes that
SIG_IGNand
SIG_DFLare small int singletons.
bpo-46932: Update bundled libexpat to 2.4.7
bpo-25707: Fixed a file leak in
xml.etree.ElementTree.iterparse()when the iterator is not exhausted. Patch by Jacob Walls.
bpo-44886: Inherit asyncio proactor datagram transport from
asyncio.DatagramTransport.
bpo-46827: Support UDP sockets in
asyncio.loop.sock_connect()for selector-based event loops. Patch by Thomas Grainger.
bpo-46811: Make test suite support Expat >=2.4.5
bpo-46252: Raise
TypeErrorif
ssl.SSLSocketis passed to transport-based APIs.
bpo-46784: Fix libexpat symbols collisions with user dynamically loaded or statically linked libexpat in embedded Python.
bpo-39327:
shutil.rmtree()can now work with VirtualBox shared folders when running from the guest operating-system.
bpo-46756: Fix a bug in
urllib.request.HTTPPasswordMgr.find_user_password()and
urllib.request.HTTPPasswordMgrWithPriorAuth.is_authenticated()which allowed to bypass authorization. For example, access to URI
example.org/foobarwas allowed if the user was authorized for URI
example.org/foo.
bpo-46643: In
typing.get_type_hints(), support evaluating stringified
ParamSpecArgsand
ParamSpecKwargsannotations. Patch by Gregory Beauregard.
bpo-45863: When the
tarfilemodule creates a pax format archive, it will put an integer representation of timestamps in the ustar header (if possible) for the benefit of older unarchivers, in addition to the existing full-precision timestamps in the pax extended header.
bpo-46676: Make
typing.ParamSpecargs and kwargs equal to themselves. Patch by Gregory Beauregard.
bpo-46672: Fix
NameErrorin
asyncio.gather()when initial type check fails.
bpo-46655: In
typing.get_type_hints(), support evaluating bare stringified
TypeAliasannotations. Patch by Gregory Beauregard.
bpo-45948: Fixed a discrepancy in the C implementation of the
xml.etree.ElementTreemodule. Now, instantiating an
xml.etree.ElementTree.XMLParserwith a
target=Nonekeyword provides a default
xml.etree.ElementTree.TreeBuildertarget as the Python implementation does.
bpo-46521: Fix a bug in the
codeopmodule that was incorrectly identifying invalid code involving string quotes as valid code.
bpo-46581: Brings
ParamSpecpropagation for
GenericAliasin line with
Concatenate(and others).
bpo-46591: Make the IDLE doc URL on the About IDLE dialog clickable.
bpo-46400: expat: Update libexpat from 2.4.1 to 2.4.4
bpo-46487: Add the
get_write_buffer_limitsmethod to
asyncio.transports.WriteTransportand to the SSL transport.
bpo-45173: Note the configparser deprecations will be removed in Python 3.12.-46436: Fix command-line option
-d/
--directoryin module
http.serverwhich is ignored when combined with command-line option
--cgi. Patch by Géry Ogam.-46333: The
__eq__()and
__hash__()methods of
typing.ForwardRefnow honor the
moduleparameter of
typing.ForwardRef. Forward references from different modules are now differentiated.
bpo-46246: Add missing
__slots__to
importlib.metadata.DeprecatedList. Patch by Arie Bovenberg.
bpo-46266: Improve day constants in
calendar.
Now all constants (
MONDAY…
SUNDAY) are documented, tested, and added to
__all__.
bpo-46232: The
sslmodule now handles certificates with bit strings in DN correctly.
bpo-43118: Fix a bug in
inspect.signature()that was causing it to fail on some subclasses of classes with a
__text_signature__referencing module globals. Patch by Weipeng Hong.
bpo-26552: Fixed case where failing
asyncio.ensure_future()did not close the coroutine. Patch by Kumar Aditya.
bpo-21987: Fix an issue with
tarfile.TarFile.getmember()getting a directory name with a trailing slash.
bpo-20392: Fix inconsistency with uppercase file extensions in
MimeTypes.guess_type(). Patch by Kumar Aditya.
bpo-46080: Fix exception in argparse help text generation if a
argparse.BooleanOptionalActionargument’s default is
argparse.SUPPRESSand it has
helpspecified. Patch by Felix Fontein.
bpo-44439: Fix
.write()method of a member file in
ZipFile, when the input data is an object that supports the buffer protocol, the file length may be wrong.
bpo-45703: When a namespace package is imported before another module from the same namespace is created/installed in a different
sys.pathlocation while the program is running, calling the
importlib.invalidate_caches()function will now also guarantee the new module is noticed.
bpo-24959: Fix bug where
unittestsometimes drops frames from tracebacks of exceptions raised in tests.
bpo-44791: Fix substitution of
ParamSpecin
Concatenatewith different parameter expressions. Substitution with a list of types returns now a tuple of types. Substitution with
Concatenatereturns now a
Concatenatewith concatenated lists of arguments.
bpo-14156: argparse.FileType now supports an argument of ‘-’ in binary mode, returning the .buffer attribute of sys.stdin/sys.stdout as appropriate. Modes including ‘x’ and ‘a’ are treated equivalently to ‘w’ when argument is ‘-’. Patch contributed by Josh Rosenberg
Documentation¶
Tests¶
bpo-46913: Fix test_faulthandler.test_sigfpe() if Python is built with undefined behavior sanitizer (UBSAN): disable UBSAN on the faulthandler_sigfpe() function. Patch by Victor Stinner.
bpo-46708: Prevent default asyncio event loop policy modification warning after
test_asyncioexecution.
bpo-46678: The function
make_legacy_pycin
Lib/test/support/import_helper.pyno longer fails when
PYTHONPYCACHEPREFIXis set to a directory on a different device from where tempfiles are stored.
bpo-46616: Ensures
test_importlib.test_windowscleans up registry keys after completion.
bpo-44359: test_ftplib now silently ignores socket errors to prevent logging unhandled threading exceptions. Patch by Victor Stinner.
bpo-46542: Fix a Python crash in test_lib2to3 when using Python built in debug mode: limit the recursion limit. Patch by Victor Stinner.
bpo-46576: test_peg_generator now disables compiler optimization when testing compilation of its own C extensions to significantly speed up the testing on non-debug builds of CPython.
bpo-47032: Ensure Windows install builds fail correctly with a non-zero exit code when part of the build fails.
bpo-47024: Update OpenSSL to 1.1.1n for macOS installers and all Windows builds.
bpo-38472: Fix GCC detection in setup.py when cross-compiling. The C compiler is now run with LC_ALL=C. Previously, the detection failed with a German locale.
bpo-46513: configure no longer uses
AC_C_CHAR_UNSIGNEDmacro and
pyconfig.hno longer defines reserved symbol
__CHAR_UNSIGNED__.
bpo-45925: Update Windows installer to use SQLite 3.37.2.
Windows¶
bpo-44549: Update bzip2 to 1.0.8 in Windows builds to mitigate CVE-2016-3189 and CVE-2019-12900
bpo-46948: Prevent CVE-2022-26488 by ensuring the Add to PATH option in the Windows installer uses the correct path when being repaired.
bpo-46638: Ensures registry virtualization is consistently disabled. For 3.10 and earlier, it remains enabled (some registry writes are protected), while for 3.11 and later it is disabled (registry modifications affect all applications).
macOS¶
IDLE¶
bpo-46630: Make query dialogs on Windows start with a cursor in the entry box.
bpo-45296: Clarify close, quit, and exit in IDLE. In the File menu, ‘Close’ and ‘Exit’ are now ‘Close Window’ (the current one) and ‘Exit’ is now ‘Exit IDLE’ (by closing all windows). In Shell, ‘quit()’ and ‘exit()’ mean ‘close Shell’. If there are no other windows, this also exits IDLE.
bpo-45447: Apply IDLE syntax highlighting to
pyifiles. Patch by Alex Waygood and Terry Jan Reedy.
C API¶
Python 3.10.2 final¶
Release date: 2022-01-13
Core and Builtins¶
bpo-46347: Fix memory leak in PyEval_EvalCodeEx.
bpo-46289: ASDL declaration of
FormattedValuehas changed to reflect
conversionfield is not optional.
bpo-46237: Fix the line number of tokenizer errors inside f-strings. Patch by Pablo Galindo.
bpo-46006: Fix a regression when a type method like
__init__()is modified in a subinterpreter. Fix a regression in
_PyUnicode_EqualToASCIIId()and type
update_slot(). Revert the change which made the Unicode dictionary of interned strings compatible with subinterpreters: the internal interned dictionary is shared again by all interpreters. Patch by Victor Stinner.
bpo-46085: Fix iterator cache mechanism of
OrderedDict.
bpo-46110: Add a maximum recursion check to the PEG parser to avoid stack overflow. Patch by Pablo Galindo
bpo-46054: Fix parser error when parsing non-utf8 characters in source files. Patch by Pablo Galindo.
bpo-46042: Improve the location of the caret in
SyntaxErrorexceptions emitted by the symbol table. Patch by Pablo Galindo.
bpo-46025: Fix a crash in the
atexitmodule involving functions that unregister themselves before raising exceptions. Patch by Pablo Galindo.
bpo-46009: Restore behavior from 3.9 and earlier when sending non-None to newly started generator. In 3.9 this did not affect the state of the generator. In 3.10.0 and 3.10.1
gen_func().send(0)is equivalent to
gen_func().throw(TypeError(...)which exhausts the generator. In 3.10.2 onward, the behavior has been reverted to that of 3.9.
bpo-46000: Improve compatibility of the
cursesmodule with NetBSD curses.
bpo-46004: Fix the
SyntaxErrorlocation for errors involving for loops with invalid targets. Patch by Pablo Galindo
bpo-42918: Fix bug where the built-in
compile()function did not always raise a
SyntaxErrorwhen passed multiple statements in ‘single’ mode. Patch by Weipeng Hong.-45755:
typinggeneric aliases now reveal the class attributes of the original generic class when passed to
dir(). This was the behavior up to Python 3.6, but was changed in 3.7-3.9.
bpo-13236:
unittest.TextTestResultand
unittest.TextTestRunnerflush now the output stream more often.
bpo-42378: Fixes the issue with log file being overwritten when
logging.FileHandleris used in
atexitwith filemode set to
'w'. Note this will cause the message in atexit not being logged if the log stream is already closed due to shutdown of logging.
Documentation¶
bpo-46120: State that
|is preferred for readability over
Unionin the
typingdocs.
bpo-46040: Fix removal Python version for
@asyncio.coroutine, the correct value is 3.11.
bpo-19737: Update the documentation for the
globals()function.
bpo-45840: Improve cross-references in the documentation for the data model.-46114: Fix test case for OpenSSL 3.0.1 version. OpenSSL 3.0 uses
0xMNN00PP0L.
Build¶
macOS¶
C API¶
bpo-46236: Fix a bug in
PyFunction_GetAnnotations()that caused it to return a
tupleinstead of a
dict.
Python 3.10.1 final¶
Release date: 2021-12-06
Core and Builtins¶
bpo-42268: Fail the configure step if the selected compiler doesn’t support memory sanitizer. Patch by Pablo Galindo
bpo-45727: Refine the custom syntax error that suggests that a comma may be missing to trigger only when the expressions are detected between parentheses or brackets. Patch by Pablo Galindo
bpo-45614: Fix
tracebackdisplay for exceptions with invalid module name.
bpo-45848: Allow the parser to obtain error lines directly from encoded files. Patch by Pablo Galindo
bpo-45826: Fixed a crash when calling
.with_traceback(None)on
NameError. This occurs internally in
unittest.TestCase.assertRaises()..
bpo-45738: Fix computation of error location for invalid continuation characters in the parser. Patch by Pablo Galindo.
bpo-45773: Fix a compiler hang when attempting to optimize certain jump patterns.
bpo-45716: Improve the
SyntaxErrormessage when using
True,
Noneor
Falseas keywords in a function call. Patch by Pablo Galindo.
bpo-45688:
sys.stdlib_module_namesnow contains the macOS-specific module
_scproxy.
bpo-30570: Fixed a crash in
issubclass()from infinite recursion when searching pathological
__bases__tuples.
bpo-45521: Fix a bug in the obmalloc radix tree code. On 64-bit machines, the bug causes the tree to hold 46-bits of virtual addresses, rather than the intended 48-bits.
bpo-45494: Fix parser crash when reporting errors involving invalid continuation characters. Patch by Pablo Galindo.
bpo-45408: Fix a crash in the parser when reporting tokenizer errors that occur at the same time unclosed parentheses are detected. ‘).
bpo-45056: Compiler now removes trailing unused constants from co_consts.
Library¶
bpo-27946: Fix possible crash when getting an attribute of class:
xml.etree.ElementTree.Elementsimultaneously with replacing the
attribdict.
bpo-37658: Fix issue when on certain conditions
asyncio.wait_for()may allow a coroutine to complete successfully, but fail to return the result, potentially causing memory leaks or other issues.
bpo-44649: Handle dataclass(slots=True) with a field that has default a default value, but for which init=False.
bpo-45803: Added missing kw_only parameter to dataclasses.make_dataclass().757: Fix bug where
disproduced an incorrect oparg when
EXTENDED_ARGis followed by an opcode that does not use its argument.
bpo-45644: In-place JSON file formatting using
python3 -m json.tool infile infilenow works correctly, previously it left the file empty. Patch by Chris Wesseling.
bpo-45679: Fix caching of multi-value
typing.Literal.
Literal[True, 2]is no longer equal to
Literal[1, 2].5438: Fix typing.Signature string representation for generic builtin types.
bpo-45574: Fix warning about
print_escapebeing unused.
bpo-45581:
sqlite3.connect()now correctly raises
MemoryErrorif the underlying SQLite API signals memory error. Patch by Erlend E. Aasland.
bpo-45557: pprint.pprint() now handles underscore_numbers correctly. Previously it was always setting it to False.
bpo-45515: Add references to
zoneinfoin the
datetimedocumentation, mostly replacing outdated references to
dateutil.tz. Change by Paul Ganssle.
bpo-45475: Reverted optimization of iterating
gzip.GzipFile,
bz2.BZ2File, and
lzma.LZMAFile(see bpo-43787) because it caused regression when user iterate them without having reference of them. Patch by Inada Naoki.
bpo-45428: Fix a regression in py_compile when reading filenames from standard input.-45249: Fix the behaviour of
traceback.print_exc()when displaying the caret when the
end_offsetin the exception is set to 0. Patch by Pablo Galindo
bpo-45416: Fix use of
asyncio.Conditionwith explicit
asyncio.Lockobjects, which was a regression due to removal of explicit loop arguments. Patch by Joongi Kim.
bpo-45419: Correct interfaces on DegenerateFiles.Path.-45329: Fix freed memory access in
pyexpat.xmlparserwhen building it with an installed expat library <= 2183: Have zipimport.zipimporter.find_spec() not raise an exception when the underlying zip file has been deleted and the internal cache has been reset via invalidate_cache().-42135: Fix typo:
importlib.find_loaderis really slated for removal in Python 3.12 not 3.10, like the others in PR 25169.
Patch by Hugo van Kemenade.-20499: Improve the speed and accuracy of statistics.pvariance()..
bpo-44295: Ensure deprecation warning from
assertDictContainsSubset()points at calling code - by Anthony Sottile.
bpo-43498: Avoid a possible “RuntimeError: dictionary changed size during iteration” when adjusting the process count of
ProcessPoolExecutor.
Documentation¶
bpo-45640: Properly marked-up grammar tokens in the documentation are now clickable and take you to the definition of a given piece of grammar. Patch by Arthur Milchior.
bpo-45788: Link doc for sys.prefix to sysconfig doc on installation paths.
bpo-45772:
socket.socketdocumentation is corrected to a class from a function.
bpo-45392: Update the docstring of the
typebuilt-in to remove a redundant line and to mention keyword arguments for the constructor.-45250: Update the documentation to note that CPython does not consistently require iterators to define
__iter__..
bpo-25381: In the extending chapter of the extending doc, update a paragraph about the global variables containing exception information.
bpo-43905: Expanded
astuple()and
asdict()docs, warning about deepcopy being applied and providing a workaround.
Tests¶
bpo-19460: Add new Test for
bpo-45835: Fix race condition in test_queue tests with multiple “feeder” threads.
bpo-45678: Add tests for scenarios in which
functools.singledispatchmethodis stacked on top of a method that has already been wrapped by two other decorators. Patch by Alex Waygood.
bpo-45578: Add tests for
dis.distb()
bpo-45678: Add tests to ensure that
functools.singledispatchmethodcorrectly wraps the attributes of the target function.
bpo-45577: Add subtests for all
pickleprotocols in
test_zoneinfo.
bpo-45566: Fix
test_frozen_picklein
test_dataclassesto check all
pickleversions.
bpo-43592:
test.libregrtestnow raises the soft resource limit for the maximum number of file descriptors when the default is too low for our test suite as was often the case on macOS.
bpo-39679: Add more test cases for
@functools.singledispatchmethodwhen combined with
@classmethodor
@staticmethod.
bpo-45400: Fix test_name_error_suggestions_do_not_trigger_for_too_many_locals() of test_exceptions if a directory name contains “a1” (like “Python-3.11.0a1”): use a stricter regular expression. Patch by Victor Stinner.
bpo-40173: Fix
test.support.import_helper.import_fresh_module().
bpo-45280: Add a test case for empty
typing.NamedTuple.
bpo-45269: Cover case when invalid
markerstype is supplied to
c_make_encoder.
bpo-45128: Fix
test_multiprocessing_forkfailure due to
test_loggingand
sys.modulesmanipulation.-45125: Improves pickling tests and docs of
SharedMemoryand
SharableListobjects.
bpo-44860: Update
test_sysconfig.test_user_similar()for the posix_user scheme:
platlibdoesn’t use
sys.platlibdir. Patch by Victor Stinner.
bpo-25130: Add calls of
gc.collect()in tests to support PyPy.
Build¶61: Run smelly.py tool from $(srcdir).
bpo-45532: Update
sys.versionto use
mainas fallback information. Patch by Jeong YunWon.
bpo-45536: The
configurescript now checks whether OpenSSL headers and libraries provide required APIs. Most common APIs are verified. The check detects outdated or missing OpenSSL. Failures do not stop configure.
bpo-45221: Fixed regression in handling of
LDFLAGSand
CPPFLAGSoptions where
argparse.parse_known_args()could interpret an option as one of the built-in command line argument, for example
-hfor help..
Windows¶
bpo-45901: When installed through the Microsoft Store and set as the default app for
*.pyfiles, command line arguments will now be passed to Python when invoking a script without explicitly launching Python (that is,
script.py argsrather than
python script.py args).
bpo-45616: Fix Python Launcher’s ability to distinguish between versions 3.1 and 3.10 when either one is explicitly requested. Previously, 3.1 would be used if 3.10 was requested but not installed, and 3.10 would be used if 3.1 was requested but 3.10 was installed.
bpo-45732: Updates bundled Tcl/Tk to 8.6.12.
bpo-45720: Internal reference to
shlwapi.dllwas dropped to help improve startup time. This DLL will no longer be loaded at the start of every Python process.
bpo-43652: Update Tcl/Tk to 8.6.11, actually this time. The previous update incorrectly included 8.6.10.
bpo-45337: venv now warns when the created environment may need to be accessed at a different path, due to redirections, links or junctions. It also now correctly installs or upgrades components when the alternate path is required.
macOS¶
bpo-45732: Update python.org macOS installer to use Tcl/Tk 8.6.12.
bpo-44828: Avoid tkinter file dialog failure on macOS 12 Monterey when using the Tk 8.6.11 provided by python.org macOS installers. Patch by Marc Culler of the Tk project.
bpo-34602: When building CPython on macOS with
./configure --with-undefined-behavior-sanitizer --with-pydebug, the stack size is now quadrupled to allow for the entire test suite to pass.
IDLE¶
Tools/Demos¶
C API¶
bpo-39026: Fix Python.h to build C extensions with Xcode: remove a relative include from
Include/cpython/pystate.h.
bpo-45307: Restore the private C API function
_PyImport_FindExtensionObject(). It will be removed in Python 3.11.
bpo-44687:
BufferedReader.peek()no longer raises
ValueErrorwhen the entire file has already been buffered.
bpo-44751: Remove
crypt.hinclude from the public
Python.hheader.
Python 3.10.0 final¶
Release date: 2021-10-04
Core and Builtins¶
Library¶
bpo-45234: Fixed a regression in
copyfile(),
copy(),
copy2()raising
FileNotFoundErrorwhen source is a directory, which should raise
IsADirectoryError
Documentation¶.
Tests¶
bpo-45128: Fix
test_multiprocessing_forkfailure due to
test_loggingand
sys.modulesmanipulation.
bpo-44860: Update
test_sysconfig.test_user_similar()for the posix_user scheme:
platlibdoesn’t use
sys.platlibdir. Patch by Victor Stinner.
Build¶.
IDLE¶
C API¶
Python 3.10.0 release candidate 2¶
Release date: 2021-09-07
Security¶
bpo-42278: Replaced usage of
tempfile.mktemp()with
TemporaryDirectoryto avoid a potential race condition.123: Fix PyAiter_Check to only check for the __anext__ presence (not for __aiter__). Rename PyAiter_Check to PyAIter_Check, PyObject_GetAiter -> PyObject_GetAIter.
bpo-45018: Fixed pickling of range iterators that iterated for over 2**32 times.
bpo-45000: A
SyntaxErroris now raised when trying to delete
__debug__. Patch by Dong-hee Na.
bpo-44963: Implement
send()and
throw()methods for
anext_awaitableobjects. Patch by Pablo Galindo.-44838: Fixed a bug that was causing the parser to raise an incorrect custom
SyntaxErrorfor invalid ‘if’ expressions. Patch by Pablo Galindo.
bpo-44584: The threading debug (
PYTHONTHREADDEBUGenvironment variable) is deprecated in Python 3.10 and will be removed in Python 3.12. This feature requires a debug build of Python. Patch by Victor Stinner.
bpo-39091: Fix crash when using passing a non-exception to a generator’s
throw()method. Patch by Noah Oxer
Library¶
bpo-45081: Fix issue when dataclasses that inherit from
typing.Protocolsubclasses have wrong
__init__. Patch provided by Yurii Karabas.-45030: Fix integer overflow in pickling and copying the range iterator.-44935:
subprocesson Solaris now also uses
os.posix_spawn()for better performance.
bpo-44911:
IsolatedAsyncioTestCasewill no longer throw an exception while cancelling leaked tasks. Patch by Bar Harel.
bpo-44524: Make exception message more useful when subclass from typing special form alias. Patch provided by Yurii Karabas.
bpo-38956:
argparse.BooleanOptionalAction’s default value is no longer printed twice when used with
argparse.ArgumentDefaultsHelpFormatter.
bpo-44860: Fix the
posix_userscheme in
sysconfigto not depend on
sys.platlibdir.-44524: Fixed an issue wherein the
__name__and
__qualname__attributes of subscribed specialforms could be
None.
bpo-44822:
sqlite3user-defined functions and aggregators returning
stringswith embedded NUL characters are no longer truncated. Patch by Erlend E. Aasland.
bpo-44801: Ensure that the
ParamSpecvariable in Callable can only be substituted with a parameters expression (a list of types, an ellipsis, ParamSpec or Concatenate).
bpo-27334: The
sqlite3context manager now performs a rollback (thus releasing the database lock) if commit failed. Patch by Luca Citi and Erlend E. Aasland.-26228: pty.spawn no longer hangs on FreeBSD, macOS, and Solaris.
bpo-33349: lib2to3 now recognizes async generators everywhere.
Documentation¶
bpo-44957: Promote PEP 604 union syntax by using it where possible. Also, mention
X | Ymore prominently in section about
Unionand mention
X | Noneat all in section about
Optional.
bpo-44903: Removed the othergui.rst file, any references to it, and the list of GUI frameworks in the FAQ. In their place I’ve added links to the Python Wiki
page on GUI frameworks.
bpo-33479: Tkinter documentation has been greatly expanded with new “Architecture” and “Threading model” sections.
bpo-36700:
base64RFC references were updated to point to RFC 4648; a section was added to point users to the new “security considerations” section of the RFC.
bpo-44756: Reverted automated virtual environment creation on
make htmlwhen building documentation. It turned out to be disruptive for downstream distributors.
bpo-42958: Updated the docstring and docs of
filecmp.cmp()to be more accurate and less confusing especially in respect to shallow arg.
bpo-43066: Added a warning to
zipfiledocs: filename arg with a leading slash may cause archive to be un-openable on Windows systems.
bpo-39452: Rewrote
Doc/library/__main__.rst. Broadened scope of the document to explicitly discuss and differentiate between
__main__.pyin packages versus the
__name__ == '__main__'expression (and the idioms that surround it).
bpo-27752: Documentation of csv.Dialect is more descriptive.
bpo-41576: document BaseException in favor of bare except-45052:
WithProcessesTestSharedMemory.test_shared_memory_basicstest was ignored, because
self.assertEqual(sms.size, sms2.size)line was failing. It is now removed and test is unskipped.
The main motivation for this line to be removed from the test is that the
sizeof
SharedMemoryis not ever guaranteed to be the same. It is decided by the platform.
bpo-45042: Fixes that test classes decorated with
@hashlib_helper.requires_hashdigestwere skipped all the time.91: Tests were added to clarify
id()is preserved when
obj * 1is used on
strand
bytesobjects. Patch by Nikita Sobolev.
bpo-44852: Add ability to wholesale silence DeprecationWarnings while running the regression test suite.
bpo-40928: Notify users running test_decimal regression tests on macOS of potential harmless “malloc can’t allocate region” messages spewed by test_decimal.
Windows¶.10.0 release candidate 1¶
Release date: 2021-08-02
Security¶
Core and Builtins¶
bpo-44792: Improve syntax errors for if expressions. Patch by Miguel Brito
bpo-34013: Generalize the invalid legacy statement custom error message (like the one generated when “print” is called without parentheses) to include more generic expressions. Patch by Pablo Galindo
bpo-44732: Rename
types.Unionto
types.UnionType.
bpo-44698: Fix undefined behaviour in complex object exponentiation.
bpo-44653: Support
typingtypes in parameter substitution in the union type.
bpo-44676: Add ability to serialise
types.Unionobjects. Patch provided by Yurii Karabas.
bpo-44633: Parameter substitution of the union type with wrong types now raises
TypeErrorinstead of returning
NotImplemented.
bpo-44662: Add
__module__to
types.Union. This also fixes
types.Unionissues with
typing.Annotated. Patch provided by Yurii Karabas.
bpo-44655: Include the name of the type in unset __slots__ attribute errors. Patch by Pablo Galindo
bpo-44655: Don’t include a missing attribute with the same name as the failing one when offering suggestions for missing attributes. Patch by Pablo Galindo
bpo-44646: Fix the hash of the union type: it no longer depends on the order of arguments.
bpo-44636: Collapse union of equal types. E.g. the result of
int | intis now
int. Fix comparison of the union type with non-hashable objects. E.g.
int | str == {}no longer raises a TypeError.
bpo-44635: Convert
Noneto
type(None)in the union type constructor.
bpo-44589: Mapping patterns in
matchstatements with two or more equal literal keys will now raise a
SyntaxErrorat compile-time.
bpo-44606: Fix
__instancecheck__and
__subclasscheck__for the union type.
bpo-42073: The
@classmethoddecorator can now wrap other classmethod-like descriptors.
bpo-44490:
typingnow searches for type parameters in
types.Unionobjects.
get_type_hintswill also properly resolve annotations with nested
types.Unionobjects. Patch provided by Yurii Karabas.
bpo-44490: Add
__parameters__attribute and
__getitem__operator to
types.Union. Patch provided by Yurii Karabas.
bpo-44472: Fix ltrace functionality when exceptions are raised. Patch by Pablo Galindo
Library¶
bpo-44806: Non-protocol subclasses of
typing.Protocolignore now the
__init__method inherited from protocol base classes.
bpo-44793: Fix checking the number of arguments when subscribe a generic type with
ParamSpecparameter.
bpo-44784: In importlib.metadata tests, override warnings behavior under expected DeprecationWarnings (importlib_metadata 4.6.3).-42854: Fixed a bug in the
_sslmodule that was throwing
OverflowErrorwhen using
_ssl._SSLSocket.write()and
_ssl._SSLSocket.read()for a big value of the
lenparameter. Patch by Pablo Galindo
bpo-44353: Refactor
typing.NewTypefrom function into callable class. Patch provided by Yurii Karabas.
bpo-44524: Add missing
__name__and
__qualname__attributes to
typingmodule classes. Patch provided by Yurii Karabas.
bpo-40897: Give priority to using the current class constructor in
inspect.signature(). Patch by Weipeng Hong.
bpo-44648: Fixed wrong error being thrown by
inspect.getsource()when examining a class in the interactive session. Instead of
TypeError, it should be
OSErrorwith appropriate error message.
bpo-44608: Fix memory leak in
_tkinter._flatten()if it is called with a sequence or set, but not list or tuple.
bpo-44559: [Enum] module reverted to 3.9; 3.10 changes pushed until 3.11-41249: Fixes
TypedDictto work with
typing.get_type_hints()and postponed evaluation of annotations across modules.
bpo-44461: Fix bug with
pdb’s handling of import error due to a package which does not have a
__main__module
bpo-43625: Fix a bug in the detection of CSV file headers by
csv.Sniffer.has_header()and improve documentation of same.
bpo-42892: Fixed an exception thrown while parsing a malformed multipart email by
bpo-27827:
pathlib.PureWindowsPath.is_reserved()now identifies a greater range of reserved filenames, including those with trailing spaces or colons.
bpo-38741:
configparser: using ‘]’ inside a section header will no longer cut the section name short at the ‘]’
bpo-27513:
bpo-29298: Fix
TypeErrorwhen required subparsers without
destdo not receive arguments. Patch by Anthony Sottile.
Documentation¶
bpo-44740: Replaced occurences of uppercase “Web” and “Internet” with lowercase versions per the 2016 revised Associated Press Style Book.-44613: importlib.metadata is no longer provisional.
bpo-44544: List all kwargs for
textwrap.wrap(),
textwrap.fill(), and
textwrap.shorten(). Now, there are nav links to attributes of
TextWrap, which makes navigation much easier while minimizing duplication in the documentation.
bpo-44453: Fix documentation for the return type of
sysconfig.get_path().
Tests¶
bpo-44734: Fixed floating point precision issue in turtle tests.
bpo-44708: Regression tests, when run with -w, are now re-running only the affected test methods instead of re-running the entire test file.
bpo-44647: Added a permanent Unicode-valued environment variable to regression tests to ensure they handle this use case in the future. If your test environment breaks because of that, report a bug to us, and temporarily set PYTHONREGRTEST_UNICODE_GUARD=0 in your test environment.
bpo-44515: Adjust recently added contextlib tests to avoid assuming the use of a refcounted GC
Windows¶
bpo-44572: Avoid consuming standard input in the
platformmodule
bpo-40263: This is a follow-on bug from. Once that is applied we run into an off-by-one assertion problem. The assert was not correct.
macOS¶
Tools/Demos¶
bpo-44756: In the Makefile for documentation (
Doc/Makefile), the
buildrule is dependent on the
venvrule. Therefore,
html,
latex, and other build-dependent rules are also now dependent on
venv. The
venvrule only performs an action if
$(VENVDIR)does not exist.
Doc/README.rstwas updated; most users now only need to type
make html.
C API¶
bpo-41103: Reverts removal of the old buffer protocol because they are part of stable ABI.
bpo-42747: The
Py_TPFLAGS_HAVE_VERSION_TAGtype flag now does nothing. The
Py_TPFLAGS_HAVE_AM_SENDflag (which was added in 3.10) is removed. Both were unnecessary because it is not possible to have type objects with the relevant fields missing.
Python 3.10.0 beta 4¶
Release date: 2021-07-10
Security¶.
Core and Builtins¶
bpo-44562: Remove uses of
PyObject_GC_Del()in error path when initializing
types.GenericAlias.
bpo-41486: Fix a memory consumption and copying performance regression in earlier 3.10 beta releases if someone used an output buffer larger than 4GiB with zlib.decompress on input data that expands that large.
bpo-44553: Implement GC methods for
types.Unionto break reference cycles and prevent memory leaks.
bpo-44523: Remove the pass-through for
hash()of
weakref.proxyobjects to prevent unintended consequences when the original referred object dies while the proxy is part of a hashable object. Patch by Pablo Galindo.
bpo-44483: Fix a crash in
types.Unionobjects when creating a union of an object with bad
__module__field.
bpo-44297: Make sure that the line number is set when entering a comprehension scope. Ensures that backtraces inclusing generator expressions show the correct line number.
bpo-44456: Improve the syntax error when mixing positional and keyword patterns. Patch by Pablo Galindo.
bpo-44368: Improve syntax errors for invalid “as” targets. Patch by Pablo Galindo
bpo-44317: Improve tokenizer error with improved locations. Patch by Pablo Galindo.
bpo-43667: Improve Unicode support in non-UTF locales on Oracle Solaris. This issue does not affect other Solaris systems.
Library¶
bpo-44558: Make the implementation consistency of
indexOf()between C and Python versions. Patch by Dong-hee Na.
bpo-34798: Break up paragraph about
pprint.PrettyPrinterconstruction parameters to make it easier to read.
bpo-44516: Update vendored pip to 21.1.3
bpo-44468:
typing.get_type_hints()now finds annotations in classes and base classes with unexpected
__module__. Previously, it skipped those MRO elements.
bpo-43977: Set the proper
Py_TPFLAGS_MAPPINGand
Py_TPFLAGS_SEQUENCEflags for subclasses created before a parent has been registered as a
collections.abc.Mappingor
collections.abc.Sequence.
bpo-44482: Fix very unlikely resource leak in
globin alternate Python implementations.
bpo-44466: The
faulthandlermodule now detects if a fatal error occurs during a garbage collector collection. Patch by Victor Stinner.
bpo-44404:
tkinter’s
after()method now supports callables without the
__name__attribute.
bpo-44458:
BUFFER_BLOCK_SIZEis now declared static, to avoid linking collisions when bz2, lmza or zlib are statically linked.
bpo-44464: Remove exception for flake8 in deprecated importlib.metadata interfaces. Sync with importlib_metadata 4.6.
bpo-44446: Take into account that
linenomight be
Nonein
traceback.FrameSummary.-44395: Fix
as_string()to pass unixfrom properly. Patch by Dong-hee Na.
bpo-34266: Handle exceptions from parsing the arg of
pdb’s run/restart command.
bpo-44077: It’s now possible to receive the type of service (ToS), a.k.a. differentiated services (DS), a.k.a. differenciated services code point (DSCP) and excplicit congestion notification (ECN) IP header fields with
socket.IP_RECVTOS.
bpo-43024: Improve the help signature of
traceback.print_exception(),
traceback.format_exception()and
traceback.format_exception_only().
bpo-30256: Pass multiprocessing BaseProxy argument
manager_ownedthrough AutoProxy.
Documentation¶
bpo-44558: Match the docstring and python implementation of
countOf()to the behavior of its c implementation.
bpo-38062: Clarify that atexit uses equality comparisons internally.
bpo-40620: Convert examples in tutorial controlflow.rst section 4.3 to be interpreter-demo style.
bpo-13814: In the Design FAQ, answer “Why don’t generators support the with statement?”451: Reset
DeprecationWarningfilters in
test.test_importlib.test_metadata_api.APITests.test_entry_points_by_indexto avoid
StopIterationerror if
DeprecationWarningsare ignored.
bpo-30256: Add test for nested queues when using
multiprocessingshared objects
AutoProxy[Queue]inside
ListProxyand
DictProxy
Build¶
Windows¶
bpo-44582: Accelerate speed of
mimetypesinitialization using a native implementation of the registry scan.
bpo-41299: Fix 16ms jitter when using timeouts in
threading, such as with
threading.Lock.acquire()or
threading.Condition.wait().-40939: Removed documentation for the removed
PyParser_*C API.
Python 3.10.0 beta 3¶
Release date: 2021-06-17
Core and Builtins¶
bpo-44409: Fix error location information for tokenizer errors raised on initialization of the tokenizer. Patch by Pablo Galindo.
bpo-44396: Fix a possible crash in the tokenizer when raising syntax errors for unclosed strings. Patch by Pablo Galindo.
bpo-44349: Fix an edge case when displaying text from files with encoding in syntax errors. Patch by Pablo Galindo.
bpo-44335: Fix a regression when identifying incorrect characters in syntax errors. Patch by Pablo Galindo
bpo-44304: Fix a crash in the
sqlite3module that happened when the garbage collector clears
sqlite.Statementobjects. Patch by Pablo Galindo
bpo-44305: Improve error message for
tryblocks without
exceptor
finallyblocks. Patch by Pablo Galindo.
bpo-43833: Emit a deprecation warning if the numeric literal is immediately followed by one of keywords: and, else, for, if, in, is, or. Raise a syntax error with more informative message if it is immediately followed by other keyword or identifier.
bpo-11105: When compiling
ast.ASTobjects with recursive references through
compile(), the interpreter doesn’t crash anymore instead it raises a
RecursionError.
Library¶
bpo-42972: The _thread.RLock type now fully implement the GC protocol: add a traverse function and the
Py_TPFLAGS_HAVE_GCflag. Patch by Victor Stinner.
bpo-44422: The
threading.enumerate()function now uses a reentrant lock to prevent a hang on reentrant call. Patch by Victor Stinner.
bpo-44389: Fix deprecation of
ssl.OP_NO_TLSv1_3
bpo-44362: Improve
sslmodule’s deprecation messages, error reporting, and documentation for deprecations.
bpo-44342: [Enum] Change pickling from by-value to by-name.
bpo-44356: [Enum] Allow multiple data-type mixins if they are all the same.
bpo-44351: Restore back
parse_makefile()in
distutils.sysconfigbecause it behaves differently than the similar implementation in
sysconfig.
bpo-44242: Remove missing flag check from Enum creation and move into a
verifydecorator.
bpo-44246: In
importlib.metadata, restore compatibility in the result from
Distribution.entry_points(
EntryPoints) to honor expectations in older implementations and issuing deprecation warnings for these cases: A.
EntryPointsobjects are once again mutable, allowing for
sort()and other list-based mutation operations. Avoid deprecation warnings by casting to a mutable sequence (e.g.
list(dist.entry_points).sort()). B.
EntryPointsresults once again allow for access by index. To avoid deprecation warnings, cast the result to a Sequence first (e.g.
tuple(dist.entry_points)[0]).
bpo-44246: In importlib.metadata.entry_points, de-duplication of distributions no longer requires loading the full metadata for PathDistribution objects, improving entry point loading performance by ~10x.-43318: Fix a bug where
pdbdoes not always echo cleared breakpoints.
bpo-37022:
pdbnow displays exceptions from
repr()with its
pand
ppcommands.
Documentation¶.
Tests¶
bpo-44363: Account for address sanitizer in test_capi. test_capi now passes when run GCC address sanitizer.
bpo-43921: Fix test_ssl.test_wrong_cert_tls13(): use
suppress_ragged_eofs=False, since
read()can raise
ssl.SSLEOFErroron Windows. Patch by Victor Stinner.
bpo-43921: Fix test_pha_required_nocert() of test_ssl: catch two more EOF cases (when the
recv()method returns an empty string). Patch by Victor Stinner.
Build.
C API¶
bpo-43795: The list in Contents of Limited API now shows the public name
PyFrameObjectrather than
_frame. The non-existing entry
_nodeno longer appears in the list.
bpo-44378:
Py_IS_TYPE()no longer uses
Py_TYPE()to avoid a compiler warning: no longer cast
const PyObject*to
PyObject*. Patch by Victor Stinner.
Python 3.10.0 beta 2¶
Release date: 2021-05-31
Security¶
bpo-44022: mod:
http.clientnow avoids infinitely reading potential HTTP headers after a
100 Continuestatus response from the server.
Core and Builtins¶
bpo-43667: Improve Unicode support in non-UTF locales on Oracle Solaris. This issue does not affect other Solaris systems.
bpo-44232: Fix a regression in
type()when a metaclass raises an exception. The C function
type_new()must properly report the exception when a metaclass constructor raises an exception and the winner class is not the metaclass. Patch by Victor Stinner.
bpo-44201: Avoid side effects of checking for specialized syntax errors in the REPL that was causing it to ask for extra tokens after a syntax error had been detected. Patch by Pablo Galindo
bpo-44184: Fix a crash at Python exit when a deallocator function removes the last strong reference to a heap type. Patch by Victor Stinner.
bpo-44180: The parser doesn’t report generic syntax errors that happen in a position further away that the one it reached in the first pass. Patch by Pablo Galindo
bpo-44168: Fix error message in the parser involving keyword arguments with invalid expressions. Patch by Pablo Galindo
bpo-44143: Fixed a crash in the parser that manifest when raising tokenizer errors when an existing exception was present. Patch by Pablo Galindo.
bpo-44114: Fix incorrect dictkeys_reversed and dictitems_reversed function signatures in C code, which broke webassembly builds.
bpo-43149: Corrent the syntax error message regarding multiple exception types to not refer to “exception groups”. Patch by Pablo Galindo
bpo-44056: Syntax errors when default
exceptis not the last
exceptare reported with the correct location. Patch by Mark Shannon.
bpo-43822: The parser will prioritize tokenizer errors over custom syntax errors when raising exceptions. Patch by Pablo Galindo.
bpo-28146: Fix a confusing error message in
str.format().
Library¶
bpo-44254: On Mac, give turtledemo button text a color that works on both light or dark background. Programmers cannot control the latter.
bpo-38693: Prefer f-strings to
.formatin importlib.resources.
bpo-33693: Importlib.metadata now prefers f-strings to .format.
bpo-44241: Incorporate minor tweaks from importlib_metadata 4.1: SimplePath protocol, support for Metadata 2.2.
bpo-44210: Make importlib.metadata._meta.PackageMetadata public.
bpo-43643: Declare readers.MultiplexedPath.name as a property per the spec.
bpo-33433: For IPv4 mapped IPv6 addresses (RFC 4291 Section 2.5.5.2), the
ipaddress.IPv6Address.is_privatecheck is deferred to the mapped IPv4 address. This solves a bug where public mapped IPv4 addresses were considered private by the IPv6 check.-38908: Subclasses of
typing.Protocolwhich only have data variables declared will now raise a
TypeErrorwhen checked with
isinstanceunless they are decorated with
runtime_checkable(). Previously, these checks passed silently. Patch provided by Yurii Karabas.
bpo-44098:
typing.ParamSpecwill no longer be found in the
__parameters__of most
typinggenerics except in valid use locations specified by PEP 612. This prevents incorrect usage like
typing.List[P][int]. This change means incorrect usage which may have passed silently in 3.10 beta 1 and earlier will now error.
bpo-44089: Allow subclassing
csv.Errorin 3.10 (it was allowed in 3.9 and earlier but was disallowed in early versions of 3.10).
bpo-44059: Register the SerenityOS Browser in the
webbrowsermodule.-43650: Fix
MemoryErrorin
shutil.unpack_archive()which fails inside
shutil._unpack_zipfile()on large files. Patch by Igor Bolshakov.
bpo-41730:
DeprecationWarningis now raised when importing
tkinter.tix, which has been deprecated in documentation since Python 3.6.
Documentation¶
bpo-42392: Document the deprecation and removal of the
loopparameter for many functions and classes in
asyncio.-44025: Clarify when ‘_’ in match statements is a keyword, and when not.
Tests¶
bpo-31904: Ignore error string case in test_py_compile
test_file_not_exists().
bpo-42083: Add test to check that
PyStructSequence_NewTypeaccepts a
PyStructSequence_Descwith
docfield set to
NULL.
bpo-35753: Fix crash in doctest when doctest parses modules that include unwrappable functions by skipping those functions.
Build¶
Windows¶
macOS¶
IDLE¶
bpo-41611: Avoid uncaught exceptions in
AutoCompleteWindow.winconfig_event().
bpo-41611: Fix IDLE sometimes freezing upon tab-completion on macOS.
bpo-44010: Highlight the new match statement’s soft keywords:
match,
case, and
_. However, this highlighting is not perfect and will be incorrect in some rare cases, including some
_-s in
casepatterns.
bpo-44026: Include interpreter’s typo fix suggestions in message line for NameErrors and AttributeErrors. Patch by E. Paine.
Tools/Demos¶
C API¶
bpo-43795: The undocumented function
Py_FrozenMain()is removed from the Limited API.
bpo-43795:
PyCodec_Unregister()is now properly exported as a function in the Windows Stable ABI DLL.
Python 3.10.0 beta 1¶
Release date: 2021-05-03
Security¶
bpo-43434: Creating
sqlite3.Connectionobjects now also produces
sqlite3.connectand
sqlite3.connect/handleauditing events. Previously these events were only produced by
sqlite3.connect()calls. Patch by Erlend E. Aasland.
bpo-43998: The
sslmodule sets more secure cipher suites defaults. Ciphers without forward secrecy and with SHA-1 MAC are disabled by default. Security level 2 prohibits weak RSA, DH, and ECC keys with less than 112 bits of security.
SSLContextdefaults to minimum protocol version TLS 1.2. Settings are based on Hynek Schlawack’s research.-43362: Fix invalid free in _sha3 module. The issue was introduced in 3.10.0a1. Python 3.9 and earlier are not affected.
bpo-43762: Add audit events for
sqlite3.connect/handle(),
sqlite3.Connection.enable_load_extension(), and
sqlite3.Connection.load_extension(). Patch by Erlend E. Aasland.
bpo-43756: Add new audit event
glob.glob/2to incorporate the new root_dir and dir_fd arguments added to
glob.glob()and
glob.iglob()..
bpo-37363: Add audit events to the
http.clientmodule.
Core and Builtins¶
bpo-43977: Prevent classes being both a sequence and a mapping when pattern matching.
bpo-43977: Use
tp_flagson the class object to determine if the subject is a sequence or mapping when pattern matching. Avoids the need to import
collections.abcwhen pattern matching.
bpo-43892: Restore proper validation of complex literal value patterns when parsing
matchblocks.
bpo-43933: Set frame.f_lineno to the line number of the ‘with’ kweyword when executing the call to
__exit__.
bpo-43933: If the current position in a frame has no line number then set the f_lineno attribute to None, instead of -1, to conform to PEP 626. This should not normally be possible, but might occur in some unusual circumstances.
bpo-43963: Importing the
_signalmodule in a subinterpreter has no longer side effects.
bpo-42739: The internal representation of line number tables is changed to not use sentinels, and an explicit length parameter is added to the out of process API function
PyLineTable_InitAddressRange. This makes the handling of line number tables more robust in some circumstances.
bpo-43908: Make
retypes immutable. Patch by Erlend E. Aasland.
bpo-43908: Make the
array.arraytype immutable. Patch by Erlend E. Aasland.
bpo-43901: Change class and module objects to lazy-create empty annotations dicts on demand. The annotations dicts are stored in the object’s __dict__ for backwards compatibility.
bpo-43892: Match patterns now use new dedicated AST nodes (
MatchValue,
MatchSingleton,
MatchSequence,
MatchStar,
MatchMapping,
MatchClass) rather than reusing expression AST nodes.
MatchAsand
MatchOrare now defined as pattern nodes rather than as expression nodes. Patch by Nick Coghlan.
bpo-42725: Usage of
await/
yield/
yield fromand named expressions within an annotation is now forbidden when PEP 563 is activated.
bpo-43754: When performing structural pattern matching (PEP 634), captured names are now left unbound until the entire pattern has matched successfully.
bpo-42737: Annotations for complex targets (everything beside simple names) no longer cause any runtime effects with
from __future__ import annotations.
bpo-43914:
SyntaxErrorexceptions raised by the interpreter will highlight the full error range of the expression that consistutes the syntax error itself, instead of just where the problem is detected. Patch by Pablo Galindo.
bpo-38605: Revert making
from __future__ import annotationsthe default. This follows the Steering Council decision to postpone PEP 563 changes to at least Python 3.11. See the original email for more information regarding the decision:. Patch by Pablo Galindo.
bpo-43475: Hashes of NaN values now depend on object identity. Formerly, they always hashed to 0 even though NaN values are not equal to one another. Having the same hash for unequal values caused pile-ups in hash tables.
bpo-43859: Improve the error message for
IndentationErrorexceptions. Patch by Pablo Galindo
bpo-41323: Constant tuple folding in bytecode optimizer now reuses tuple in constant table.
bpo-43846: Data stack usage is much reduced for large literal and call expressions.
bpo-38530: When printing
NameErrorraised by the interpreter,
PyErr_Display()will offer suggestions of similar variable names in the function that the exception was raised from. Patch by Pablo Galindo
bpo-43823: Improve syntax errors for invalid dictionary literals. Patch by Pablo Galindo.
bpo-43822: Improve syntax errors in the parser for missing commas between expressions. Patch by Pablo Galindo.
bpo-43798:
ast.aliasnodes now include source location metadata attributes e.g. lineno, col_offset.
bpo-43797: Improve
SyntaxErrorerror messages for invalid comparisons. Patch by Pablo Galindo.
bpo-43760: Move the flag for checking whether tracing is enabled to the C stack, from the heap. Should speed up dispatch in the interpreter.
bpo-43682: Static methods (
@staticmethod) and class methods (
@classmethod) now inherit the method attributes (
__module__,
__name__,
__qualname__,
__doc__,
__annotations__) and have a new
__wrapped__attribute. Patch by Victor Stinner.
bpo-43751: Fixed a bug where
anext(ait, default)would erroneously return None.
bpo-42128:
__match_args__is no longer allowed to be a list.
bpo-43683: Add GEN_START opcode. Marks start of generator, including async, or coroutine and handles sending values to a newly created generator or coroutine.
bpo-43105: Importlib now resolves relative paths when creating module spec objects from file locations.
bpo-43682: Static methods (
@staticmethod) are now callable as regular functions. Patch by Victor Stinner.
bpo-42609: Prevented crashes in the AST validator and optimizer when compiling some absurdly long expressions like
"+0"*1000000.
RecursionErroris now raised instead.
bpo-38530: When printing
AttributeError,
PyErr_Display()will offer suggestions of similar attribute names in the object that the exception was raised from. Patch by Pablo Galindo
Library¶
bpo-44015: In @dataclass(), raise a TypeError if KW_ONLY is specified more than once.
bpo-25478: Added a total() method to collections.Counter() to compute the sum of the counts.
bpo-43733: Change
netrc.netrcto use UTF-8 encoding before using locale encoding.
bpo-43979: Removed an unnecessary list comprehension before looping from
urllib.parse.parse_qsl(). Patch by Christoph Zwerschke and Dong-hee Na.
bpo-43993: Update bundled pip to 21.1.1.
bpo-43957: [Enum] Deprecate
TypeErrorwhen non-member is used in a containment check; In 3.12
Trueor
Falsewill be returned instead, and containment will return
Trueif the value is either a member of that enum or one of its members’ value.
bpo-42904: For backwards compatibility with previous minor versions of Python, if
typing.get_type_hints()receives no namespace dictionary arguments,
typing.get_type_hints()will search through the global then local namespaces during evaluation of stringized type annotations (string forward references) inside a class.
bpo-43945: [Enum] Deprecate non-standard mixin format() behavior: in 3.12 the enum member, not the member’s value, will be used for format() calls.
bpo-41139: Deprecate undocumented
cgi.log()API.
bpo-43937: Fixed the
turtlemodule working with non-default root window.
bpo-43930: Update bundled pip to 21.1 and setuptools to 56.0.0
bpo-43907: Fix a bug in the pure-Python pickle implementation when using protocol 5, where bytearray instances that occur several time in the pickled object graph would incorrectly unpickle into repeated copies of the bytearray object.
bpo-43926: In
importlib.metadata, provide a uniform interface to
Description, allow for any field to be encoded with multiline values, remove continuation lines from multiline values, and add a
.jsonproperty for easy access to the PEP 566 JSON-compatible form. Sync with
importlib_metadata 4.0.
bpo-43920: OpenSSL 3.0.0:
load_verify_locations()now returns a consistent error message when cadata contains no valid certificate.
bpo-43607:
urllibcan now convert Windows paths with
\\?\prefixes into URL paths.
bpo-43817: Add
inspect.get_annotations(), which safely computes the annotations defined on an object. It works around the quirks of accessing the annotations from various types of objects, and makes very few assumptions about the object passed in.
inspect.get_annotations()can also correctly un-stringize stringized annotations.
inspect.signature(),
inspect.from_callable(), and
inspect.from_function()now call
inspect.get_annotations()to retrieve annotations. This means
inspect.signature()and
inspect.from_callable()can now un-stringize stringized annotations, too.-42854: The
sslmodule now uses
SSL_read_exand
SSL_write_exinternally. The functions support reading and writing of data larger than 2 GB. Writing zero-length data no longer fails with a protocol violation error.
bpo-42333: Port
_sslextension module to multiphase initialization.
bpo-43880:
sslnow raises DeprecationWarning for OP_NO_SSL/TLS* options, old TLS versions, old protocols, and other features that have been deprecated since Python 3.6, 3.7, or OpenSSL 1.1.0.
bpo-41559: PEP 612 is now implemented purely in Python; builtin
types.GenericAliasobjects no longer include
typing.ParamSpecin
__parameters__(with the exception of
collections.abc.Callable‘s
GenericAlias). This means previously invalid uses of
ParamSpec(such as
list[P]) which worked in earlier versions of Python 3.10 alpha, will now raise
TypeErrorduring substitution.
bpo-43867: The
multiprocessing
Serverclass now explicitly catches
SystemExitand closes the client connection in this case. It happens when the
Server.serve_client()method reaches the end of file (EOF).
bpo-40443: Remove unused imports: pyclbr no longer uses copy, and typing no longer uses ast. Patch by Victor Stinner.
bpo-43820: Remove an unneeded copy of the namespace passed to dataclasses.make_dataclass().
bpo-43787: Add
__iter__()method to
bz2.BZ2File,
gzip.GzipFile, and
lzma.LZMAFile. It makes iterating them about 2x faster. Patch by Inada Naoki.
bpo-43680: Deprecate io.OpenWrapper and _pyio.OpenWrapper: use io.open and _pyio.open instead. Until Python 3.9, _pyio.open was not a static method and builtins.open was set to OpenWrapper to not become a bound method when set to a class variable. _io.open is a built-in function whereas _pyio.open is a Python function. In Python 3.10, _pyio.open() is now a static method, and builtins.open() is now io.open().
bpo-43680: The Python
_pyio.open()function becomes a static method to behave as
io.open()built-in function: don’t become a bound method when stored as a class variable. It becomes possible since static methods are now callable in Python 3.10. Moreover,
_pyio.OpenWrapper()becomes a simple alias to
_pyio.open(). Patch by Victor Stinner.
bpo-41515: Fix
KeyErrorraised in
typing.get_type_hints()due to synthetic modules that don’t appear in
sys.modules.
bpo-43776: When
subprocess.Popenargs are provided as a string or as
pathlib.Path, the Popen instance repr now shows the right thing.
bpo-42248: [Enum] ensure exceptions raised in
_missing__are released
bpo-43744: fix issue with enum member name matching the start of a private variable name
bpo-43772: Fixed the return value of
TypeVar.__ror__. Patch by Jelle Zijlstra.
bpo-43764: Add match_args parameter to @dataclass decorator to allow suppression of __match_args__ generation.
bpo-43799: OpenSSL 3.0.0: define
OPENSSL_API_COMPAT1.1.1 to suppress deprecation warnings. Python requires OpenSSL 1.1.1 APIs.
bpo-43478: Mocks can no longer be used as the specs for other Mocks. As a result, an already-mocked object cannot have an attribute mocked using
autospec=Trueor be the subject of a
create_autospec(...)call. This can uncover bugs in tests since these Mock-derived Mocks will always pass certain tests (e.g.
isinstance()) and builtin assert functions (e.g. assert_called_once_with) will unconditionally pass.
bpo-43794: Add
ssl.OP_IGNORE_UNEXPECTED_EOFconstants (OpenSSL 3.0.0)
bpo-43785: Improve
bz2.BZ2Fileperformance by removing the RLock from BZ2File. This makes BZ2File thread unsafe in the face of multiple simultaneous readers or writers, just like its equivalent classes in
gzipand
lzmahave always been. Patch by Inada Naoki.-43766: Implement PEP 647 in the
typingmodule by adding
TypeGuard.
bpo-25264:
os.path.realpath()now accepts a strict keyword-only argument. When set to
True,
OSErroris raised if a path doesn’t exist or a symlink loop is encountered.
bpo-43780: In
importlib.metadata, incorporate changes from importlib_metadata 3.10: Add mtime-based caching during distribution discovery. Flagged use of dict result from
entry_points()as deprecated.
The
P.argsand
P.kwargsattributes of
typing.ParamSpecare now instances of the new classes
typing.ParamSpecArgsand
typing.ParamSpecKwargs, which enables a more useful
repr(). Patch by Jelle Zijlstra.
bpo-43731: Add an
encodingparameter
logging.fileConfig().
bpo-43712: Add
encodingand
errorsparameters to
fileinput.input()and
fileinput.FileInput.
bpo-38659: A
simple_enumdecorator is added to the
enummodule to convert a normal class into an Enum.
test_simple_enumadded to test simple enums against a corresponding normal Enum. Standard library modules updated to use
simple_enum.
bpo-43764: Fix an issue where
__match_args__generation could fail for some
dataclasses.
bpo-43752: Fix
sqlite3regression for zero-sized blobs with converters, where
b""was returned instead of
None. The regression was introduced by PR 24723. Patch by Erlend E. Aasland.
bpo-43655:
tkinterdialog windows are now recognized as dialogs by window managers on macOS and X Window.
bpo-43723: The following
threadingmethods are now deprecated and should be replaced:
currentThread=>
threading.current_thread()
activeCount=>
threading.active_count()
Condition.notifyAll=>
threading.Condition.notify_all()
Event.isSet=>
threading.Event.is_set()
Thread.setName=>
threading.Thread.name
thread.getName=>
threading.Thread.name
Thread.isDaemon=>
threading.Thread.daemon
Thread.setDaemon=>
threading.Thread.daemon
Patch by Jelle Zijlstra.
bpo-2135: Deprecate find_module() and find_loader() implementations in importlib and zipimport.
bpo-43534:
turtle.textinput()and
turtle.numinput()create now a transient window working on behalf of the canvas window.
bpo-43532: Add the ability to specify keyword-only fields to dataclasses. These fields will become keyword-only arguments to the generated __init__.
bpo-43522: Fix problem with
hostname_checks_common_name. OpenSSL does not copy hostflags from struct SSL_CTX to struct SSL.
bpo-8978: Improve error message for
tarfile.open()when
lzma/
bz2are unavailable. Patch by Anthony Sottile.
bpo-42967: Allow
bytes
separatorargument in
urllib.parse.parse_qsand
urllib.parse.parse_qslwhen parsing
strquery strings. Previously, this raised a
TypeError.
bpo-43296: Improve
sqlite3error handling:
sqlite3_value_blob()errors that set
SQLITE_NOMEMnow raise
MemoryError. Patch by Erlend E. Aasland.
bpo-43312: New functions
sysconfig.get_preferred_scheme()and
sysconfig.get_default_scheme()are added to query a platform for its preferred “user”, “home”, and “prefix” (default) scheme names.
bpo-43265: Improve
sqlite3.Connection.backup()error handling. The error message for non-existent target database names is now
unknown database <database name>instead of
SQL logic error. Patch by Erlend E. Aasland.
bpo-41282: Install schemes in
distutils.command.installare now loaded from
sysconfig.
bpo-41282:
distutils.sysconfighas been merged to
sysconfig.
bpo-43176: Fixed processing of a dataclass that inherits from a frozen dataclass with no fields. It is now correctly detected as an error.
bpo-43080:
pprintnow has support for
dataclasses.dataclass. Patch by Lewis Gaul.
bpo-39950: Add
pathlib.Path.hardlink_to()method that supersedes
link_to(). The new method has the same argument order as
symlink_to().
bpo-42904:
typing.get_type_hints()now checks the local namespace of a class when evaluating PEP 563 annotations inside said class.
bpo-42269: Add
slotsparameter to
dataclasses.dataclassdecorator to automatically generate
__slots__for class. Patch provided by Yurii Karabas.
bpo-39529: Deprecated use of
asyncio.get_event_loop()without running event loop. Emit deprecation warning for
asynciofunctions which implicitly create a
Futureor
Taskobjects if there is no running event loop and no explicit loop argument is passed:
ensure_future(),
wrap_future(),
gather(),
shield(),
as_completed()and constructors of
Future,
Task,
StreamReader,
StreamReaderProtocol.
bpo-18369: Certificate and PrivateKey classes were added to the ssl module. Certificates and keys can now be loaded from memory buffer, too.
bpo-41486: Use a new output buffer management code for
bz2/
lzma/
zlibmodules, and add
.readall()function to
_compression.DecompressReaderclass. These bring some performance improvements. Patch by Ma Lin.
bpo-31870: The
ssl.get_server_certificate()function now has a timeout parameter.
bpo-41735: Fix thread locks in zlib module may go wrong in rare case. Patch by Ma Lin.
bpo-36470: Fix dataclasses with
InitVars and
replace(). Patch by Claudiu Popa.
bpo-40849: Expose X509_V_FLAG_PARTIAL_CHAIN ssl flag
bpo-35114:
ssl.RAND_status()now returns a boolean value (as documented) instead of
1or
0.
bpo-39906:
pathlib.Path.stat()and
chmod()now accept a follow_symlinks keyword-only argument for consistency with corresponding functions in the
osmodule.
bpo-39899:
os.path.expanduser()now refuses to guess Windows home directories if the basename of current user’s home directory does not match their username.
pathlib.Path.expanduser()and
home()now consistently raise
RuntimeErrorexception when a home directory cannot be resolved. Previously a
KeyErrorexception could be raised on Windows when the
"USERNAME"environment variable was unset.
bpo-36076: Added SNI support to
ssl.get_server_certificate().
bpo-38490: Covariance, Pearson’s correlation, and simple linear regression functionality was added to statistics module. Patch by Tymoteusz Wołodźko.
bpo-33731: Provide a locale.localize() function, which converts a normalized number string into a locale format.
bpo-32745: Fix a regression in the handling of ctypes’
ctypes.c_wchar_ptype: embedded null characters would cause a
ValueErrorto be raised. Patch by Zackery Spytz.
Documentation¶
bpo-43987: Add “Annotations Best Practices” document as a new HOWTO.
bpo-43977: Document the new
Py_TPFLAGS_MAPPINGand
Py_TPFLAGS_SEQUENCEtype flags.
bpo-43959: The documentation on the PyContextVar C-API was clarified.
bpo-43938: Update dataclasses documentation to express that FrozenInstanceError is derived from AttributeError.
bpo-43778: Fix the Sphinx glossary_search extension: create the _static/ sub-directory if it doesn’t exist.43:
test.libregrtestnow marks a test as ENV_CHANGED (altered the execution environment) if a thread raises an exception but does not catch it. It sets a hook on
threading.excepthook(). Use
--fail-env-changedoption to mark the test as failed..
Build¶
Windows¶
bpo-35306: Adds additional arguments to
os.startfile()function.
bpo-43538:-43652: Update Tcl and Tk to 8.6.11 in Windows installer.
bpo-43492: Upgrade Windows installer to use SQLite 3.35.5.
bpo-30555: Fix
WindowsConsoleIOerrors in the presence of fd redirection. Patch by Segev Finer.-43568: Drop support for MACOSX_DEPLOYMENT_TARGET < 10.33851: Build SQLite with
SQLITE_OMIT_AUTOINITon macOS. Patch by Erlend E. Aasland.
bpo-43492: Update macOS installer to use SQLite 3.35.4.
bpo-42235:
Mac/BuildScript/build-installer.pywill now use “–enable-optimizations” and
--with-ltowhen building on macOS 10.15 or later.
IDLE¶
bpo-37903: Add mouse actions to the shell sidebar. Left click and optional drag selects one or more lines, as with the editor line number sidebar. Right click after selecting raises a context menu with ‘copy with prompts’. This zips together prompts from the sidebar with lines from the selected text.
bpo-43981: Fix reference leak in test_sidebar and test_squeezer. Patches by Terry Jan Reedy and Pablo Galindo
bpo-37892: Indent IDLE Shell input with spaces instead of tabs
bpo-43655: IDLE dialog windows are now recognized as dialogs by window managers on macOS and X Window.
bpo-37903: IDLE’s shell now shows prompts in a separate side-bar.
C API¶
bpo-43916: Add a new
Py_TPFLAGS_DISALLOW_INSTANTIATIONtype flag to disallow creating type instances. Patch by Victor Stinner.
bpo-43774: Remove the now unused
PYMALLOC_DEBUGmacro. Debug hooks on memory allocators are now installed by default if Python is built in debug mode (if
Py_DEBUGmacro is defined). Moreover, they can now be used on Python build in release mode (ex: using
PYTHONMALLOC=debugenvironment variable).
bpo-43962: _PyInterpreterState_IDIncref() now calls _PyInterpreterState_IDInitref() and always increments id_refcount. Previously, calling _xxsubinterpreters.get_current() could create an id_refcount inconsistency when a _xxsubinterpreters.InterpreterID object was deallocated. Patch by Victor Stinner.
bpo-28254: Add new C-API functions to control the state of the garbage collector:
PyGC_Enable(),
PyGC_Disable(),
PyGC_IsEnabled(), corresponding to the functions in the
gcmodule.
bpo-43908: Introduce
Py_TPFLAGS_IMMUTABLETYPEflag for immutable type objects, and modify
PyType_Ready()to set it for static types. Patch by Erlend E. Aasland.
bpo-43795:
PyMem_Calloc()is now available in the limited C API (
Py_LIMITED_API).
bpo-43868:
PyOS_ReadlineFunctionPointer()is no longer exported by limited C API headers and by
python3.dllon Windows. Like any function that takes
FILE*, it is not part of the stable ABI.
bpo-43795: Stable ABI and limited API definitions are generated from a central manifest (PEP 652).
bpo-43753:. Patch by Victor Stinner.
Python 3.10.0 alpha 7¶
Release date: 2021-04-05-27129: Update CPython bytecode magic number.
bpo-43672: Raise ImportWarning when calling find_loader().
bpo-43660: Fix crash that happens when replacing
sys.stderrwith a callable that can remove the object while an exception is being printed. Patch by Pablo Galindo.
bpo-27129: The bytecode interpreter uses instruction, rather byte, offsets internally. This reduces the number of EXTENDED_ARG instructions needed and streamlines instruction dispatch a bit.
bpo-40645: Fix reference leak in the
_hashopensslextension. Patch by Pablo Galindo.
bpo-42134: Calls to find_module() by the import system now raise ImportWarning.
bpo-41064: Improve the syntax error for invalid usage of double starred elements (‘**’) in f-strings. Patch by Pablo Galindo.
bpo-43575: Speed up calls to
map()by using the PEP 590
vectorcallcalling convention. Patch by Dong-hee Na.
bpo-42137: The import system now prefers using
__spec__for
ModuleType.__repr__over
module_repr().
bpo-43452: Added micro-optimizations to
_PyType_Lookup()to improve cache lookup performance in the common case of cache hits.-43497: Emit SyntaxWarnings for assertions with tuple constants, this is a regression introduced in python3.7
bpo-39316: Tracing now has correct line numbers for attribute accesses when the the attribute is on a different line from the object. Improves debugging and profiling for multi-line method chains.-43410: Fix a bug that was causing the parser to crash when emitting syntax errors when reading input from stdin. Patch by Pablo Galindo
bpo-43406: Fix a possible race condition where
PyErr_CheckSignalstries to execute a non-Python signal handler.
bpo-42128: Add
__match_args__to
structsequencebased classes. Patch by Pablo Galindo.
bpo-43390: CPython now sets the
SA_ONSTACKflag in
PyOS_setsigfor the VM’s default signal handlers. This is friendlier to other in-process code that an extension module or embedding use could pull in (such as Golang’s cgo) where tiny thread stacks are the norm and
sigaltstack()has been used to provide for signal handlers. This is a no-op change for the vast majority of processes that don’t use sigaltstack.
bpo-43287: Speed up calls to
filter()by using the PEP 590
vectorcallcalling convention. Patch by Dong-hee Na.
bpo-37448: Add a radix tree based memory map to track in-use obmalloc arenas. Use to replace the old implementation of address_in_range(). The radix tree approach makes it easy to increase pool sizes beyond the OS page size. Boosting the pool and arena size allows obmalloc to handle a significantly higher percentage of requests from its ultra-fast paths.
It also has the advantage of eliminating the memory unsanitary behavior of the previous address_in_range(). The old address_in_range() was marked with the annotations _Py_NO_SANITIZE_ADDRESS, _Py_NO_SANITIZE_THREAD, and _Py_NO_SANITIZE_MEMORY. Those annotations are no longer needed.
To disable the radix tree map, set a preprocessor flag as follows:
-DWITH_PYMALLOC_RADIX_TREE=0.
Co-authored-by: Tim Peters <tim.peters@gmail.com>
bpo-29988: Only handle asynchronous exceptions and requests to drop the GIL when returning from a call or on the back edges of loops. Makes sure that
__exit__()is always called in with statements, even for interrupts.
Library¶
bpo-43720: Document various stdlib deprecations in imp, pkgutil, and importlib.util for removal in Python 3.12.
bpo-43433:
xmlrpc.client.ServerProxyno longer ignores query and fragment in the URL of the server.
bpo-31956: The
index()method of
array.arraynow has optional start and stop parameters.
bpo-40066: Enum: adjust
repr()to show only enum and member name (not value, nor angle brackets) and
str()to show only member name. Update and improve documentation to match.
bpo-42136: Deprecate all module_repr() methods found in importlib as their use is being phased out by Python 3.12.
bpo-35930: Raising an exception raised in a “future” instance will create reference cycles.
bpo-41369: Finish updating the vendored libmpdec to version 2.5.1. Patch by Stefan Krah.
bpo-43422: Revert the _decimal C API which was added in bpo-41324.
bpo-43577: Fix deadlock when using
ssl.SSLContextdebug callback with
ssl.SSLContext.sni_callback().
bpo-43571: It’s now possible to create MPTCP sockets with IPPROTO_MPTCP
bpo-43542:
image/heicand
image/heifwere added to
mimetypes.
bpo-40645: The
hmacmodule now uses OpenSSL’s HMAC implementation when digestmod argument is a hash name or builtin hash function.
bpo-43510: Implement PEP 597: Add
EncodingWarningwarning,
-X warn_default_encodingoption,
PYTHONWARNDEFAULTENCODINGenvironment variable and
encoding="locale"argument value.
bpo-43521:
ast.unparsecan now render NaNs and empty sets.
bpo-42914:
pprint.pprint()gains a new boolean
underscore_numbersoptional argument to emit integers with thousands separated by an underscore character for improved readability (for example
1_000_000instead of
1000000).
bpo-41361:
rotate()calls are now slightly faster due to faster argument parsing.-43445: Add frozen modules to
sys.stdlib_module_names. For example, add
"_frozen_importlib"and
"_frozen_importlib_external"names.
bpo-43245: Add keyword arguments support to
ChainMap.new_child().
bpo-29982: Add optional parameter ignore_cleanup_errors to
tempfile.TemporaryDirectory()and allow multiple
cleanup()attempts. Contributed by C.A.M. Gerlach.
bpo-43428: Include changes from importlib_metadata 3.7:
Performance enhancements to distribution discovery.
entry_pointsonly returns unique distributions.
Introduces new
EntryPointsobject for containing a set of entry points with convenience methods for selecting entry points by group or name.
entry_pointsnow returns this object if selection parameters are supplied but continues to return a dict object for compatibility. Users are encouraged to rely on the selection interface. The dict object result is likely to be deprecated in the future.
Added packages_distributions function to return a mapping of packages to the distributions that provide them.
bpo-43332: Improves the networking efficiency of
http.clientwhen using a proxy via
set_tunnel(). Fewer small send calls are made during connection setup.
bpo-43420: Improve performance of
fractions.Fractionarithmetics for large components. Contributed by Sergey B. Kirpichev.
bpo-43356: Allow passing a signal number to
_thread.interrupt_main().
bpo-43399: Fix
ElementTree.extendnot working on iterators when using the Python implementation
bpo-43369: Improve
sqlite3error handling: If
sqlite3_column_text()and
sqlite3_column_blob()set
SQLITE_NOMEM,
MemoryErroris now raised. Patch by Erlend E. Aasland.
bpo-43368: Fix a regression introduced in PR 24562, where an empty bytestring was fetched as
Noneinstead of
b''in
sqlite3. Patch by Mariusz Felisiak.
bpo-41282: Fixed stacklevel of
DeprecationWarningemitted from
import distutils.
bpo-42129:
importlib.resourcesnow honors namespace packages, merging resources from each location in the namespace as introduced in
importlib_resources3.2 and including incidental changes through 5.0.3.
bpo-43295:
datetime.datetime.strptime()now raises
ValueErrorinstead of
IndexErrorwhen matching
'z'with the
%zformat specifier.
bpo-43125: Return empty string if base64mime.body_encode receive empty bytes
bpo-43084:
curses.window.enclose()returns now
Trueor
False(as was documented) instead of
1or
0.
bpo-42994: Add MIME types for opus, AAC, 3gpp and 3gpp2
bpo-14678: Add an invalidate_caches() method to the zipimport.zipimporter class to support importlib.invalidate_caches(). Patch by Desmond Cheong.
bpo-42782: Fail fast in
shutil.move()to avoid creating destination directories on failure.
bpo-40066: Enum’s
repr()and
str()have changed:
repr()is now EnumClass.MemberName and
str()is MemberName. Additionally, stdlib Enum’s whose contents are available as module attributes, such as
RegexFlag.IGNORECASE, have their
repr()as module.name, e.g.
re.IGNORECASE.
bpo-26053: Fixed bug where the
pdbinteractive run command echoed the args from the shell command line, even if those have been overridden at the pdb prompt.
bpo-24160: Fixed bug where breakpoints did not persist across multiple debugger sessions in
pdb’s interactive mode.
bpo-40701: When the
tempfile.tempdirglobal variable is set to a value of type bytes, it is now handled consistently. Previously exceptions could be raised from some tempfile APIs when the directory did not already exist in this situation. Also ensures that the
tempfile.gettempdir()and
tempfile.gettempdirb()functions always return
strand
bytesrespectively.
bpo-39342: Expose
X509_V_FLAG_ALLOW_PROXY_CERTSas
VERIFY_ALLOW_PROXY_CERTSto allow proxy certificate validation as explained in.
bpo-31861: Add builtins.aiter and builtins.anext. Patch by Joshua Bronson (@jab), Daniel Pope (@lordmauve), and Justin Wang (@justin39).-43354: Fix type documentation for
Fault.faultCode; the type has to be
intinstead of
str.
bpo-41933: Clarified wording of s * n in the Common Sequence Operations
Tests¶
Build¶
bpo-43179: Introduce and correctly use ALIGNOF_X in place of SIZEOF_X for alignment-related code in optimized string routines. Patch by Jessica Clarke.
bpo-43631: Update macOS, Windows, and CI to OpenSSL 1.1.1k.
bpo-43617: Improve configure.ac: Check for presence of autoconf-archive package and remove our copies of M4 macros.
bpo-43466: The
configurescript now supports
--with-openssl-rpathoption.
bpo-43372: Use
_freeze_importlibto generate code for the
__hello__module. This approach ensures the code matches the interpreter version. Previously, PYTHON_FOR_REGEN was used to generate the code, which might be wrong. The marshal format for code objects has changed with bpo-42246, commit 877df851. Update the code and the expected code sizes in ctypes test_frozentable.
Windows¶
IDLE¶
C API¶
bpo-43688:).
Patch by Victor Stinner.. Patch by Victor Stinner.. Patch by Victor Stinner.
bpo-43244:. Patch by Victor Stinner.
bpo-43541: Fix a
PyEval_EvalCodeEx()regression: fix reference counting on builtins. Patch by Victor Stinner..
The Python
symtablemodule remains available and is unchanged.
Patch by Victor Stinner.
bpo-43244: Remove the
PyAST_Validate()function. It is no longer possible to build a AST object (
mod_tytype) with the public C API. The function was already excluded from the limited C API (PEP 384). Patch by Victor Stinner.
Python 3.10.0 alpha 6¶
Release date: 2021-03-01
Security¶
Core and Builtins¶
bpo-43321: Fix
SystemErrorraised when
PyArg_Parse*()is used with
#but without
PY_SSIZE_T_CLEANdefined.
bpo-36346:
PyArg_Parse*()functions now emits
DeprecationWarningwhen
uor
Zformat is used. See PEP 623 for detail.
bpo-43277: Add a new
PySet_CheckExact()function to the C-API to check if an object is an instance of
setbut not an instance of a subtype. Patch by Pablo Galindo.
bpo-42990:. Patch by Victor Stinner.
bpo-42990: Functions have a new
__builtins__attribute which is used to look for builtin symbols when a function is executed, instead of looking into
__globals__['__builtins__']. Patch by Mark Shannon and Victor Stinner.
bpo-43149: Improve the error message in the parser for exception groups without parentheses. Patch by Pablo Galindo.
bpo-43121: Fixed an incorrect
SyntaxErrormessage for missing comma in literals. Patch by Pablo Galindo.808: Simple calls to
type(object)are now faster due to the
vectorcallcalling convention. Patch by Dennis Sweeney.
bpo-42217: Make the compiler merges same co_code and co_linetable objects in a module like already did for co_consts.
bpo-41972: Substring search functions such as
str1 in str2and
str2.find(str1)now sometimes use the “Two-Way” string comparison algorithm to avoid quadratic behavior on long strings.
bpo-42128: Implement PEP 634 (structural pattern matching). Patch by Brandt Bucher.
bpo-40692: In the
concurrent.futures.ProcessPoolExecutor, validate that
multiprocess.synchronize()is available on a given platform and rely on that check in the
concurrent.futurestest suite so we can run tests that are unrelated to
ProcessPoolExecutoron those platforms.
bpo-38302: If
object.__ipow__()returns
NotImplemented, the operator will correctly fall back to
object.__pow__()and
object.__rpow__()as expected.
Library¶
bpo-43316: The
python -m gzipcommand line application now properly fails when detecting an unsupported extension. It exits with a non-zero exit code and prints an error message to stderr.
bpo-43317: Set the chunk size for the
gzipmodule main function to io.DEFAULT_BUFFER_SIZE. This is slightly faster than the 1024 bytes constant that was used previously.
bpo-43146: Handle None in single-arg versions of
print_exception()and
format_exception().
bpo-43260: Fix TextIOWrapper can not flush internal buffer forever after very large text is written.
bpo-43258: Prevent needless allocation of
sqlite3aggregate function context when no rows match an aggregate query. Patch by Erlend E. Aasland.
bpo-43251: Improve
sqlite3error handling:
sqlite3_column_name()failures now result in
MemoryError. Patch by Erlend E. Aasland.
bpo-40956: Fix segfault in
sqlite3.Connection.backup()if no argument was provided. The regression was introduced by PR 23838. Patch by Erlend E. Aasland.
bpo-43172: The readline module now passes its tests when built directly against libedit. Existing irreconcilable API differences remain in
readline.get_begidx()and
readline.get_endidx()behavior based on libreadline vs libedit use.
bpo-43163: Fix a bug in
codeopthat was causing it to not ask for more input when multi-line snippets have unclosed parentheses. Patch by Pablo Galindo
bpo-43162: deprecate unsupported ability to access enum members as attributes of other enum members
bpo-43146: Fix recent regression in None argument handling in
tracebackmodule functions.
bpo-43102: The namedtuple __new__ method had its __builtins__ set to None instead of an actual dictionary. This created problems for introspection tools.
bpo-43106: Added
O_EVTONLY,
O_FSYNC,
O_SYMLINKand
O_NOFOLLOW_ANYfor macOS. Patch by Dong-hee Na.
bpo-42960: Adds
resource.RLIMIT_KQUEUESconstant from FreeBSD to the
resourcemodule.
bpo-42151: Make the pure Python implementation of
xml.etree.ElementTreebehave the same as the C implementation (
_elementree) regarding default attribute values (by not setting
specified_attributes=1).
bpo-29753: In ctypes, now packed bitfields are calculated properly and the first item of packed bitfields is now shrank correctly.
Documentation¶
Tests¶
Build¶
bpo-43174: Windows build now uses
/utf-8compiler option.
bpo-43103: Add a new configure
--without-static-libpythonoption to not build the
libpythonMAJOR.MINOR.astatic library and not install the
python.oobject file.
bpo-13501: The configure script can now use libedit instead of readline with the command line option
--with-readline=editline.
bpo-42603: Make configure script use pkg-config to detect the location of Tcl/Tk headers and libraries, used to build tkinter.
On macOS, a Tcl/Tk configuration provided by pkg-config will be preferred over Tcl/Tk frameworks installed in
/{System/,}Library/Frameworks. If both exist and the latter is preferred, the appropriate
--with-tcltk-*configuration options need to be explicitly set.
bpo-39448: Add the “regen-frozen” makefile target that regenerates the code for the frozen
__hello__module.
Windows¶
macOS¶
IDLE¶
C API¶
bpo-43278: Always put compiler and system information on the first line of the REPL welcome message.
bpo-43270: Remove the private
_PyErr_OCCURRED()macro: use the public
PyErr_Occurred()function instead.
bpo-35134: Move odictobject.h, parser_interface.h, picklebufobject.h, pydebug.h, and pyfpe.h into the cpython/ directory. They must not be included directly, as they are already included by Python.h: Include Files.
bpo-35134: Move pyarena.h, pyctype.h, and pytime.h into the cpython/ directory. They must not be included directly, as they are already included by Python.h: Include Files.
bpo-40170:
PyExceptionClass_Name()is now always declared as a function, in order to hide implementation details. The macro accessed
PyTypeObject.tp_namedirectly. Patch by Erlend E. Aasland.
bpo-43239: The
PyCFunction_New()function is now exported in the ABI when compiled with
-fvisibility=hidden.
bpo-40170:
PyIter_Check()is now always declared as a function, in order to hide implementation details. The macro accessed
PyTypeObject.tp_iternextdirectly. Patch by Erlend E. Aasland.
bpo-40170: Convert
PyDescr_IsData()macro to a function to hide implementation details: The macro accessed
PyTypeObject.tp_descr_setdirectly. Patch by Erlend E. Aasland.
bpo-43181: Convert
PyObject_TypeCheck()macro to a static inline function. Patch by Erlend E. Aasland.
Python 3.10.0 alpha 5¶
Release date: 2021-02-02
Security¶
bpo-42938: Avoid static buffers when computing the repr of
ctypes.c_doubleand
ctypes.c_longdoublevalues.
Core and Builtins¶
bpo-42990: Refactor the
PyEval_family of functions.
An new function
_PyEval_Vectoris added to simplify calls to Python from C.
_PyEval_EvalCodeWithNameis removed
PyEval_EvalCodeExis retained as part of the API, but is not used internally
bpo-38631: Replace
Py_FatalError()calls in the compiler with regular
SystemErrorexceptions. Patch by Victor Stinner.
bpo-42997: Improve error message for missing “:” before blocks. Patch by Pablo Galindo.
bpo-43017: Improve error message in the parser when using un-parenthesised tuples in comprehensions. Patch by Pablo Galindo.
bpo-42986: Fix parser crash when reporting syntax errors in f-string with newlines. Patch by Pablo Galindo.
bpo-40176: Syntax errors for unterminated string literals now point to the start of the string instead of reporting EOF/EOL.
bpo-42927: The inline cache for
LOAD_ATTRnow also optimizes access to attributes defined by
__slots__. This makes reading such attribute up to 30% faster.
bpo-42864: Improve error messages in the parser when parentheses are not closed. Patch by Pablo Galindo.).
bpo-42882: Fix the
_PyUnicode_FromId()function (_Py_IDENTIFIER(var) API) when
Py_Initialize()/
Py_Finalize()is called multiple times: preserve
_PyRuntime.unicode_ids.next_indexvalue.
bpo-42827: Fix a crash when working out the error line of a
SyntaxErrorin some multi-line expressions.
bpo-42823: frame.f_lineno is correct even if frame.f_trace is set to True
bpo-37324: Remove deprecated aliases to Collections Abstract Base Classes from the
collectionsmodule.
bpo-41994: Fixed possible leak in
importwhen
sys.modulesis not a
dict.
bpo-27772: In string formatting, preceding the width field by
'0'no longer affects the default alignment for strings.
Library¶
bpo-43108: Fixed a reference leak in the
cursesmodule. Patch by Pablo Galindo
bpo-43077: Update the bundled pip to 21.0.1 and setuptools to 52.0.0.
bpo-41282: Deprecate
distutilsin documentation and add warning on import.
bpo-43014: Improve performance of
tokenizeby 20-30%. Patch by Anthony Sottile.
bpo-42323: Fix
math.nextafter()for NaN on AIX.
bpo-42955: Add
sys.stdlib_module_names, containing the list of the standard library module names. Patch by Victor Stinner.
bpo-42944: Fix
random.Random.samplewhen
countsargument is not
None.
bpo-42934: Use
TracebackException’s new
compactparam in
TestResultto reduce time and memory consumed by traceback formatting.
bpo-42931: Add
randbytes()to
random.__all__.
bpo-38250: [Enum] Flags consisting of a single bit are now considered canonical, and will be the only flags returned from listing and iterating over a Flag class or a Flag member. Multi-bit flags are considered aliases; they will be returned from lookups and operations that result in their value. Iteration for both Flag and Flag members is in definition order.
bpo-42877: Added the
compactparameter to the constructor of
traceback.TracebackExceptionto reduce time and memory for use cases that only need to call
TracebackException.format()and
TracebackException.format_exception_only().
bpo-42923: The
Py_FatalError()function and the
faulthandlermodule now dump the list of extension modules on a fatal error.
bpo-42848: Removed recursion from
TracebackExceptionto allow it to handle long exception chains.
bpo-42901: [Enum] move member creation from
EnumMeta.__new__to
_proto_member.__set_name__, allowing members to be created and visible in
__init_subclass__.
bpo-42780: Fix os.set_inheritable() for O_PATH file descriptors on Linux.
bpo-42866: Fix a reference leak in the
getcodec()function of CJK codecs. Patch by Victor Stinner.
bpo-42846: Convert the 6 CJK codec extension modules (_codecs_cn, _codecs_hk, _codecs_iso2022, _codecs_jp, _codecs_kr and _codecs_tw) to the multiphase initialization API (PEP 489). Patch by Victor Stinner.
bpo-42851: remove __init_subclass__ support for Enum members
bpo-42834: Make internal caches of the
_jsonmodule compatible with subinterpreters.
bpo-41748: Fix HTMLParser parsing rules for element attributes containing commas with spaces. Patch by Karl Dubost.
bpo-40810: Require SQLite 3.7.15 or newer. Patch by Erlend E. Aasland.
bpo-1635741: Convert the _multibytecodec extension module (CJK codecs) to multi-phase initialization (PEP 489). Patch by Erlend E. Aasland.
bpo-42802: The distutils
bdist_wininstcommand deprecated in Python 3.8 has been removed. The distutils
bdist_wheelcommand is now recommended to distribute binary packages on Windows.
bpo-24464: The undocumented built-in function
sqlite3.enable_shared_cacheis now deprecated, scheduled for removal in Python 3.12. Its use is strongly discouraged by the SQLite3 documentation. Patch by Erlend E. Aas-42005: Fix CLI of
cProfileand
profileto catch
BrokenPipeError.
bpo-41604: Don’t decrement the reference count of the previous user_ptr when set_panel_userptr fails.
bpo-41149: Allow executing callables that have a boolean value of
Falsewhen passed to
Threading.threadas the target. Patch contributed by Barney Stratford.
bpo-38307: Add an ‘end_lineno’ attribute to the Class and Function objects that appear in the tree returned by pyclbr functions. This and the existing ‘lineno’ attribute define the extent of class and def statements. Patch by Aviral Srivastava.
bpo-39273: The
BUTTON5_*constants are now exposed in the
cursesmodule if available.
bpo-33289: Correct call to
tkinter.colorchooserto return RGB triplet of ints instead of floats. Patch by Cheryl Sabella.
Documentation¶
Tests¶
Build¶
bpo-43031: Pass
--timeout=$(TESTTIMEOUT)option to the default profile task
./python -m test --pgocommand.
bpo-36143:
make regen-allnow also runs
regen-keyword. Patch by Victor Stinner.
bpo-42874: Removed the grep -q and -E flags in the tzpath validation section of the configure script to better accommodate users of some platforms (specifically Solaris 10).
bpo-31904: Add library search path by wr-cc in add_cross_compiling_paths() for VxWorks.
bpo-42856: Add
--with-wheel-pkg-dir=PATHoption to.
Windows¶
macOS¶.
C API¶
bpo-42979: When Python is built in debug mode (with C assertions), calling a type slot like
sq_length(
__len__()in Python) now fails with a fatal error if the slot succeeded with an exception set, or failed with no exception set. The error message contains the slot, the type name, and the current exception (if an exception is set). Patch by Victor Stinner.
bpo-43030: Fixed a compiler warning in
Py_UNICODE_ISSPACE()on platforms with signed
wchar_t.
Python 3.10.0 alpha 4¶
Release date: 2021-01-04
Core and Builtins¶
bpo-42814: Fix undefined behavior in
Objects/genericaliasobject.c.-27794: Improve the error message for failed writes/deletes to property objects. When possible, the attribute name is now shown. Patch provided by Yurii Karabas.
bpo-42745: Make the type attribute lookup cache per-interpreter. Patch by Victor Stinner.
bpo-42246: Jumps to jumps are not eliminated when it would break PEP 626.
bpo-42246: Make sure that the
f_lastiand
f_linenoattributes of a frame are set correctly when an exception is raised or re-raised. Required for PEP 626.
bpo-32381: The coding cookie (ex:
# coding: latin1) is now ignored in the command passed to the
-ccommand line option. Patch by Victor Stinner.
bpo-30858: Improve error location in expressions that contain assignments. Patch by Pablo Galindo and Lysandros Nikolaou.
bpo-42615: Remove jump commands made redundant by the deletion of unreachable bytecode blocks
bpo-42639: Make the
atexitmodule state per-interpreter. It is now safe have more than one
atexitmodule instance. Patch by Dong-hee Na and Victor Stinner.
bpo-32381: Fix encoding name when running a
.pycfile on Windows:
PyRun_SimpleFileExFlags()now uses the correct encoding to decode the filename.
Callables no longer validate their
argtypes, in
Callable[[argtypes], resulttype]to prepare for PEP 612. Patch by Ken Jin.
bpo-40137: Convert functools module to use
PyType_FromModuleAndSpec().
bpo-40077: Convert
arrayto use heap types, and establish module state for these.
bpo-42008: Fix _random.Random() seeding.
bpo-1635741: Port the
pyexpatextension module to multi-phase initialization (PEP 489).
bpo-40521: Make the Unicode dictionary of interned strings compatible with subinterpreters. Patch by Victor Stinner.
bpo-39465: Make
_PyUnicode_FromId()function compatible with subinterpreters. Each interpreter now has an array of identifier objects (interned strings decoded from UTF-8). Patch by Victor Stinner.
Library¶
bpo-42257: Handle empty string in variable executable in platform.libc_ver()
bpo-42772: randrange() now raises a TypeError when step is specified without a stop argument. Formerly, it silently ignored the step argument.-42740:
typing.get_args()and
typing.get_origin()now support PEP 604 union types and PEP 612 additions to
Callable.
bpo-42655:
subprocessextra_groups is now correctly passed into setgroups() system call.
bpo-42727:
EnumMeta.__prepare__now accepts
**kwdsto properly support
__init_subclass__
bpo-38308: Add optional weights to statistics.harmonic_mean().
bpo-42721: When simple query dialogs (
tkinter.simpledialog), message boxes (
tkinter.messagebox) or color choose dialog (
tkinter.colorchooser) are created without arguments master and parent, and the default root window is not yet created, and
NoDefaultRoot()was not called, a new temporal hidden root window will be created automatically. It will not be set as the default root window and will be destroyed right after closing the dialog window. It will help to use these simple dialog windows in programs which do not need other GUI.
bpo-25246: Optimized
collections.deque.remove().
bpo-35728: Added a root parameter to
tkinter.font.nametofont().
bpo-15303:
tkintersupports now widgets with boolean value False.
bpo-42681: Fixed range checks for color and pair numbers in
curses.
bpo-42685: Improved placing of simple query windows in Tkinter (such as
tkinter.simpledialog.askinteger()). They are now centered at the center of the parent window if it is specified and shown, otherwise at the center of the screen.
bpo-9694: Argparse help no longer uses the confusing phrase, “optional arguments”. It uses “options” instead.
bpo-1635741: Port the
_threadextension module to the multiphase initialization API (PEP 489) and convert its static types to heap types.39:
atexit._run_exitfuncs()now logs callback exceptions using
sys.unraisablehook, rather than logging them directly into
sys.stderrand raise the last exception.
bpo-42644:
logging.disablewill now validate the types and value of its parameter. It also now accepts strings representing the levels (as does
loging.setLevel) instead of only the numerical values.
bpo-42639: At Python exit, if a callback registered with
atexit.register()fails, its exception is now logged. Previously, only some exceptions were logged, and the last exception was always silently ignored.
bpo-36541: Fixed lib2to3.pgen2 to be able to parse PEP-570 positional only argument syntax.
bpo-42382: In
importlib.metadata: -
EntryPointobjects now expose a
.distobject referencing the
Distributionwhen constructed from a
Distribution. - Add support for package discovery under package normalization rules. - The object returned by
metadata()now has a formally defined protocol called
PackageMetadatawith declared support for the
.get_all()method. - Synced with importlib_metadata 3.3.
bpo-41877: A check is added against misspellings of autospect, auto_spec and set_spec being passed as arguments to patch, patch.object and create_autospec.
bpo-39717: [tarfile] update nested exception raising to use
from Noneor
from e
bpo-41877: AttributeError for suspected misspellings of assertions on mocks are now pointing out that the cause are misspelled assertions and also what to do if the misspelling is actually an intended attribute name. The unittest.mock document is also updated to reflect the current set of recognised misspellings.
bpo-41559: Implemented PEP 612: added
ParamSpecand
Concatenateto
typing. Patch by Ken Jin.
bpo-42385: StrEnum: fix _generate_next_value_ to return a str
bpo-31904: Define THREAD_STACK_SIZE for VxWorks.
bpo-34750: [Enum]
_EnumDict.update()is now supported
bpo-42517: Enum: private names do not become members / do not generate errors – they remain normal attributes
bpo-42678:
Enum: call
__init_subclass__after members have been added
bpo-28964:
ast.literal_eval()adds line number information (if available) in error message for malformed nodes.
bpo-42470:
random.sample()no longer warns on a sequence which is also a set.
bpo-31904:
posixpath.expanduser()returns the input path unchanged if user home directory is None on VxWorks.93: Raise
OverflowErrorinstead of silent truncation in
socket.ntohs()and
socket.htons(). Silent truncation was deprecated in Python 3.7. Patch by Erlend E. Aasland
bpo-42222: Harmonized
random.randrange()argument handling to match
range().
The integer test and conversion in
randrange()now uses
operator.index().
Non-integer arguments to
randrange()are deprecated.
The
ValueErroris deprecated in favor of a
TypeError.
It now runs a little faster than before.
(Contributed by Raymond Hettinger and Serhiy Storchaka.)
bpo-42163: Restore compatibility for
uname_resultaround deepcopy and _replace.
bpo-42090:
zipfile.Path.joinpathnow accepts arbitrary arguments, same as
pathlib.Path.joinpath.
bpo-1635741: Port the _csv module to the multi-phase initialization API (PEP 489).
bpo-42059:
typing.TypedDicttypes created using the alternative call-style syntax now correctly respect the
totalkeyword argument when setting their
__required_keys__and
__optional_keys__class attributes.
bpo-41960: Add
globalnsand
localnsparameters to the
inspect.signature()and
inspect.Signature.from_callable().
bpo-41907: fix
format()behavior for
IntFlag
bpo-41891: Ensure asyncio.wait_for waits for task completion
bpo-24792: Fixed bug where
zipimportersometimes reports an incorrect cause of import errors.
bpo-31904: Fix site and sysconfig modules for VxWorks RTOS which has no home directories.
bpo-41462: Add
os.set_blocking()support for VxWorks RTOS.
bpo-40219: Lowered
tkinter.ttk.LabeledScaledummy widget to prevent hiding part of the content label.
bpo-37193: Fixed memory leak in
socketserver.ThreadingMixInintroduced in Python 3.7.
bpo-39068: Fix initialization race condition in
a85encode()and
b85encode()in
base64. Patch by Brandon Stansbury.
Documentation¶
bpo-17140: Add documentation for the
multiprocessing.pool.ThreadPoolclass.
bpo-34398: Prominently feature listings from the glossary in documentation search results. Patch by Ammar Askar.
Tests¶
bpo-42794: Update test_nntplib to use official group name of news.aioe.org for testing. Patch by Dong-hee Na.
bpo-31904: Skip some asyncio tests on VxWorks.
bpo-42641: Enhance
test_select.test_select(): it now takes 500 ms rather than 10 seconds. Use Python rather than a shell to make the test more portable.
bpo-31904: Skip some tests in _test_all_chown_common() on VxWorks.
bpo-42199: Fix bytecode helper assertNotInBytecode.
bpo-41443: Add more attribute checking in test_posix.py
bpo-31904: Disable os.popen and impacted tests on VxWorks
bpo-41439: Port test_ssl and test_uuid to VxWorks RTOS.
Build¶
bpo-42692: Fix __builtin_available check on older compilers. Patch by Joshua Root.
bpo-27640: Added
--disable-test-modulesoption to the
configurescript: don’t build nor install test modules. Patch by Xavier de Gaye, Thomas Petazzoni and Peixing Xin.
bpo-42604:”.
bpo-42598: Fix implicit function declarations in configure which could have resulted in incorrect configuration checks. Patch contributed by Joshua Root.
bpo-31904: Enable libpython3.so for VxWorks.
bpo-29076: Add fish shell support to macOS installer.
macOS¶
Tools/Demos¶
C API¶
bpo-42591: Export the
Py_FrozenMain()function: fix a Python 3.9.0 regression. Python 3.9 uses
-fvisibility=hiddenand the function was not exported explicitly and so not exported.
bpo-32381: Remove the private
_Py_fopen()function which is no longer needed. Use
_Py_wfopen()or
_Py_fopen_obj()instead. Patch by Victor Stinner.
bpo-1635741: Port
resourceextension module to module state
bpo-42111: Update the
xxlimitedmodule to be a better example of how to use the limited C API.
bpo-40052: Fix an alignment build warning/error in function
PyVectorcall_Function(). Patch by Andreas Schneider, Antoine Pitrou and Petr Viktorin.
Python 3.10.0 alpha 3¶
Release date: 2020-12-07
Security¶
Core and Builtins¶
bpo-42576:
types.GenericAliaswill now raise a
TypeErrorwhen attempting to initialize with a keyword argument. Previously, this would cause the interpreter to crash if the interpreter was compiled with debug symbols. This does not affect interpreters compiled for release. Patch by Ken Jin.
bpo-42536: Several built-in and standard library types now ensure that their internal result tuples are always tracked by the garbage collector:
Previously, they could have become untracked by a prior garbage collection. Patch by Brandt Bucher.
bpo-42500: Improve handling of exceptions near recursion limit. Converts a number of Fatal Errors in RecursionErrors.
bpo-42246: PEP 626: After a return, the f_lineno attribute of a frame is always the last line executed.
bpo-42435: Speed up comparison of bytes objects with non-bytes objects when option
-bis specified. Speed up comparison of bytarray objects with non-buffer object.
bpo-1635741: Port the
_warningsextension module to the multi-phase initialization API (PEP 489). Patch by Victor Stinner.-42202: Change function parameters annotations internal representation to tuple of strings. Patch provided by Yurii Karabas.
bpo-42374: Fix a regression introduced by the new parser, where an unparenthesized walrus operator was not allowed within generator expressions.
bpo-42316: Allow an unparenthesized walrus in subscript indexes.
bpo-42349: Make sure that the compiler front-end produces a well-formed control flow graph. Be be more aggressive in the compiler back-end, as it is now safe to do so.82: Optimise constant subexpressions that appear as part of named expressions (previously the AST optimiser did not descend into named expressions). Patch by Nick Coghlan.
bpo-42266: Fixed a bug with the LOAD_ATTR opcode cache that was not respecting monkey-patching a class-level attribute to make it a descriptor. Patch by Pablo Galindo.
bpo-40077: Convert
queueto use heap types.
bpo-42246: Improved accuracy of line tracing events and f_lineno attribute of Frame objects. See PEP 626 for details.
bpo-40077: Convert
mmapto use heap types.
bpo-42233: Allow
GenericAliasobjects to use union type expressions. This allows expressions like
list[int] | dict[float, str]where previously a
TypeErrorwould have been thrown. This also fixes union type expressions not de-duplicating
GenericAliasobjects. (Contributed by Ken Jin in bpo-42233.)
bpo-26131: The import system triggers a
ImportWarningwhen it falls back to using
load_module().-42562: Fix issue when dis failed to parse function that has no line numbers. Patch provided by Yurii Karabas.-42532: Remove unexpected call of
__bool__when passing a
spec_argargument to a Mock.
bpo-38200: Added itertools.pairwise()
bpo-41818: Fix test_master_read() so that it succeeds on all platforms that either raise OSError or return b”” upon reading from master.-41818: Make test_openpty() avoid unexpected success due to number of rows and/or number of columns being == 0.
bpo-42392: Remove loop parameter from
asyncio.subprocessand
asyncio.tasksfunctions. Patch provided by Yurii Karabas.
bpo-42392: Remove loop parameter from
asyncio.open_connectionand
asyncio.start_serverfunctions. Patch provided by Yurii Karabas.
bpo-28468: Add
platform.freedesktop_os_release()function to parse freedesktop.org
os-releasefiles.
bpo-42299:. Patch by Dong-hee Na and and Terry J. Reedy.
bpo-26131: Deprecate zipimport.zipimporter.load_module() in favour of exec_module().
bpo-41818: Updated tests for the pty library. test_basic() has been changed to test_openpty(); this additionally checks if slave termios and slave winsize are being set properly by pty.openpty(). In order to add support for FreeBSD, NetBSD, OpenBSD, and Darwin, this also adds test_master_read(), which demonstrates that pty.spawn() should not depend on an OSError to exit from its copy loop.
bpo-42392: Remove loop parameter from
__init__in all
asyncio.locksand
asyncio.Queueclasses. Patch provided by Yurii Karabas.
bpo-15450: Make
filecmp.dircmprespect subclassing. Now the
filecmp.dircmp.subdirsbehaves as expected when subclassing dircmp.
bpo-42413: The exception
socket.timeoutis now an alias of
TimeoutError.
bpo-31904: Support signal module on VxWorks.
bpo-42406: We fixed an issue in
pickle.whichmodulein which importing
multiprocessingcould change the how pickle identifies which module an object belongs to, potentially breaking the unpickling of those objects.
bpo-42403: Simplify the
importlibexternal bootstrap code:
importlib._bootstrap_externalnow uses regular imports to import builtin modules. When it is imported, the builtin
__import__()function is already fully working and so can be used to import builtin modules like
sys. Patch by Victor Stinner.
bpo-1635741: Convert _sre module types to heap types (PEP 384). Patch by Erlend E. Aasland.
bpo-42375: subprocess module update for DragonFlyBSD support.
bpo-41713: Port the
_signalextension module to the multi-phase initialization API (PEP 489). Patch by Victor Stinner and Mohamed Koubaa.
bpo-37205:
time.time(),
time.perf_counter()and
time.monotonic()functions can no longer fail with a Python fatal error, instead raise a regular Python exception on failure.-37205:
time.perf_counter()on Windows and
time.monotonic()on macOS are now system-wide. Previously, they used an offset computed at startup to reduce the precision loss caused by the float type. Use
time.perf_counter_ns()and
time.monotonic_ns()added in Python 3.7 to avoid this precision loss.
bpo-42318: Fixed support of non-BMP characters in
tkinteron macOS.
bpo-42350: Fix the
threading.Threadclass at fork: do nothing if the thread is already stopped (ex: fork called at Python exit). Previously, an error was logged in the child process.
bpo-42333: Port _ssl extension module to heap types.
bpo-42014: The
onerrorcallback from
shutil.rmtreenow receives correct function when
os.openfails.
bpo-42237: Fix
os.sendfile()on illumos.
bpo-42308: Add
threading.__excepthook__to allow retrieving the original value of
threading.excepthook()in case it is set to a broken or a different value. Patch by Mario Corchero.
bpo-42131: Implement PEP 451/spec methods on zipimport.zipimporter: find_spec(), create_module(), and exec_module().
This also allows for the documented deprecation of find_loader(), find_module(), and load_module().
bpo-41877: Mock objects which are not unsafe will now raise an AttributeError if an attribute with the prefix asert, aseert, or assrt is accessed, in addition to this already happening for the prefixes assert or assret.
bpo-42264:
sqlite3.OptimizedUnicodehas been undocumented and obsolete since Python 3.3, when it was made an alias to
str. It is now deprecated, scheduled for removal in Python 3.12.
bpo-42251: Added
threading.gettrace()and
threading.getprofile()to retrieve the functions set by
threading.settrace()and
threading.setprofile()respectively. Patch by Mario Corchero.
bpo-42249: Fixed writing binary Plist files larger than 4 GiB.
bpo-42236: On Unix, the
os.device_encoding()function now returns
'UTF-8'rather than the device encoding if the Python UTF-8 Mode is enabled.
bpo-41754: webbrowser: Ignore NotADirectoryError when calling
xdg-settings.
bpo-42183: Fix a stack overflow error for asyncio Task or Future repr().
The overflow occurs under some circumstances when a Task or Future recursively returns itself.
bpo-42140: Improve asyncio.wait function to create the futures set just one time.
bpo-42133: Update various modules in the stdlib to fall back on
__spec__.loaderwhen
__loader__isn’t defined on a module.
bpo-26131: The
load_module()methods found in importlib now trigger a DeprecationWarning.-26389: The
traceback.format_exception(),
traceback.format_exception_only(), and
traceback.print_exception()functions can now take an exception object as a positional-only argument.
bpo-41889: Enum: fix regression involving inheriting a multiply inherited enum
bpo-41861: Convert
sqlite3to use heap types (PEP 384). Patch by Erlend E. Aasland.
bpo-40624: Added support for the XPath
!=operator in xml.etree
bpo-28850: Fix
pprint.PrettyPrinter.format()overrides being ignored for contents of small containers. The
pprint._safe_repr()function was removed.
bpo-41625: Expose the
splice()as
os.splice()in the
osmodule. Patch by Pablo Galindo
bpo-34215: Clarify the error message for
asyncio.IncompleteReadErrorwhen
expectedis
None.
bpo-41543: Add async context manager support for contextlib.nullcontext.
bpo-21041:
pathlib.PurePath.parentsnow supports negative indexing. Patch contributed by Yaroslav Pankovych.
bpo-41332: Added missing connect_accepted_socket() method to
asyncio.AbstractEventLoop..
bpo-40968:
urllib.requestand
http.clientnow send
http/1.1ALPN extension during TLS handshake when no custom context is supplied.
bpo-41001: Add func:
os.eventfdto provide a low level interface for Linux’s event notification file descriptor.
bpo-40816: Add AsyncContextDecorator to contextlib to support async context manager as a decorator.
bpo-40550: Fix time-of-check/time-of-action issue in subprocess.Popen.send_signal.
bpo-39411: Add an
is_asyncidentifier to
pyclbr’s
Functionobjects. Patch by Batuhan Taskaya
bpo-35498: Add slice support to
pathlib.PurePath.parents.
Documentation¶
bpo-42238: Tentative to deprecate
make suspiciousby first removing it from the CI and documentation builds, but keeping it around for manual uses.
bpo-42153: Fix the URL for the IMAP protocol documents.
bpo-41028: Language and version switchers, previously maintained in every cpython branches, are now handled by docsbuild-script.
Tests¶
bpo-41473: Re-enable.
bpo-31904: Fix test_netrc on VxWorks: create temporary directories using temp_cwd().
bpo-31904: skip test_getaddrinfo_ipv6_scopeid_symbolic and test_getnameinfo_ipv6_scopeid_symbolic on VxWorks
bpo-31904: skip test_test of test_mailcap on VxWorks
bpo-31904: add shell requirement for test_pipes
bpo-31904: skip some tests related to fifo on VxWorks
bpo-31904: Fix test_doctest.py failures for VxWorks.
bpo-40754: Include
_testinternalcapimodule in Windows installer for test suite
bpo-41561: test_ssl: skip test_min_max_version_mismatch when TLS 1.0 is not available
bpo-31904: Fix os module failures for VxWorks RTOS.
bpo-31904: Fix fifo test cases for VxWorks RTOS.
Build¶
bpo-31904: remove libnet dependency from detect_socket() for VxWorks-38823: It is no longer possible to build the
_ctypesextension module without
wchar_ttype: remove
CTYPES_UNICODEmacro. Anyway, the
wchar_ttype is required to build Python. Patch by Victor Stinner.
bpo-42087: Support was removed for AIX 5.3 and below. See bpo-40680.
bpo-40998: Addressed three compiler warnings found by undefined behavior sanitizer (ubsan).
Windows¶
macOS¶
bpo-42504: Fix build on macOS Big Sur when MACOSX_DEPLOYMENT_TARGET=11-42232: Added Darwin specific madvise options to mmap module.
bpo-38443: The
--enable-universalsdkand
--with-universal-archsoptions for the configure script now check that the specified architectures can be used.
IDLE¶
bpo-42508: Keep IDLE running on macOS. Remove obsolete workaround that prevented running files with shortcuts when using new universal2 installers built on macOS 11.
bpo-42426: Fix reporting offset of the RE error in searchengine.
bpo-42415: Get docstrings for IDLE calltips more often by using inspect.getdoc.
Tools/Demos¶
C API¶
bpo-42423: The
PyType_FromSpecWithBases()and
PyType_FromModuleAndSpec()functions now accept a single class as the bases argument.
bpo-1635741: Port
selectextension module to multiphase initialization (PEP 489).
bpo-1635741: Port _posixsubprocess extension module to multiphase initialization (PEP 489).
bpo-1635741: Port _posixshmem extension module to multiphase initialization (PEP 489)
bpo-1635741: Port _struct extension module to multiphase initialization (PEP 489)
bpo-1635741: Port
spwdextension module to multiphase initialization (PEP 489)
bpo-1635741: Port
gcextension module to multiphase initialization (PEP 489)
bpo-1635741: Port _queue extension module to multiphase initialization (PEP 489)
bpo-39573: Convert
Py_TYPE()and
Py_SIZE()back to macros to allow using them as an l-value. Many third party C extension modules rely on the ability of using Py_TYPE() and Py_SIZE() to set an object type and size:
Py_TYPE(obj) = type;and
Py_SIZE(obj) = size;.
bpo-1635741: Port
symtableextension module to multiphase initialization (PEP 489)
bpo-1635741: Port
grpand
pwdextension modules to multiphase initialization (PEP 489)
bpo-1635741: Port _random extension module to multiphase initialization (PEP 489)
bpo-1635741: Port _hashlib extension module to multiphase initialization (PEP 489)
bpo-41713: Removed the undocumented
PyOS_InitInterrupts()function. Initializing Python already implicitly installs signal handlers: see
PyConfig.install_signal_handlers. Patch by Victor Stinner.
bpo-40170: The
Py_TRASHCAN_BEGINmacro no longer accesses PyTypeObject attributes, but now can get the condition by calling the new private
_PyTrash_cond()function which hides implementation details.
bpo-42260:.. Patch by Victor Stinner.
bpo-42260: The
PyConfig_Read()function now only parses
PyConfig.argvarguments once:
PyConfig.parse_argvis set to
2after arguments are parsed. Since Python arguments are strippped from
PyConfig.argv, parsing arguments twice would parse the application options as Python options.
bpo-42262: Added
Py_NewRef()and
Py_XNewRef()functions to increment the reference count of an object and return the object. Patch by Victor Stinner.
bpo-42260: When
Py_Initialize()is called twice, the second call now updates more
sysattributes for the configuration, rather than only
sys.argv. Patch by Victor Stinner.
bpo-41832: The
PyType_FromModuleAndSpec()function now accepts NULL
tp_docslot.
bpo-1635741: Added
PyModule_AddObjectRef()function: similar to
PyModule_AddObject()but don’t steal a reference to the value on success. Patch by Victor Stinner.
bpo-42171: The
METH_FASTCALLcalling convention is added to the limited API. The functions
PyModule_AddType(),
PyType_FromModuleAndSpec(),
PyType_GetModule()and
PyType_GetModuleState()are added to the limited API on Windows.
bpo-42085: Add dedicated entry to PyAsyncMethods for sending values
bpo-41073:
PyType_GetSlot()can now accept static types.
bpo-30459:. Patch by Zackery Spytz and Victor Stinner.
Python 3.10.0 alpha 2¶
Release date: 2020-11-03.
Core and Builtins¶
bpo-42236: If the
nl_langinfo(CODESET)function returns an empty string, Python now uses UTF-8 as the filesystem encoding. Patch by Victor Stinner. ‘!=’ token in the
barry_as_fluflrule. Patch by Pablo Galindo.
bpo-42206: Propagate and raise the errors caused by
PyAST_Validate()in the parser.
bpo-41796: The
astmodule internal state is now per interpreter. Patch by Victor Stinner.93: The
LOAD_ATTRinstruction now uses new “per opcode cache” mechanism and it is about 36% faster now. Patch by Pablo Galindo and Yury Selivanov.
bpo-42030: Support for the legacy AIX-specific shared library loading support has been removed. All versions of AIX since 4.3 have supported and defaulted to using the common Unix mechanism instead.-41974: Removed special methods
__int__,
__float__,
__floordiv__,
__mod__,
__divmod__,
__rfloordiv__,
__rmod__and
__rdivmod__of the
complexclass. They always raised a
TypeError.
bpo-41902: Micro optimization when compute
sq_itemand
mp_subscriptof
range. Patch by Dong-hee Na.
bpo-41894: When loading a native module and a load failure occurs, prevent a possible UnicodeDecodeError when not running in a UTF-8 locale by decoding the load error message using the current locale’s encoding.
bpo-41902: Micro optimization for range.index if step is 1. Patch by Dong-hee Na.
bpo-41435: Add
sys._current_exceptions()function to retrieve a dictionary mapping each thread’s identifier to the topmost exception currently active in that thread at the time the function is called.
bpo-38605: Enable
from __future__ import annotations(PEP 563) by default. The values found in
__annotations__dicts are now strings, e.g.
{"x": "int"}instead of
{"x": int}.
Library¶-29566:
binhex.binhex()consistently writes macOS 9 line endings.
bpo-26789: The
logging.FileHandlerclass now keeps a reference to the builtin
open()function to be able to open or reopen the file during Python finalization. Fix errors like:
NameError: name 'open' is not defined. Patch by Victor Stinner.
bpo-42157: Removed the
unicodedata.ucnhash_CAPIattribute which was an internal PyCapsule object. The related private
_PyUnicode_Name_CAPIstructure was moved to the internal C API. Patch by Victor Stinner.
bpo-42157: Convert the
unicodedataextension module to the multiphase initialization API (PEP 489) and convert the
unicodedata.UCDstatic type to a heap type. Patch by Mohamed Koubaa and Victor Stinner.
bpo-42146: Fix memory leak in
subprocess.Popen()in case an uid (gid) specified in
user(
group,
extra_groups) overflows
uid_t(
gid_t).
bpo-42103:
InvalidFileExceptionand
RecursionErrorare now the only errors caused by loading malformed binary Plist file (previously ValueError and TypeError could be raised in some specific cases).
bpo-41490: In
importlib.resources,
.pathmethod is more aggressive about releasing handles to zipfile objects early, enabling use-cases like certifi to leave the context open but delete the underlying zip file.
bpo-41052: Pickling heap types implemented in C with protocols 0 and 1 raises now an error instead of producing incorrect data.
bpo-42089: In
importlib.metadata.PackageNotFoundError, make reference to the package metadata being missing to improve the user experience.-19270:
sched.scheduler.cancel()will now cancel the correct event, if two events with same priority are scheduled for the same time. Patch by Bar Harel.
bpo-28660:
textwrap.wrap()now attempts to break long words after hyphens when
break_long_words=Trueand
break_on_hyphens=True.
bpo-35823: Use
vfork()instead of
fork()for
subprocess.Popen()on Linux to improve performance in cases where it is deemed safe.
bpo-42043: Add support for
zipfile.Pathinheritance.
zipfile.Path.is_file()now returns False for non-existent names.
zipfile.Pathobjects now expose a
.filenameattribute and rely on that to resolve
.nameand
.parentwhen the
Pathobject is at the root of the zipfile.
bpo-42021: Fix possible ref leaks in
sqlite3module init.
bpo-39101: Fixed tests using IsolatedAsyncioTestCase from hanging on BaseExceptions.
bpo-41976: Fixed a bug that was causing
ctypes.util.find_library()to return
Nonewhen triying to locate a library in an environment when gcc>=9 is available and
ldconfigis not. Patch by Pablo Galindo
bpo-41943: Fix bug where TestCase.assertLogs doesn’t correctly filter messages by level.
bpo-41923: Implement PEP 613, introducing
typing.TypeAliasannotation.
bpo-41905: A new function in abc: update_abstractmethods to re-calculate an abstract class’s abstract status. In addition, dataclass has been changed to call this function.
bpo-23706: Added newline parameter to
pathlib.Path.write_text().
bpo-41876: Tkinter font class repr uses font name
bpo-41831:
str()for the
typeattribute of the
tkinter.Eventobject always returns now the numeric code returned by Tk instead of the name of the event type.
bpo-39337:
encodings.normalize_encoding()now ignores non-ASCII characters.
bpo-41747: Ensure all methods that generated from
dataclasses.dataclass()objects now have the proper
__qualname__attribute referring to the class they belong to. Patch by Batuhan Taskaya.
bpo-30681: Handle exceptions caused by unparsable date headers when using email “default” policy. Patch by Tim Bell, Georges Toth
bpo-41586: Add F_SETPIPE_SZ and F_GETPIPE_SZ to fcntl module. Allow setting pipesize on subprocess.Popen.
bpo-41229: Add
contextlib.aclosingfor deterministic cleanup of async generators which is analogous to
contextlib.closingfor non-async generators. Patch by Joongi Kim and John Belmonte.
bpo-16396: Allow
ctypes.wintypesto be imported on non-Windows systems.
bpo-4356: Add a key function to the bisect module.
bpo-40592:
shutil.which()now ignores empty entries in
PATHEXTinstead of treating them as a match.
bpo-40492: Fix
--outfilefor
cProfile/
profilenot writing the output file in the original directory when the program being profiled changes the working directory. PR by Anthony Sottile.
bpo-34204: The
shelvemodule now uses
pickle.DEFAULT_PROTOCOLby default instead of
pickleprotocol
3.
bpo-27321: Fixed KeyError exception when flattening an email to a string attempts to replace a non-existent Content-Transfer-Encoding header.
bpo-38976: The
http.cookiejarmodule now supports the parsing of cookies in CURL-style cookiejar files through MozillaCookieJar on all platforms. Previously, such cookie entries would be silently ignored when loading a cookiejar with such entries.
Additionally, the HTTP Only attribute is persisted in the object, and will be correctly written to file if the MozillaCookieJar object is subsequently dumped.
Documentation¶-39693: Fix tarfile’s extractfile documentation
bpo-39416: Document some restrictions on the default string representations of numeric classes.
Tests¶-41306: Fixed a failure in
test_tk.test_widgets.ScaleTesthappening when executing the test with Tk 8.6.10.
Build¶
Windows¶
bpo-38439: Updates the icons for IDLE in the Windows Store package.
bpo-38252: Use 8-byte step to detect ASCII sequence in 64-bit Windows build.
bpo-39107: Update Tcl and Tk to 8.6.10 in Windows installer.
bpo-41557: Update Windows installer to use SQLite 3.33.0.
bpo-38324: Avoid Unicode errors when accessing certain locale data on Windows.
macOS¶
IDLE¶
bpo-33987: Mostly finish using ttk widgets, mainly for editor, settings, and searches. Some patches by Mark Roseman..
C API¶
bpo-42157: The private
_PyUnicode_Name_CAPIstructure of the PyCapsule API
unicodedata.ucnhash_CAPIhas been moved to the internal C API. Patch by Victor Stinner.
bpo-42015: Fix potential crash in deallocating method objects when dynamically allocated
PyMethodDef’s lifetime is managed through the
selfargument of a
PyCFunction.
bpo-40423: The
subprocessmodule and
os.closerangewill now use the
close_range(low, high, flags)syscall when it is available for more efficient closing of ranges of descriptors.
bpo-41845:
PyObject_GenericGetDict()is available again in the limited API when targeting 3.10 or later.
bpo-40422: Add
_Py_closerangefunction to provide performant closing of a range of file descriptors.
bpo-41986:
Py_FileSystemDefaultEncodeErrorsand
Py_UTF8Modeare available again in limited API.
bpo-41756: Add
PyIter_Sendfunction to allow sending value into generator/coroutine/iterator without raising StopIteration exception to signal return.
bpo-41784: Added
PyUnicode_AsUTF8AndSizeto the limited C API.
Python 3.10.0 alpha 1¶
Release date: 2020-10-05).
bpo-39603: Prevent http header injection by rejecting control characters in http.client.putrequest(…).
Core and Builtins¶
bpo-41909: Fixed stack overflow in
issubclass()and
isinstance()when getting the
__bases__attribute leads to infinite recursion.
bpo-41922: Speed up calls to
reversed()by using the PEP 590
vectorcallcalling convention. Patch by Dong-hee Na.
bpo-41873: Calls to
float()are now faster due to the
vectorcallcalling convention. Patch by Dennis Sweeney.
bpo-41870: Speed up calls to
bool()by using the PEP 590
vectorcallcalling convention. Patch by Dong-hee Na.
bpo-1635741: Port the
_bisectmodule to the multi-phase initialization API (PEP 489).
bpo-39934: Correctly count control blocks in ‘except’ in compiler. Ensures that a syntax error, rather a fatal error, occurs for deeply nested, named exception handlers.
bpo-41780: Fix
__dir__()of
types.GenericAlias. Patch by Batuhan Taskaya.
bpo-1635741: Port the
_lsprofextension module to multi-phase initialization (PEP 489).
bpo-1635741: Port the
cmathextension module to multi-phase initialization (PEP 489).
bpo-1635741: Port the
_scproxyextension module to multi-phase initialization (PEP 489).
bpo-1635741: Port the
termiosextension module to multi-phase initialization (PEP 489).
bpo-1635741: Convert the
_sha256extension module types to heap types.
bpo-41690: Fix a possible stack overflow in the parser when parsing functions and classes with a huge amount of arguments. Patch by Pablo Galindo.
bpo-1635741: Port the
_overlappedextension module to multi-phase initialization (PEP 489).
bpo-1635741: Port the
_curses_panelextension module to multi-phase initialization (PEP 489).
bpo-1635741: Port the
_opcodeextension module to multi-phase initialization (PEP 489).
bpo-41681: Fixes the wrong error description in the error raised by using 2
,in format string in f-string and
str.format().
bpo-41675: The implementation of
signal.siginterrupt()now uses
sigaction()(if it is available in the system) instead of the deprecated
siginterrupt(). Patch by Pablo Galindo.
bpo-41670: Prevent line trace being skipped on platforms not compiled with
USE_COMPUTED_GOTOS. Fixes issue where some lines nested within a try-except block were not being traced on Windows.
bpo-41654: Fix a crash that occurred when destroying subclasses of
MemoryError. Patch by Pablo Galindo.
bpo-1635741: Port the
zlibextension module to multi-phase initialization (PEP 489).-40077: Convert
_operatorto use
PyType_FromSpec().
bpo-1653741: Port
_sha3to multi-phase init. Convert static types to heap types.
bpo-1635741: Port the
_blake2extension module to the multi-phase initialization API (PEP 489).-1635741: Port the
_sha1,
_sha512, and
_md5extension modules to multi-phase initialization API (PEP 489).
bpo-41431: Optimize
dict_merge()for copying dict (e.g.
dict(d)and
{}.update(d)).
bpo-41428: Implement PEP 604. This supports (int | str) etc. in place of Union[str, int].
bpo-41340: Removed fallback implementation for
strdup.
bpo-38156: Handle interrupts that come after EOF correctly in
PyOS_StdioReadline.
bpo-41342:
round()with integer argument is now faster (9–60%).
bpo-41334: Constructors
str(),
bytes()and
bytearray()are now faster (around 30–40% for small objects).
bpo-41295: Resolve a regression in CPython 3.8.4 where defining “__setattr__” in a multi-inheritance setup and calling up the hierarchy chain could fail if builtins/extension types were involved in the base types.
bpo-41323: Bytecode optimizations are performed directly on the control flow graph. This will result in slightly more compact code objects in some circumstances.
bpo-41247: Always cache the running loop holder when running
asyncio.set_running_loop.
bpo-41252: Fix incorrect refcounting in _ssl.c’s
_servername_callback().
bpo-1635741: Port
multiprocessingto multi-phase initialization
bpo-1635741: Port
winapito multiphase initialization-1635741: Port
faulthandlerto multiphase initialization.
bpo-1635741: Port
sha256to multiphase initialization
bpo-41175: Guard against a NULL pointer dereference within bytearrayobject triggered by the
bytearray() + bytearray()operation.
bpo-41100: add arm64 to the allowable Mac OS arches in mpdecimal.h
bpo-41094: Fix decoding errors with audit when open files with non-ASCII names on non-UTF-8 locale.
bpo-39960: The “hackcheck” that prevents sneaking around a type’s __setattr__() by calling the superclass method was rewritten to allow C implemented heap types.
bpo-41084: Prefix the error message with ‘f-string: ‘, when parsing an f-string expression which throws a
SyntaxError.
bpo-40521: Empty frozensets are no longer singletons.
bpo-41076: Pre-feed the parser with the location of the f-string expression, not the f-string itself, which allows us to skip the shifting of the AST node locations after the parsing is completed.: Rename
PyPegen*functions to
PyParser*, so that we can remove the old set of
PyParser*functions that were using the old parser, but keep everything backwards-compatible.
bpo-35975: Stefan Behnel reported that cf_feature_version is used even when PyCF_ONLY_AST is not set. This is against the intention and against the documented behavior, so it’s been fixed.
bpo-40939: Remove the remaining files from the old parser and the
symbolmodule.
bpo-40077: Convert
_bz2to use
PyType_FromSpec().
bpo-41006: The
encodings.latin_1module is no longer imported at startup. Now it is only imported when it is the filesystem encoding or the stdio encoding.
bpo-40636:
zip()now supports PEP 618’s
strictparameter, which raises a
ValueErrorif the arguments are exhausted at different lengths. Patch by Brandt Bucher.
bpo-1635741: Port
_gdbmto multiphase initialization.-1635741: Port
_dbmto multiphase initialization.
bpo-40957: Fix refleak in _Py_fopen_obj() when PySys_Audit() fails
bpo-40950: Add a state to the
nismodule (PEP 3121) and apply the multiphase initialization. Patch by Dong-hee Na.
bpo-40947: The Python Path Configuration now takes
PyConfig.platlibdirin account.
bpo-40939: Remove the old parser, the
parsermodule and all associated support code, command-line options and environment variables. Patch by Pablo Galindo.90: Each dictionary view now has a
mappingattribute that provides a
types.MappingProxyTypewrapping the original dictionary. Patch contributed by Dennis Sweeney.
bpo-40889: Improved the performance of symmetric difference operations on dictionary item views. Patch by Dennis Sweeney.-1635741: Port
fcntlto multiphase initialization.
bpo-19468: Delete unnecessary instance check in importlib.reload(). Patch by Furkan Önder.
bpo-40824: Unexpected errors in calling the
__iter__method are no longer masked by
TypeErrorin the
inoperator and functions
contains(),
indexOf()and
countOf()of the
operatormodule.
bpo-40792: Attributes
start,
stopand
stepof the
rangeobject now always has exact type
int. Previously, they could have been an instance of a subclass of
int.-39573:
Py_TYPE()is changed to the inline static function. Patch by Dong-hee Na.
bpo-40696: Fix a hang that can arise after
generator.throw()due to a cycle in the exception context chain.
bpo-40521: Each interpreter now its has own free lists, singletons and caches:
Free lists: float, tuple, list, dict, frame, context, asynchronous generator, MemoryError.
Singletons: empty tuple, empty bytes string, empty Unicode string, single byte character, single Unicode (latin1) character.
Slice cache.
They are no longer shared by all interpreters.
bpo-40679: Certain
TypeErrormessages about missing or extra arguments now include the function’s qualified name. Patch by Dennis Sweeney.
bpo-29590: Make the stack trace correct after calling
generator.throw()on a generator that has yielded from a
yield from.
bpo-4022: Improve performance of generators by not raising internal StopIteration.
bpo-1635741: Port
mmapto multiphase initialization.
bpo-1635741: Port
_lzmato multiphase initialization.
bpo-37999: Builtin and extension functions that take integer arguments no longer accept
Decimals,
Fractions and other objects that can be converted to integers only with a loss (e.g. that have the
__int__()method but do not have the
__index__()method).
bpo-29882: Add
int.bit_count(), counting the number of ones in the binary representation of an integer. Patch by Niklas Fiekas.
bpo-36982: Use ncurses extended color functions when available to support terminals with 256 colors, and add the new function
curses.has_extended_color_support()to indicate whether extended color support is provided by the underlying ncurses library.
bpo-19569: Add the private macros
_Py_COMP_DIAG_PUSH,
_Py_COMP_DIAG_IGNORE_DEPR_DECLS, and
_Py_COMP_DIAG_POP.
bpo-26680: The int type now supports the x.is_integer() method for compatibility with float.
Library¶
bpo-41900: C14N 2.0 serialisation in xml.etree.ElementTree failed for unprefixed attributes when a default namespace was defined.
bpo-41887: Strip leading spaces and tabs on
ast.literal_eval(). Also document stripping of spaces and tabs for
eval().
bpo-41773: Note in documentation that
random.choices()doesn’t support non-finite weights, raise
ValueErrorwhen given non-finite weights.
bpo-41840: Fix a bug in the
symtablemodule that was causing module-scope global variables to not be reported as both local and global. Patch by Pablo Galindo.
bpo-41842: Add
codecs.unregister()function to unregister a codec search function.
bpo-40564: In
zipfile.Path, mutate the passed ZipFile object type instead of making a copy. Prevents issues when both the local copy and the caller’s copy attempt to close the same file handle.
bpo-40670: More reliable validation of statements in
timeit.Timer. It now accepts “empty” statements (only whitespaces and comments) and rejects misindentent statements.
bpo-41833: The
threading.Threadconstructor now uses the target name if the target argument is specified but the name argument is omitted.
bpo-41817: fix
tkinter.EventTypeEnum so all members are strings, and none are tuples
bpo-41810:
types.EllipsisType,
types.NotImplementedTypeand
types.NoneTypehave been reintroduced, providing a new set of types readily interpretable by static type checkers.
bpo-41815: Fix SQLite3 segfault when backing up closed database. Patch contributed by Peter David McCormick.
bpo-41816: StrEnum added: it ensures that all members are already strings or string candidates
bpo-41517: fix bug allowing Enums to be extended via multiple inheritance
bpo-39587: use the correct mix-in data type when constructing Enums
bpo-41792: Add is_typeddict function to typing.py to check if a type is a TypedDict class
Previously there was no way to check that without using private API. See the
relevant issue in python/typing
bpo-41789: Honor
objectoverrides in
Enumclass creation (specifically,
__str__,
__repr__,
__format__, and
__reduce_ex__).
bpo-32218:
enum.Flagand
enum.IntFlagmembers are now iterable
bpo-39651: Fix a race condition in the
call_soon_threadsafe()method of
asyncio.ProactorEventLoop: do nothing if the self-pipe socket has been closed.
bpo-1635741: Port the
mashalextension module to the multi-phase initialization API (PEP 489).
bpo-1635741: Port the
_stringextension module to the multi-phase initialization API (PEP 489).
bpo-41732: Added an iterator to
memoryview.-41662: No longer override exceptions raised in
__len__()of a sequence of parameters in
sqlite3with
ProgrammingError.
bpo-39010: Restarting a
ProactorEventLoopon Windows no longer logs spurious
ConnectionResetErrors.
bpo-41638:
ProgrammingErrormessage for absent parameter in
sqlite3contains now the name of the parameter instead of its index when parameters are supplied as a dict.
bpo-41662: Fixed crash when mutate list of parameters during iteration in
sqlite3.
bpo-41513: Improved the accuracy of math.hypot(). Internally, each step is computed with extra precision so that the result is now almost always correctly rounded.
bpo-41609: The pdb whatis command correctly reports instance methods as ‘Method’ rather than ‘Function’.
bpo-39994: Fixed pprint’s handling of dict subclasses that override __repr__.-41528: turtle uses math module functions to convert degrees to radians and vice versa and to calculate vector norm
bpo-41513: Minor algorithmic improvement to math.hypot() and math.dist() giving small gains in speed and accuracy.
bpo-41503: Fixed a race between setTarget and flush in logging.handlers.MemoryHandler.
bpo-41497: Fix potential UnicodeDecodeError in dis module.
bpo-41467: On Windows, fix asyncio
recv_into()return value when the socket/pipe is closed (
BrokenPipeError): return
0rather than an empty byte string (
b'').
bpo-41425: Make tkinter doc example runnable.
bpo-41421: Make an algebraic simplification to random.paretovariate(). It now is slightly less subject to round-off error and is slightly faster. Inputs that used to cause ZeroDivisionError now cause an OverflowError instead.
bpo-41440: Add
os.cpu_count()support for VxWorks RTOS.
bpo-41316: Fix the
tarfilemodule to write only basename of TAR file to GZIP compression header.
bpo-41384: Raise TclError instead of TypeError when an unknown option is passed to tkinter.OptionMenu.
bpo-41317: Use add_done_callback() in asyncio.loop.sock_accept() to unsubscribe reader early on cancellation.
bpo-41364: Reduce import overhead of
uuid.
bpo-35328: Set the environment variable
VIRTUAL_ENV_PROMPTat
venvactivation.
bpo-41341: Recursive evaluation of
typing.ForwardRefin
get_type_hints.
bpo-41344: Prevent creating
shared_memory.SharedMemoryobjects with
size=0.
bpo-41333:
collections.OrderedDict.pop()is now 2 times faster.73: Speed up any transport using
_ProactorReadPipeTransportby calling
recv_intoinstead of
recv, thus not creating a new buffer for each
recvcall in the transport’s read loop.
bpo-41235: Fix the error handling in
ssl.SSLContext.load_dh_params().
bpo-41207: In distutils.spawn, restore expectation that DistutilsExecError is raised when the command is not found.
bpo-29727: Register
array.arrayas a
MutableSequence. Patch by Pablo Galindo.
bpo-39168: Remove the
__new__method of
typing.Generic.
bpo-41194: Fix a crash in the
_astmodule: it can no longer be loaded more than once. It now uses a global state rather than a module state.
bpo-41195: Add read-only ssl.SSLContext.security_level attribute to retrieve the context’s security level.
bpo-41193: The
write_history()atexit function of the readline completer now ignores any
OSErrorto ignore error if the filesystem is read-only, instead of only ignoring
FileNotFoundErrorand
PermissionError.
bpo-41182: selector: use DefaultSelector based upon implementation-31082: Use the term “iterable” in the docstring for
functools.reduce().
bpo-40521: Remove freelist from collections.deque().: Invalid file descriptor values are now prevented from being passed to os.fpathconf. (discovered by Coverity)-41025: Fixed an issue preventing the C implementation of
zoneinfo.ZoneInfofrom being subclassed.
bpo-35018: Add the
xml.sax.handler.LexicalHandlerclass that is present in other SAX XML implementations.
bpo-41002: Improve performance of HTTPResponse.read with a given amount. Patch by Bruce Merry.24: Ensure
importlib.resources.pathreturns an extant path for the SourceFileLoader’s resource reader. Avoids the regression identified in master while a long-term solution is devised.
bpo-40955: Fix a minor memory leak in
subprocessmodule when extra_groups was specified.
bpo-40855: The standard deviation and variance functions in the statistics module were ignoring their mu and xbar arguments.
bpo-40939: Use the new PEG parser when generating the stdlib
keywordmodule.
bpo-23427: Add
sys.orig_argvattribute: the list of the original command line arguments passed to the Python executable.
bpo-33689: Ignore empty or whitespace-only lines in .pth files. This matches the documentated behavior. Before, empty lines caused the site-packages dir to appear multiple times in sys.path. By Ido Michael, contributors Malcolm Smith and Tal Einat.
bpo-40884: Added a
defaultsparameter to
logging.Formatter, to allow specifying default values for custom fields. Patch by Asaf Alon and Bar Harel.
bpo-40876: Clarify error message in the
csvmodule.
bpo-39791: Refresh importlib.metadata from importlib_metadata 1.6.1.
bpo-40807: Stop codeop._maybe_compile, used by code.InteractiveInterpreter (and IDLE). from emitting each warning three times.
bpo-32604: Fix reference leak in the
selectmodule when the module is imported in a subinterpreter.
bpo-39791: Built-in loaders (SourceFileLoader and ZipImporter) now supply
TraversableResourcesimplementations for
ResourceReader, and the fallback function has been removed.
bpo-39314:
rlcompleter.Completerand the standard Python shell now close the parenthesis for functions that take no arguments. Patch contributed by Rémi Lapeyre.-40834: Fix truncate when sending str object with_xxsubinterpreters.channel_send.
bpo-40755: Add rich comparisons to collections.Counter().
bpo-26407: Unexpected errors in calling the
__iter__method are no longer masked by
TypeErrorin
csv.reader(),
csv.writer.writerow()and
csv.writer.writerows().
bpo-39384: Fixed email.contentmanager to allow set_content() to set a null string.
bpo-40744: The
sqlite3module uses SQLite API functions that require SQLite v3.7.3 or higher. This patch removes support for older SQLite versions, and explicitly requires SQLite 3.7.3 both at build, compile and runtime. Patch by Sergey Fedoseev and Erlend E. Aasland.
bpo-40777: Initialize PyDateTime_IsoCalendarDateType.tp_base at run-time to avoid errors on some compilers.
bpo-38488: Update ensurepip to install pip 20.1.1 and setuptools 47.1.0.
bpo-40792: The result of
operator.index()now always has exact type
int. Previously, the result could have been an instance of a subclass of
int.-16995: Add
base64.b32hexencode()and
base64.b32hexdecode()to support the Base32 Encoding with Extended Hex Alphabet.-40756: The second argument (extra) of
LoggerAdapter.__init__now defaults to None.
bpo-37129: Add a new
os.RWF_APPENDflag for
os.pwritev().
bpo-40737: Fix possible reference leak for
sqlite3initialization.
bpo-40726: Handle cases where the
end_linenois
Noneon
ast.increment_lineno().626: Add h5 file extension as MIME Type application/x-hdf5, as per HDF Group recommendation for HDF5 formatted data files. Patch contributed by Mark Schwab.
bpo-25920: On macOS, when building Python for macOS 10.4 and older, which wasn’t the case for python.org macOS installer,
socket.getaddrinfo()no longer uses an internal lock to prevent race conditions when calling
getaddrinfo()which is thread-safe since macOS 10.5. Python 3.9 requires macOS 10.6 or newer. The internal lock caused random hang on fork when another thread was calling
socket.getaddrinfo(). The lock was also used on FreeBSD older than 5.3, OpenBSD older than 201311 and NetBSD older than 4.-36543: Restored the deprecated
xml.etree.cElementTreemodule.
bpo-40611:
MAP_POPULATEconstant has now been added to the list of exported
mmapmodule flags.
bpo-39881: PEP 554 for use in the test suite. (Patch By Joannah Nanjekye)
bpo-13097:
ctypesnow raises an
ArgumentErrorwhen a callback is invoked with more than 1024 arguments.
bpo-39385: A new test assertion context-manager,
unittest.assertNoLogs()will ensure a given block of code emits no log messages using the logging module. Contributed by Kit Yan Choi.
bpo-23082: Updated the error message and docs of PurePath.relative_to() to better reflect the function behaviour.
bpo-40318: Use SQLite3 trace v2 API, if it is available.
bpo-40105: ZipFile truncates files to avoid corruption when a shorter comment is provided in append (“a”) mode. Patch by Jan Mazur.
bpo-40084: Fix
Enum.__dir__: dir(Enum.member) now includes attributes as well as methods.
bpo-31122: ssl.wrap_socket() now raises ssl.SSLEOFError rather than OSError when peer closes connection during TLS negotiation
bpo-39728: fix default
_missing_so a duplicate
ValueErroris not set as the
__context__of the original
ValueError-38731: Add
--quietoption to command-line interface of
py_compile. Patch by Gregory Schevchenko.
bpo-35714:
struct.erroris now raised if there is a null character in a
structformat string.
bpo-38144: Added the root_dir and dir_fd parameters in
glob.glob().
bpo-26543: Fix
IMAP4.noop()when debug mode is enabled (ex:
imaplib.Debug = 3).
bpo-12178:
csv.writer()now correctly escapes escapechar when input contains escapechar. Patch by Catalin Iacob, Berker Peksag, and Itay Elbirt.
bpo-36290: AST nodes are now raising
TypeErroron conflicting keyword arguments. Patch contributed by Rémi Lapeyre.
bpo-33944: Added site.py site-packages tracing in verbose mode.
bpo-35078: Refactor formatweekday, formatmonthname methods in LocaleHTMLCalendar and LocaleTextCalendar classes in calendar module to call the base class methods.This enables customizable CSS classes for LocaleHTMLCalendar. Patch by Srinivas Reddy Thatiparthy
bpo-29620:
assertWarns()no longer raises a
RuntimeExceptionwhen accessing a module’s
__warningregistry__causes importation of a new module, or when a new module is imported in another thread. Patch by Kernc.
bpo-31844: Remove
ParserBase.error()method from the private and undocumented
_markupbasemodule.
html.parser.HTMLParseris the only subclass of
ParserBaseand its
error()implementation was deprecated in Python 3.4 and removed in Python 3.5.
bpo-34226: Fix
cgi.parse_multipartwithout content_length. Patch by Roger Duran
bpo-33660: Fix pathlib.PosixPath to resolve a relative path located on the root directory properly.
bpo-28557: Improve the error message for a misbehaving
rawio.readinto
bpo-26680: The d.is_integer() method is added to the Decimal type, for compatibility with other number types.
bpo-26680: The x.is_integer() method is incorporated into the abstract types of the numeric tower, Real, Rational and Integral, with appropriate default implementations.
Documentation¶
bpo-41428: Add documentation for PEP 604 (Allow writing union types as
X | Y).
bpo-41774: In Programming FAQ “Sequences (Tuples/Lists)” section, add “How do you remove multiple items from a list”.
bpo-35293: Fix RemovedInSphinx40Warning when building the documentation. Patch by Dong-hee Na.
bpo-37149: Change Shipman tkinter doc link from archive.org to TkDocs. (The doc has been removed from the NMT server.) The new link responds much faster and includes a short explanatory note.
bpo-41726: Update the refcounts info of
PyType_FromModuleAndSpec.-41045: Add documentation for debug feature of f-strings.
bpo-41314: Changed the release when
from __future__ import annotationsbecomes the default from
4.0to
3.10(following a change in PEP 563).
bpo-40979: Refactored typing.rst, arranging more than 70 classes, functions, and decorators into new sub-sections.
bpo-40552: Fix in tutorial section 4.2. Code snippet is now correct.
bpo-39883: Make code, examples, and recipes in the Python documentation be licensed under the more permissive BSD0 license in addition to the existing Python 2.0 license.
bpo-37703: Updated Documentation to comprehensively elaborate on the behaviour of gather.cancel()
Tests¶
bpo-41939: Fix test_site.test_license_exists_at_url(): call
urllib.request.urlcleanup()to reset the global
urllib.request._opener. Patch by Victor Stinner.
bpo-41731: Make test_cmd_line_script pass with option ‘-vv’.
bpo-41602: Add tests for SIGINT handling in the runpy module.
bpo-41521:
test.support: Rename
blacklistparameter of
check__all__()to
not_exported.
bpo-41477: Make ctypes optional in test_genericalias.-17258: Skip some
multiprocessingtests when MD5 hash digest is blocked.
bpo-31904: Increase LOOPBACK_TIMEOUT to 10 for VxWorks RTOS.
bpo-38169: Increase code coverage for SharedMemory and ShareableList
bpo-34401: Make test_gdb properly run on HP-UX. Patch by Michael Osipov.
Build¶
bpo-38249: Update
Py_UNREACHABLEto use __builtin_unreachable() if only the compiler is able to use it. Patch by Dong-hee Na.
bpo-41617: Fix
pycore_bitutils.hheader file to support old clang versions:
__builtin_bswap16()is not available in LLVM clang 3.0.
bpo-40204: Pin Sphinx version to 2.3.1 in
Doc/Makefile.
bpo-36020: The C99 functions
snprintf()and
vsnprintf()are now required to build Python.
bpo-40684:
make installnow uses the
PLATLIBDIRvariable for the destination
lib-dynload/directory when
./configure --with-platlibdiris used.
bpo-40683: Fixed an issue where the
zoneinfomodule and its tests were not included when Python is installed with
make.
Windows¶
bpo-41744: Fixes automatic import of props file when using the Nuget package.
bpo-41627: The user site directory for 32-bit now includes a
-32suffix to distinguish it from the 64-bit interpreter’s directory.
bpo-41526: Fixed layout of final page of the installer by removing the special thanks to Mark Hammond (with his permission)..
bpo-41142:
msilibnow supports creating CAB files with non-ASCII file path and adding files with non-ASCII file path to them.
bpo-41074: Fixed support of non-ASCII names in functions
msilib.OpenDatabase()and
msilib.init_database()and non-ASCII SQL in method
msilib.Database.OpenView().
bpo-41039: Stable ABI redirection DLL (python3.dll) now uses
#pragma comment(linker)for re-exporting.-37556: Extend py.exe help to mention overrides via venv, shebang, environmental variables & ini files.
macOS¶
bpo-41557: Update macOS installer to use SQLite 3.33.0.-40741: Update macOS installer to use SQLite 3.32.3.
bpo-41005: fixed an XDG settings issue not allowing macos to open browser in webbrowser.py
bpo-40741: Update macOS installer to use SQLite 3.32.2.
IDLE¶
bpo-41775: Use ‘IDLE Shell’ as shell title
bpo-35764: Rewrite the Calltips doc section.
bpo-40181: In calltips, stop reminding that ‘/’ marks the end of positional-only arguments..
bpo-41300: Save files with non-ascii chars. Fix regression released in 3.9.0b4 and 3.8.4.
bpo-37765: Add keywords to module name completion list. Rewrite Completions section of IDLE doc.
bpo-41152: The encoding of
stdin,
stdoutand
stderrin IDLE is now always UTF-8.
bpo-41144: Make Open Module open a special module such as os.path.
bpo-39885: Make context menu Cut and Copy work again when right-clicking within a selection.
bpo-40723: Make test_idle pass when run after import.
C API¶
bpo-41936: Removed undocumented macros
Py_ALLOW_RECURSIONand
Py_END_ALLOW_RECURSIONand the
recursion_criticalfield of the
PyInterpreterStatestructure.
bpo-41692: The
PyUnicode_InternImmortal()function is now deprecated and will be removed in Python 3.12: use
PyUnicode_InternInPlace()instead. Patch by Victor Stinner.
bpo-41842: Add
PyCodec_Unregister()function to unregister a codec search function.
bpo-41834: Remove the
_Py_CheckRecursionLimitvariable: it has been replaced by
ceval.recursion_limitof the
PyInterpreterStatestructure. Patch by Victor Stinner.
bpo-41689: Types created with
PyType_FromSpec()now make any signature in their
tp_docslot accessible from
__text_signature__.
bpo-41524: Fix bug in PyOS_mystrnicmp and PyOS_mystricmp that incremented pointers beyond the end of a string.
bpo-41324: Add a minimal decimal capsule API. The API supports fast conversions between Decimals up to 38 digits and their triple representation as a C struct.
bpo-30155: Add
PyDateTime_DATE_GET_TZINFO()and
PyDateTime_TIME_GET_TZINFO()macros for accessing the
tzinfoattributes of
datetime.datetimeand
datetime.timeobjects.
bpo-40170: Revert
PyType_HasFeature()change: it reads again directly the
PyTypeObject.tp_flagsmember when the limited C API is not used, rather than always calling
PyType_GetFlags()which hides implementation details.
bpo-41123: Remove
PyUnicode_AsUnicodeCopy.
bpo-41123: Removed
PyLong_FromUnicode().
bpo-41123: Removed
PyUnicode_GetMax().
bpo-41123: Removed
Py_UNICODE_str*functions manipulating
Py_UNICODE*strings.
bpo-41103:
PyObject_AsCharBuffer(),
PyObject_AsReadBuffer(),
PyObject_CheckReadBuffer(), and
PyObject_AsWriteBuffer()are removed. Please migrate to new buffer protocol;
PyObject_GetBuffer()and
PyBuffer_Release().
bpo-36346: Raises DeprecationWarning for
PyUnicode_FromUnicode(NULL, size)and
PyUnicode_FromStringAndSize(NULL, size)with
size > 0.
bpo-36346: Mark
Py_UNICODE_COPY,
Py_UNICODE_FILL,
PyUnicode_WSTR_LENGTH,
PyUnicode_FromUnicode,
PyUnicode_AsUnicode, and
PyUnicode_AsUnicodeAndSizeas deprecated in C. Remove
Py_UNICODE_MATCHwhich was deprecated and broken since Python 3.3.
bpo-40989: The
PyObject_INIT()and
PyObject_INIT_VAR()macros become aliases to, respectively,
PyObject_Init()and
PyObject_InitVar()functions.
bpo-36020: On Windows,
#include "pyerrors.h"no longer defines
snprintfand
vsnprintfmacros.
bpo-40943: The
PY_SSIZE_T_CLEANmacro must now be defined to use
PyArg_ParseTuple()and
Py_BuildValue()formats which use
#:
es#,
et#,
s#,
u#,
y#,
z#,
U#and
Z#. See Parsing arguments and building values and the PEP 353.-40679: Fix a
_PyEval_EvalCode()crash if qualname argument is NULL.
bpo-40839: Calling
PyDict_GetItem()without GIL held had been allowed for historical reason. It is no longer allowed.
bpo-40826:
PyOS_InterruptOccurred()now fails with a fatal error if it is called with the GIL released.
bpo-40792: The result of
PyNumber_Index()now always has exact type
int. Previously, the result could have been an instance of a subclass of
int.
bpo-39573: Convert
Py_REFCNT()and
Py_SIZE()macros to static inline functions. They cannot be used as l-value anymore: use
Py_SET_REFCNT()and
Py_SET_SIZE()to set an object reference count and size. This change is backward incompatible on purpose, to prepare the C API for an opaque
PyObjectstructure.
bpo-40703: The PyType_FromSpec*() functions no longer overwrite the type’s “__module__” attribute if it is set via “Py_tp_members” or “Py_tp_getset”.
bpo-39583: Remove superfluous “extern C” declarations from
Include/cpython/*.h.
Python 3.9.0 beta 1¶
Release date: 2020-05-19
Security¶ ‘un overall ‘from _ ‘[’ ‘U’ ‘string’ to ‘specification’.
macOS¶
IDLE¶
bpo-27115: For ‘Go. | https://docs.python.org/3/whatsnew/changelog.html#id45 | CC-MAIN-2022-33 | refinedweb | 26,824 | 53.27 |
3.1 Think relational
FileMaker Pro 3.0 is a further improvement of the simple, flat database
concept of a table.
It supports "relational capabilities". What's this? If you knew FMPro
2.1, it's a kind of editable, bidirectional lookup.
A relation is a kind of static connection when a certain field of a
record of a database matches its counterpart somewhere else. Based on
this relation you may get the contents of other related fields to this
matching record.
The basic relation is from one field to another one, a one-to-one
relation. Example: a relation from a customer database to get related
data from an address database, based on the matching customer id.
You may have multiple records that share the same information - this is
a many-to-one relation. Here the concept of relations demonstrates its
major power: you change the information only once, and immediately it
becomes available for all other records that hold a relation to this
information. Example: A customer ordered multiple times. His address is
still the same.
Some definitions on database concepts (by demey@hgins.uia.ac.be (Hendrik
Demey)):
* A relationship: a "virtual" link between 2 different databases (based
on a link between 2 *identical* fields in these 2 databases), allowing
information from database 1 (the parent) to be displayed in database 2
(the child). The relationship is based on an exact match between two
fields in the parent and child database. The trigger field is also
called a "primary key". When a child database looks at information from
its parent, it will display this "primary key". Some databases are
constructed to display information from several "parents", in that case
all the "primary keys" are called "foreign keys", because they uniquely
identify information in other databases.
* A related field: Information in a related field exists only in another
(the parent) database, and not in the database in which this field is
being looked at (the child). Related fields are represented by their
name being prerended by a double colon (::related_field_name). If You
try to export all the info of a certain record to a tab delimited file,
starting from a database with one or more related fields, based on one
or more relationships, the info from the related field is not exported
to this text file, as it does not exist in this specific child database,
but only in its related parent.
Comment: you may include related records for export. This will include
EVERY matching record! Example:
Field 1, Related::Field 2 will export as
Key1,"The first related field"
,"Another related field, matching to Key1, too"
* A portal is a new kind of lay-out tool in FM3, by which You create a
"window" inside the child database enabling You to view the related
fields from a parent database. In a one to many relationship (e.g. a
database of a school, with the parent a list of all pupils, the class
they attend and their home address; the child is a database of all
classes. Selecting a specific class will give a view of all pupil
records attending this specific class), this portal will present a list
view of all related records, based on a specific relationship. A
specific portal can only be based on *only one* relationship. In a
datase, several relationships can be created to different (or the same,
even the same child) files, therefore, more than one different portals
can be created. If specifically enabled, it is possible to create new
records with new information (e.g. a new pupil entering a certain class)
in a portal, that will be posted into the parent database. Again, if
specifically enabled, records viewed through a portal can be deleted
from their parent, while being looked at from the child database.
* A lookup physically copies information from the parent database, again
based on a specific relationships (this is different in FM3 from earlies
versions!). Exporting a tab delimited text file from a record contains
also the info carried over from a related file through a lookup field.
Information in a lookup field is static. Once copied over from the
parent database, the information inside this lookupfield stays
unchanged, even if the content of the parent field in the parent databse
is changed in the meantime.. Existing contents will get overwritten.
* Pros and cons of related fields/portals versus lookup fields:
- Information in a portal or related fields is dynamicaly updated, each
time the information in the parent database is changed. Lookup fields
are static.
- Related databases are smaller than databases based on lookup fields.
- Related databases present consistent information.
- Lookups present static information.
Take a set of invoices and the tax amount (a percentage) based on a
related field. If You change this tax level, all invoices (included
older ones) will represent this new value, and all invoices (including
the older ones) will be recalculated. With a tax based on a lookup
field, the information in the older invoices remains unchanged, and
therefore correct. Only newly created invoices will be based on the new
tax level. (Insofar a relookup order is not being issue!!!)
- In a lookup field, an exact match is not necesssary; they are more
flexible regarding the match field to copy next higher or lower matching
values. In a relationship an exact match is an absolute necessity in
order to obtain related records. The dialog box of the lookup definition
contains 4 radio buttons, enabling the user to define an exact match,
copy an item lower or higher than, or put up a dialog box with a
* Types of relationships:
- One-to-one: only one record corresponds to a certain trigger.
Information based on a one-to-one relation can easily be entered in the
same database, in one record.
- One-to-many: one record in the parent corresponds with multiple
records in the child (or vice versa). This kind of information is
represented on the "layout" of an FM3 database by a related field (for a
many-to-one) or a portal (for a one-to-many).
- Many-to-many: several one-to-many relationships exist at the same
moment, and between the same groups.
3.1.1 Many to many relations (m:n)
There are multiple problems on defining many-to-many / m:n relations. FMP's solution is
not to support them directly. However, you may use them by mapping a m:n relation
manually down to m:1 and 1:n. For that purpose you may have to create a separate file.
Example: There's a nice learning example with multiple teachers and pupils. A teacher may
have different pupils, a pupil several teachers.
Teacher database M:N database Pupil database
Key, Teacher Name Teacher key, Pupil key Key, Name
T1, AAA T1, P1 P1, ZZZ
T2, BBB T1, P2 P2, ZZX
T3, CCC T2, P2 P3, ZZY
Now you may get every pupil taught by teacher AAA, or any teacher of pupil ZZX.
Workaround:
Relations within FileMaker Pro are based on indexed lines. A line is composed of all
characters up to the end of line (in fact it's an end of paragraph, entered by <return> or the
full, last line) with a maximum of 60 characters; from the 61st character and up is not
used. Only text fields should hold return symbols. You may use them e.g. for a one-to-may
key or a many-to-one key, and thus as well for a many-to-many key.
Example:
The teacher database may hold the record and fields
Teacher: T1, Pupils: "P1<return>P2"
This will relate to both pupils ZZZ (P1) and ZZX (P2)
Within the Pupil database you may use
Pupil: P1, Teachers: "T1<return>T2"
Now you may find from P1 all other pupils of his class of teacher T1.
3.2 What are portals?
Q: What are portals?
A: Imagine them as a window to look through at datas within another
database.
Actually, there are some limitations:
* In a portal, records are displayed in their order of creation only.
* Deleting portals should be done very carefully.
If you delete a record, and permit deletion of related records, you may
remove data that is still used for other records.
If you do not use deletions properly, you may delete by mistake actual
or related records.
A related record may contain more data than what you see within the
portal.
But here the Pros:
They are fast and flexible!
You may use them to navigate around quickly by the "Go to related
record" script command.
Additional note on sliding portals: From FMP 3.0v3 on fields must be
perfectly enclosed to slide properly.
3.2.1 Sorting Portal Records
Portals have no option to sort, but show the records in order of
creation.
There are various workarounds:
- For complete databases this will force a permanent, resorted order:
* sort the database in question in correct order,
* create a clone,
* import to the clone
- For small sets of records
1) Flag the records in the portal
2) Sort the records in the many file (contains the portal records)
3) Duplicate the sorted records (in creation order the duplicates are
already sorted)
4) Delete the flagged records
5) View the records in the one file through the portal
(reported by Kirk Bowman <bowman@ONRAMP.NET>)
Example from Ted Shapiro, NY:
----------
By the way, here's a not too horrible method for sorting the contents of
a portal, aka the SORTAL (tm):
- Many students have registered for one class.
- Each class has a unique ID#.
- In the CLASSES file there is a portal to view students in the related
file ROSTERS.
In CLASSES -- script: SORTAL Part 1
Freeze Window
Copy Class ID#
Perform script (External: ROSTERS "SORTAL Part 2")
Refresh Window
In ROSTERS -- script: SORTAL Part 2
Perform Script (Find & Flag Class ID)
Perform Script (Sort StudentLastName)
Perform Script (DupeLoop)
Perform Script (Find Flagged & Delete)
script: Find & Flag Class ID
Enter Find Mode
Paste (Select, "Class ID")
Perform Find
Replace (No Dialog, "Flag", "1")
script: Sort StudentLastName
Sort (Restore, no dialog)
script: DupeLoop
Go to Record/Request (First)
Loop
Duplicate Record/Request
Clear (Select, "Flag")
Go to Record/Request (Exit after last, Next)
End Loop
script: Find Flagged &
Perform Find (Restore) --- this is find Flag=1
Delete All Records (No Dialog)
----
Another solution is to go via a separate database. Example: database 1
holds field A as trigger for portal B. A script finds all matching
values in database 3 and sorts them properly. Then the script lets
import all relevant portal data to a special database 2 that only holds
e.g. the portal data. The portal then gets all data from this portal
database 2 to database 1.
3.3 Bug & Wish List
Send suggestions and bug reports to on their suggestion
page. "Suggestions & Bug reports"
"James Fortier" <jim40er@halcyon.com> maintains a list that may be
available on
3.4 Relational Examples
This section will describe unusual solutions for relations to
demonstrate the capabilities. Please forward your examples for
inclusion!
3.4.1 Self Joining list
In case you want to see a portal of records that match a valid search
criterion only:
"Now here's something else that's way cool about Self-joins. If you
want to generate aggregate data on only a subset of your database, you
can do so in the following manner:
1) Create a text field called, say, FoundSet.
2) Create a calculation field called, say, FoundSetIndex as a
concatenation of YourKeyValue (such as Customer ID, Client ID, or
whatever) & FoundSet. Make the result text.
3) Create a self-relation on FoundSetIndex, i.e., have the same file
point back to itself.
4) Define your aggregate function to be dependent on the related
(self-joined) field (this is important).
5) Find the records you want to work with
6) Go to the FoundSet field and replace the value in your current found
set with something like an "F". This makes only the current found set
records create the self-join.
7) Stand back and view in amazement the power of FMP3.
PS Don't forget to clear the value in the FoundSet field before you exit
the script."
(from Jim Burd <burdman@cl.k12.md.us>)
<value sensitive lists under construction, currently about 8
alternatives to verify and classify>
3.5 Globals
Globals are helpful im many ways.
They may hold variables, such as
- a predefined constant value that you use throughout your database
This may be e.g. a user-defined delimiter for phone numbers, a certain
key word, a signature, logo, warning etc.
- a variable value, such as the layout number, a buffer for some
calculation, replace, set field, copy or paste script step etc.
Globals are not as global as you might expect. When a database is shared
between multiple users, every user may modify the global value on his
own, although he may not be able to save this modified value.
Be warned that when you clone a database, the value of a global field
will be removed as well!
Global fields may be repeating fields. Thus you may use e.g. a
calculation or script to extract one of multiple choices for variables
or even pictures.
Global fields may not get indexed. This may look obvious, but results in
some drawbacks. A major one is visible for relations: They only may be
built on indexed values. But as soon as a calculation includes an
unindexed value, such as another unstored calculation or global field,
it may not get indexed any more.
BTW you get a warning when you build a relation on a global field
itself, but it still is possible. A suitable example is e.g. a dummy
relation (global field one to related field one, both contain the value
"1") to a shared database in order to use the same - maybe global -
information within different databases.
Any global field within another database may be accessed by any
relation, regardless how nonsensical or matching this relationship is.
"did you know you can still modify globals:
- even if the file is "locked" in the finder
- even if the file is on a locked disk/volume
- even if the access privileges are set to disallow edits
The only way to prevent mods are to set the access privileges for that
field to be read-only.
Interestingly, the first two attempts above allow changes which don't
get saved to disk, but the third does get saved - which could be a
"gotcha" if you assume otherwise."
(by Eric Scheid <ironclad@planet.net.au>)
[ Usenet FAQs | Web FAQs | Documents | RFC Index ] | http://www.faqs.org/faqs/databases/filemaker-pro/faq/section-3.html | CC-MAIN-2014-52 | refinedweb | 2,446 | 61.77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.