text stringlengths 20 1.01M | url stringlengths 14 1.25k | dump stringlengths 9 15 ⌀ | lang stringclasses 4
values | source stringclasses 4
values |
|---|---|---|---|---|
sopen()
Open a file for shared access
Synopsis:
#include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <share.h> int sopen( const char* filename, int oflag, int share, ... );
Arguments:
- filename
- The path name of the file that you want to open.
- oflag
- Flags that specify the status and access modes of the file. This argument is a combination of the following bits (defined in <fcntl.h>):
-_CREAT — create the file if it doesn't exist. This bit has no effect if the file already exists.
- O_TRUNC — truncate the file to contain no data if the file exists; this bit has no effect if the file doesn't exist.
- O_EXCL — open the file for exclusive access. If the file exists and you also specify O_CREAT, the open fails (that is, use O_EXCL to ensure that the file doesn't already exist).
- The shared access for the file. This is a combination of the following bits (defined in <share.h>):
- SH_COMPAT — set compatibility mode.
- SH_DENYRW — prevent read or write access to the file.
- SH_DENYWR — prevent write access to the file.
- SH_DENYRD — prevent read access to the file.
- SH_DENYNO — permit both read and write access to the file.
If you set O_CREAT in oflag, you must also specify the following argument:
- mode
- An object of type mode_t that specifies the access mode that you want to use for a newly created file. For more information, see Access permissions in the documentation for stat().
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:, ... );
Returns:
A descriptor for the file, or -1 if an error occurs while opening the file BUSY
- Sharing mode (share) was denied due to a conflicting open.
- EEXIST
- The O_CREAT and O_EXCL flags are set, and the named file exists.
- EISDIR
- The named file is a directory, and the oflag argument specifies write-only or read/write access.
- ELOOP
- Too many levels of symbolic links or prefixes.
- EMFILE
- No more descriptors available (too many open files).
- ENOENT
- Path or file not found.
- ENOSYS
- The sopen() function isn't implemented for the filesystem specified in path.
Examples:
; } | https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/s/sopen.html | CC-MAIN-2020-45 | en | refinedweb |
Details and simple examples of the python class
- 2020-05-27 06:12:42
- OfStack
python class,
class
1. Class is a data structure that can be used to create instances. (1 in general, the class encapsulates the data and the methods available for that data)
2. The Python class is a callable object, that is, a class object
3. Classes are usually defined at the top of a module so that class instances can be created anywhere in the source code file defined by the class.
4. Instance initializationinstance = ClassName(args....) Classes can be instantiated using two special methods, s = s = s = s = s = s = s = s = s = s = s = s = s.
base: a superclass is a collection of one or more parent classes for inheritance The body of a class can include: declaration statements, class member definitions, data properties, methods If the class does not have an inheritance relationship, base in parentheses is not providedbase: a superclass is a collection of one or more parent classes for inheritance The body of a class can include: declaration statements, class member definitions, data properties, methods If the class does not have an inheritance relationship, base in parentheses is not provided
class ClassName(base): 'class documentation string' # Class document string class suite # The class body
The class statement, like def, is executable code; The class is not created until the class statement is run Within the class statement, any assignment statement creates class attributes Each instance object inherits the class's properties and gets its own namespaceThe class statement, like def, is executable code; The class is not created until the class statement is run Within the class statement, any assignment statement creates class attributes Each instance object inherits the class's properties and gets its own namespace
class FirstClass(): spam = 30 # Class data attribute def display(self): # Class method print self.spam x = FirstClass() # Creating class instances x.display() # The method call >>> 30 dir(FirstClass) >>> ['__doc__', '__module__', 'display', 'spam']
Python class methods and calls
The properties that the instance (object) containsCallable property: method Data attributes
In OOP, instances are like records with "data," and classes are "programs" that process these recordsCalling a method through an instance is equivalent to calling a method of the class to which it belongs to handle the current instance. For example, in the previous code example, x.display () is automatically converted to FirstClass.display (x), which calls the class's methods to handle the instance x Therefore, each method in the class must have an self parameter, which implies the current instance Assigning an self property within a method produces each instance's own property Python states that no method is allowed to be called without an instance, which is the concept of 'binding' (binding) The assignment statement in the class statement creates class attributes, such as spam in the previous example Assigning self, a special parameter passed to a method in a class method, creates an instance property
Python constructor
When an instance is created, Python will automatically call the method of s 57en__ in the class, providing the attributes to the instance with the option of invisiblyThe method is called the constructor If no method is defined in the class, the instance will be created with a simple namespace. The first parameter of 1 must be self, and the self variable is used to refer to the instance bound by the method in the class instance method. Because an instance of a method is always passed as the first argument in any method call, self is selected to represent the instance. You must put self in the method declaration, but you can do it without using an instance (self). If self is not used in your method, consider creating a regular function, unless you have a specific reason for doing so. After all, your method code doesn't use an instance and doesn't associate its functionality with a class, which makes it look more like a regular function. In other object-oriented languages, self might be called this. S 70en __ cannot return any object Destructor: s 71en__ Constructors are necessary, and destructors can often be ignored (the Python interpreter will recycle itself)
class MyClass(): def __init__(self, name): self.name = name print 'My name is ' + self.name def __del__(self): print self.name + ' is dead.' i1 = MyClass('Shaw') >>> My name is Shaw del i1 >>> Shaw id dead.
classUse dir() or s 78en__ to view the properties of the class or instance S 79en__ : get the document string S 80en__ : get all the parent classes S 81en__ : the module in which the class is located S 82en__ : the name of the class to which the instance belongs
The variables available in the Python class methodsInstance variable: self. Variable name Local variables: variables created inside a method that can be used directly Static variables: variables defined in a class. Class name. Variable name Global variables: used directly
inheritance
Inheritance describes how properties of a base class are 'inherited' to a derived classA subclass can inherit any property of its base class, including data properties and methods A class that does not specify a base class has a base class called object by default Python allows multiple inheritance (you can inherit from multiple parent classes)
Thank you for reading, I hope to help you, thank you for your support of this site! | https://ofstack.com/python/21311/details-and-simple-examples-of-the-python-class.html | CC-MAIN-2020-45 | en | refinedweb |
Henan Tongwei Medical Equipment Co., LtdCall us : +86 − −19139704654 // Email us : [email protected]
Validation Guide Validation Guide for Pall Emflon PFR filter cartridges were found to meet the requirements of the USP for Class VI (121C) Plastics 5 Part II Studies on Removal Efficiency 1 Microbial Validation using Brevundimonas diminutaLiquid Challenge Tests 1 1 Introduction The FDA guidelines on Sterile Products Produced by Aseptic Processing (1987) state 'A sterilizing filter
Cartridges and filters for use with 5500 RU8500 and 7700 Series half masks as well as 5400 RU6500 and 7600 Series full facepieces Combination filter cartridges feature a low profile with curved top that will not catch on pipes or other objects Easy to perform user seal checks even on the gas and vapor cartridges
Standard Profile II Filter Elements Available in RF Series RMF Series and AB Series—Code 3 and Code 7 (1) Air flow used for these data was 20 cfm/10″module except grade 700 which was run at 4 cfm (2) Pressure drop is PSI per GPM for a single 10″module For multiple elements divide by number of modules For fluids other than water multiply by viscosity in centipoise (3) For
Filter Cartridges for Ink Jet Ink Formulation IJ 1769b The Profile Star ink jet filter is an all-polypropylene pleated depth filter that combines the exceptional dirt-holding capacity of the Profile II medium with the high flow rates of the HDC II pleated medium While the Profile Star filter has a pressure drop and flow capability that are comparable to many competitive pleated
Pall R1F900 Profile II Filter Cartridge Condition: New $39 90 FAST 'N FREE Est Delivery Mon Jun 15 30-day returns Ships from United States Buy It Now Quantity : Buy It Now Add to cart Ships from Danville Kentucky Shipping Returns and Payments Details See details Returns Accepted within 30 days Buyer pays return shipping Shipping Returns and Payments Details See details
Proflow II-E-SELECT filter cartridges provide a chemically resistant exceptional flow rate and on-stream life with an economical PTFE membrane Parker Fluoroflow-HSA Cartridge Increased performance all-fluoropolymer cartridge for aggressive applications Industrial Filtration Systems for Fluids Oils Solvents Valin filtration systems use the latest technology to support applications
Poly Fine II Filter Cartridges Profile A/S 1401 Filter Elements Varafine VFSE Filters Varafine VFSG Filter Cartridges Varafine VFTR Filter Cartridges Water-Fine Filter Cartridges Zefluor Elements with Gore Tube Filters Membralox ceramique elements Membralox SD ceramique elements Coralon Food and Beverage Emflon PFRW Filter Cartridges Fuente
MSA Safety 815369 P100 Particulate Filter Respirator Cartridge Advantage Chemical and Combination Low-Profile Cartridge P100 Filter Type Crafted for easy installation and strong protection Advantage Respirator Cartridges use a bayonet-style design for easy mounting With low-lug height and lead-in connectors the cartridges lock into place with only a single twist The 815369 P100 Cartridge
Filterite Claris Filters Coreless Filter Elements Profile II Filter Elements Profile A/S Series Filter Elements Bag Filters Housings Felt Filter Bags Standard Felter Filter Bags PolyWeild Filter Bags Extended Life Filter Bags Heavy Duty Extended Life Filter Bags PolyFold Filter Bags Polymicro Microfiber Filter Bags Polymicro Microfiber Filter Bags Seamless Absolute-Rated BOS Filter Bags
High Rate Sand Filters For residential inground or aboveground swimming pools requiring turnover through 59 000 gallons Permanent media high rate sand filters in multiple diameter models accommodate large and small pools offering the best combination of economy performance durability and ease of maintenance The Profile II filter cartridges provide a removal efficiency of 99 98% in compatible
Pre-filter cartridges - for coarse filtration Millipore Polygard Beviguard filter cartridges - for fine colloidal haze removal from beverage products Vitipore II PVDF membrane filters - for cold sterile filtration prior to packaging (Pleated pre-filter with glass fibre/filter aid/polypropylene composite filter media)
Profile II Filter Cartridges RF Style "W" Code Cartridge Part Number R F W This is a guide to the part numbering structure only For specific options please contact Pall Table 1 : Nominal Length Table 2 : Removal Rating 05 1 2 Profile II RF style filter cartridges are comprised of a polypropylene filter medium cylindrical sleeve formed by a proprietary Pall process with a polypropylene
Filters Cartridges Escape Respirators Mask Accessories Lightweight low-profile Flexi-Filter Pads make it easy for wearers to work for hours without fatigue or overheating The swept-back design increases user field of vision while low-breathing resistance ensures hours of comfort Convenient finger tabs ensure easy installation and removal view details compare Advantage Chemical
This Pack comes with 2 Type - IV/B filter cartridges and 1 filter pump This Pack efficiently works at removing dirt and debris from your pool and keeps it spectacularly clean Made for a long-term durable use and featuring a simple design this cartridge is remarkably easy to install clean and replace Additionally it is compatible with 2100 GPH and 2500 GPH filter pumps The included
Prelude Filter Cartridges Pall Water's Prelude™-Fine Filter Cartridges Zefluor Elements with Gore Tube Filters Membralox ceramique elements Membralox SD ceramique elements Coralon Produtos alimentares e bebidas Emflon PFRW Filter Cartridges Fuente Colloids Filter Cartridges Ultipor N66 Filter Cartridges PREcart PP II Filter Cartridges SUPRApak SW Series Modules Profile Star Filter
PALL Profile II Filter Cartridge Part No RM3F050H21 PALL Profile II Filter Cartridge Part No RM3F050H21 Manufacturer: Pall Corporation Model: Not Specified Condition: Used See More Information Seller InformationCentral Mass Lab Recyclers United States Phone Number Login / Register Contact Central Mass Lab Recyclers Phone 978-503-4681 United States Price In Stock
Profile II Nylon Filters — for applications where polypropylene Profile II filters are chemically or physically incompatible such as for the filtration of hot vegetable and mineral oils and aromatic solvents Profile II Plus Filters — these all-polypropylene filters have a positive charge to provide enhanced removal efficiency for small
Profile II Filter Cartridges For Clarification and Particle Removal Data Sheet FBPROIIWENa Profile II filter cartridges are high efficiency depth filters designed for superior clarification and particle removal in food and beverage applications Description Constructed of melt blown polypropylene media Profile II cartridges feature a fixed fiber matrix with graded pore structure created by
Profile
disposable polythene aprons
surgical facial mask making machinery equipment 3 ply
high efficiency full auto air filter mask making
china disposable aluminum foil cooler insulation bag epe
how to minimize coronavirus exposure while traveling
impact of covid-19 on n99 respirator market 2020
n95 mask machine automatic semi-automatic production
medical device recalls archives
a call on the fashion industry to help make ppe suits
combinaisons usage unique classic tyvek blanche
china ppe isolation hazmat protective suit
import data and price of pp nonwoven fabric
twin-med series grey twin wheel casters
china n95 face mask factory direct sale low price buy
non woven face mask suppliers exporters in
imdx receives iso certification
disposable non-skid shoe cover
difference between polypropylene and nylon
china disposable medical material healthy visit
pp non woven fabric grade c facemask in korea
product testing and ppe ce marking
china face mask melt blown fabric machine
a diy guide to making alternative face masks
polypropylne filtre cartouche | https://www.hulpbijhuis.nl/2015_08_06/1311.html | CC-MAIN-2020-45 | en | refinedweb |
In my last post, I discussed how to get predictions from Gaussian Processes in STAN quickly using the analytical solution. I was able to get it down to 3.8 seconds, which is pretty quick. But I can do better.
One of this issues you may or may not have noticed is, using the model wherein posterior predictions are generated quantities, your computer bogs down with anything over 1000 iterations (I know mine froze up). The issue here is that generated quantities saves all the variables into memory, including those large matrices \( \boldsymbol{K}_{obs}, \boldsymbol{K}_{obs}^{*}, \boldsymbol{K}^{*} \) . We can resolve this issue, and speed things up, using functions to calculate the predictive values while storing the matrices only as local variables within the function (they are not saved in memory).
One obvious solution is to not calculate them within STAN, but to do it externally. Python can do this relatively quickly with judicious use of numpy (whose linear algebra functions are all written in C and so very fast) and numba/just-in-time compilers. However, since STAN compiles everything into C++, and many of its linear algebra functions are optimized for speed, it makes sense to do it all in STAN. Fortunately, we can create our own functions within STAN to do this, which are then compiled and executed in C++. The code is as follows:
import numpy as np import matplotlib.pyplot as plt import pystan as pyst X = np.arange(-5, 6) Y_m = np.sin(X) Y = Y_m + np.random.normal(0, 0.5, len(Y_m)) X_pred = np.linspace(-5, 7, 100) gp_pred = """ functions{ // radial basis, or square exponential, function matrix rbf(int Nx, vector x, int Ny, vector y, real eta, real rho){ matrix[Nx,Ny] K; for(i in 1:Nx){ for(j in 1:Ny){ K[i,j] = eta*exp(-rho*pow(x[i]-y[j], 2)); } } return K; } // all of the posterior calculations are now done within this function vector post_pred_rng(real eta, real rho, real sn, int No, vector xo, int Np, vector xp, vector yobs){ matrix[No,No] Ko; matrix[Np,Np] Kp; matrix[No,Np] Kop; matrix[Np,No] Ko_inv_t; vector[Np] mu_p; matrix[Np,Np] Tau; matrix[Np,Np] L2; vector[Np] Yp; // note the use of matrix multiplication for the sn noise, to remove any for-loops Ko = rbf(No, xo, No, xo, eta, rho) + diag_matrix(rep_vector(1, No))*sn ; Kp = rbf(Np, xp, Np, xp, eta, rho) + diag_matrix(rep_vector(1, Np))*sn ; Kop = rbf(No, xo, Np, xp, eta, rho) ; Ko_inv_t = Kop' / Ko; mu_p = Ko_inv_t * yobs; Tau = Kp - Ko_inv_t * Kop; L2 = cholesky_decompose(Tau); Yp = mu_p + L2*rep_vector(normal_rng(0,1), Np); return Yp; } } data{ int<lower=1> N1; int<lower=1> N2; vector[N1] X; vector[N1] Y; vector[N2] Xp ; } transformed data{ vector[N1] mu; for(n in 1:N1) mu[n] = 0; } parameters{ real<lower=0> eta_sq; real<lower=0> inv_rho_sq; real<lower=0> sigma_sq; } transformed parameters{ real<lower=0> rho_sq; rho_sq = inv(inv_rho_sq); } model{ matrix[N1,N1] Sigma; matrix[N1,N1] L_S; // can actually use those functions here, too!! Sigma = rbf(N1, X, N1, X, eta_sq, rho_sq) + diag_matrix(rep_vector(1, N1))*sigma_sq; L_S = cholesky_decompose(Sigma); Y ~ multi_normal_cholesky(mu, L_S); eta_sq ~ cauchy(0,5); inv_rho_sq ~ cauchy(0,5); sigma_sq ~ cauchy(0, 5); } generated quantities{ vector[N2] Ypred; // this is where the magic happens. note that now we only store Ypred, // instead of all those extraneous matrices Ypred = post_pred_rng(eta_sq, rho_sq, sigma_sq, N1, X, N2, Xp, Y); } """ gp1 = pyst.StanModel(model_code=gp_pred) data1 = {'N1': len(X), 'X': X, 'Y': Y, 'Xp': X_pred, 'N2': len(X_pred)} fit_gp1 = gp1.sampling(data1, iter=1000)
There are a couple of tricks here. I used a diagonal matrix \(\boldsymbol{I}\sigma_n\) to remove a for-loop in calculating the noise variance. It has the added benefit of cleaning up the code (I find for-loops to be messy to read, I like things tidy). Second, by using functions, the generated quantities only stores the predictions, not all the extra matrices, freeing up tons of memory.
One other thing to note is that the prediction function ends with the suffix ‘_rng’. This is because it is a random number generator, drawing random observations from the posterior distribution. Using the ‘_rng’ suffix allows the function to access other ‘_rng’ functions, chiefly the normal_rng function which draws random normal deviates. That’s necessary for the cholesky trick to turn N(0,1) numbers into the posterior distribution (see the last post). However, normal_rng only returns ONE number, so you have to repeat it for however many observations you need, hence the rep_vector( ) wrapper.
This code is extremely fast. After compilation, it executes 4 chains, 1000 iterations in roughly 1 second (compared to just over three from the previous post). Further, since I no longer have memory issues, I can run more iterations. Whereas 5000 iterations froze my computer before, now it executes in 5 seconds. 10,000 iterations, previously unimaginable on my laptop, runs in 10 seconds.
Pretty great. | https://natelemoine.com/even-faster-gaussian-processes-in-stan/ | CC-MAIN-2020-45 | en | refinedweb |
dialog_event_get_login_remember_me()
Get the state of the login dialog's "Remember me" check box from a DIALOG_RESPONSE event.
Synopsis:
#include <bps/dialog.h>
BPS_API bool dialog_event_get_login_remember_me(bps_event_t *event)
Since:
BlackBerry 10.0.0
Arguments:
- event
The DIALOG_RESPONSE event to get the state of the "Remember me" check box from.
Library:libbps (For the qcc command, use the -l bps option to link against this library)
Description:
The dialog_event_get_login_remember_me() function gets the state of the "Remember me" check box when the login dialog is dismissed by the user such as when the user presses a button on the login dialog.
Returns:
true if the "Remember me" check box is checked; false if the "Remember me" check box is not checked.
Last modified: 2014-05-14
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.bps.lib_ref/topic/dialog_event_get_login_remember_me.html | CC-MAIN-2020-45 | en | refinedweb |
write, );
Interfaces documented on this reference page conform to
industry standards as follows:
write(), writev(): XSH4.0, XSH4.2, XSH5.0, XNS5.0
pwrite(): POSIX.1, XSH5.0
Unless otherwise stated, when text is tagged with an indicator
for a particular revision of a standard, the information
applies when the application is built in a compilation
environment that adheres to the specified and higher
revisions of that standard.; Specifies the number
of iovec structures pointed to by the iov
parameter.NS5.0] If filedes refers to a socket, a write() request
is equivalent to a send() request with no options options is set and
the filedes parameter refers to a regular file, a successful
write() or pwrite() call does not return until the
data is delivered to the underlying hardware, as described
in open(2).
With devices incapable of seeking, writing always takes
place starting at the current position. The value of a
file pointer associated with such a device is undefined.
If the O_APPEND flag of the file status options is set,
the file offset is set to the end of the file prior to
each write, and no intervening file modification operation
occurs between changing the file offset and the write
operation.
If a write() or pwrite() requests that more bytes be written
than there is space for (for example, the ulimit() or
the physical end of a medium), only as many bytes as there
is space for are written. For example, suppose there is
space for 20 bytes more in a file before reaching a limit.
A write of 512 bytes returns 20. The next write of a
nonzero number of bytes will give a failure return (except
as noted below) and [XSH4.2]() call.
[Tru64 UNIX] This also applies whether or not
O_NDELAY is set. If O_NONBLOCK is clear, a write()
or pwrite() request to a full pipe causes the process
to block until enough space becomes available
to handle the entire request.
[Tru64 UNIX] This also applies if O_NDELAY is
clear. If the O_NONBLOCK flag is set, write() or
pwrite() requests are handled differently in the
following ways: the function does block the process;
requests for PIPE_BUF or fewer bytes either
succeed completely and return nbytes, or return -1
and set errno to [EAGAIN]. A request for greater
than PIPE_BUF bytes either transfers as much as it
can and returns the number of bytes written, or
transfers no data and returns -1 with errno set to
[EAGAIN]. Also, if a request is greater than
PIPE_BUF bytes and all data previously written to
the pipe has been read, write() or pwrite() transfers
at least PIPE_BUF bytes.
[Tru64 UNIX] This also applies if O_NDELAY.
[Tru64 UNIX] This also applies if O_NDELAY is
clear. If O_NONBLOCK is set, the function does not
block the process. Instead, if some data can be
written without blocking the process, it writes as
much as it can and returns the number of bytes
written. Otherwise, it returns -1 and errno is set
to [EAGAIN].
[Tru64 UNIX] This also applies if O_NDELAY is set,
except 0 (zero) is returned.
[Tru64 UNIX] of the
blocking locks are removed or until the function is terminated
by a signal. If O_NDELAY or O_NONBLOCK is set, the
function returns --1 and sets errno to [EAGAIN].
Upon successful completion, the write() or pwrite() function
marks the st_ctime and st_mtime fields of the file
for update and, if the file is a regular file, clears its
set-user ID and set-group ID attributes.
The fcntl(2) reference page provides more information
about record locks.
Writing Data to STREAMS Files [Toc] [Back]
[XSH4.2] For STREAMS files, the operation of write() and
pwrite() is determined by the values of the minimum and
maximum nbytes range ("packet size" accepted by the
STREAM). These values are contained in the topmost STREAM
module. Unless the user pushes the topmost module, these
values cannot be set or tested from user level (see I_PUSH
on the streamio(7)) reference page). If nbytes falls
within the packet size range, nbytes bytes are written. If
nbytes does not fall within the range and the minimum
packet size value is 0 (zero), write() or pwrite() breaks
the buffer into maximum packet size segments prior to
sending the data downstream (the last segment may contain
less than the maximum packet size). If nbytes does not
fall within the range and the minimum value is nonzero,
write() or pwrite() fails with errno set to [ERANGE].
Writing a zero-length buffer (nbytes is 0) sends 0 bytes
with 0 returned. However, writing a zero-length buffer to
a STREAMS-based pipe or FIFO sends no message and 0 is
returned. The process may issue the I_SWROPT ioctl()
request to enable zero-length messages to be sent across
the pipe or FIFO.
[XSH4.2] (that is, the
STREAM write queue is full due to internal flow control
conditions), the function blocks until data can be
accepted.
[Tru64 UNIX] This also applies if O_NDELAY is
clear. If O_NONBLOCK is set and the STREAM cannot
accept data, the function returns -1 and sets errno
to [EAGAIN].
[Tru64 UNIX] This also applies if O_NDELAY is set.
If O_NONBLOCK is set and part of the buffer has
been written when a condition occurs in which the
STREAM cannot accept additional data, the function
terminates and returns the number of bytes written.
[Tru64 UNIX] This also applies if O_NDELAY is set.
[XSH4.2] In addition, write(), pwrite(), and writev()
will fail if the STREAM head had processed an asynchronous
error before the call. In this case, the value of errno
does not reflect the result of write(), pwrite(), or
writev(), but reflects the prior error.
[Tru64 UNIX] For compatibility with earlier releases,
values for iov_len that are greater than or equal to 2^63
will be treated as zero.
[Tru64 UNIX] The write(), pwrite(), and writev() functions,
which suspend the calling process until the request
is completed, are redefined so that only the calling
thread is suspended.
[Tru64 UNIX] When debugging a module that includes the
writev() function, use _Ewritev to refer to the writev()
call. in which both read() and
write() either restarted the transfer or set errno to
[EINTR], depending on the setting of the SA_RESTART option
for the interrupting signal.
As a result of this change, applications must now either
handle the [EINTR] error or block any expected signals for
the duration of the read(), pread(), write(), or pwrite()
operation.
Upon successful completion, the write() or pwrite() function
returns the number of bytes actually written to the
file associated with the filedes parameter. This number is
never.
End-of-Media Handling for Tapes [Toc] [Back]
If writing goes beyond the "early warning" EOT indicator
while this indicator is disabled, the write(), pwrite(),
and writev() functions will return the number of bytes
actually written. The write(), pwrite(), and writev()
functions return a value of -1, if: Attempting to write
past the "real" EOT. Attempting to write past "early
warning" EOT indicator while this indicator is enabled.
Refer to mtio(7) for information on enabling and disabling
"early warning" EOT.
End-of-Media Handling for Disks [Toc] [Back]
Disk end-of-media handling is POSIX-compliant. Attempting
to write at or beyond the end of a partition returns a
value of -1. A partial write returns the number of bytes
actually written.
Note: A partial write is a request that spans the end of a
partition.
The write(), pwrite(), and writev() functions set errno to
the specified values for the following conditions: The
O_NONBLOCK flag is set on this file and the process would
be delayed in the write operation.
[Tru64 UNIX] An attempt was made to write to a
STREAM that cannot accept data with either the
O_NDELAY or O_NONBLOCK flag set.
[Tru64 UNIX] An enforcement mode record lock is
outstanding in the portion of the file that is to
be written. The filedes parameter does not specify
a valid file descriptor that is open for writing.
[Tru64 UNIX] Enforced record locking is enabled,
O_NDELAY is clear, and a deadlock condition is
detected. [Tru64 UNIX] The write failed because
the user's disk block quota is exhausted. [Tru64
UNIX] The buffer parameter or part of the iov
parameter points to a location outside the allocated
address space of the process. An attempt was
made to write a file that exceeds the maximum file
size. A write() or pwrite() on a pipe is interrupted
by a signal and no bytes have been transferred
through the pipe. [XSH4.2] The STREAM or
multiplexer referenced by filedes is linked
(directly or indirectly) downstream from a multiplexer.
[XSH4.2] The iov_count parameter value was less
than or equal to 0 or greater than IOV_MAX.
[XSH4.2] The sum of the iov_len values in the iov
array would overflow an ssize_t buffer.
[Tru64 UNIX] The file position pointer associated
with the filedes parameter was negative.
[Tru64 UNIX] One of the iov_len values in the iov
array was negative or the sum overflowed a 32-bit
integer. [XSH4.2] A physical I/O error occurred.
These errors do not always occur with the associated
function, but can occur with the subsequent
function. [Tru64 UNIX] The file has enforcement
mode file locking set, and allocating another
locked region would exceed the configurable system
limit of NLOCK_RECORD. [XSH4.2] No free space is
left on the file system containing the file.
[Tru64 UNIX] An attempt was made to write past the
"early warning" EOT while this indicator was
enabled.
[Tru64 UNIX] An attempt was made to write at or
beyond the end of a partition. [XSH4.2] A hangup
occurred on the STREAM being written to.
The device associated with file descriptor (the
filedes parameter) is a block special device or
character special file, and the file pointer is out
of range. [Tru64 UNIX] An attempt was made to
write to a socket or type SOCK_STREAM that is not
connected to a peer socket. [XSH4.2] An attempt
was made to write to a pipe that has only one end
open.
An attempt was made to write to a pipe or FIFO that
is not opened for reading by any process. A SIGPIPE
signal is sent to the process. [XSH4.2] The
transfer request size was outside the range supported
by the STREAMS file associated with filedes.
In addition, the pwrite() function fails and the file
pointer remains unchanged if the following is true: The
file specified by fildes is associated with a pipe or
FIFO.
[XSH4.2]: [Tru64 UNIX] For filesystems mounted with
the nfsv2 option, the process attempted to write beyond
the 2 gigabyte boundary. [Tru64 UNIX] The named file is
a directory and write access is requested. [Tru64 UNIX]
Insufficient resources, such as buffers, are available to
complete the call. Typically, a call used with sockets
has failed due to a shortage of message or send/receive
buffer space. [Tru64 UNIX] The named file resides on a
read-only file system and write access is required.
[Tru64 UNIX] The NFS file handle is stale.: [Tru64 UNIX] A write to a pipe
(FIFO) of PIPE_BUF bytes or less is requested, O_NONBLOCK
is set, and less than nbytes bytes of free space is available.
[Tru64 UNIX] Enforced record locking was enabled,
O_NDELAY or O_NONBLOCK was set and there were
record-locks on the file, or O_NONBLOCK was set,
and data cannot be accepted immediately. [Tru64
UNIX] The sum of the iov_len values in the iov
array overflowed an integer. [Tru64 UNIX]
Attempts to write to a STREAM with nbytes are outside
the specified minimum and maximum range, and
the minimum value is non-zero.
Functions: fcntl(2), getmsg(2), lseek(2), open(2),
pipe(2), poll(2), select(2), lockf(3), ulimit(3)
Files: mtio(7)
Standards: standards(5)
write(2) | https://nixdoc.net/man-pages/Tru64/man2/write.2.html | CC-MAIN-2020-45 | en | refinedweb |
Imposter syndrome: how to display: front-end;
p{margin-bottom:30px!important;} The odds were stacked against me. First off, I was born female (albeit a situation I am pleased with, it’s not the wisest career choice in the grand scheme of…
January 15, 2020
Ever since the release of ECMAScript 6 in 2015 the language has been constantly evolving and maturing. New features are being proposed and developed regularly. Proposed features go through 4 stages:
proposal,
draft,
candidate and
finished. Finished proposals are added to the language in an annual update. In 2020 new exciting features will be available for us to use in our projects. If you are a web developer, here’s a list of 4 features you should look forward to start using.
The Nullish Coalescing Operator, written with double question marks
??, is a logical operator that returns its right handed operand if the outcome of the left handed operand is
null or
undefined. You might think, don’t we already have an operator that does this called the “or” operator?
Where the or operator, written with double lines
||, is different is that it returns the right handed operand if the left handed operand is false. This a very important distinction.
Look at the following lines:
undefined || 'default' null || 'default' false || 'default' ‘’ || 'default' 0 || 'default'
All of these return the string default. This could cause problems if we only wanted to return default if the outcome was null or undefined. Before the nullish coalescing operator there was a way to do this, but it required more type checking and more writing. Using the nullish coalescing operator allows you to better predict the outcome and avoid unwanted behaviour.
a ?? 'default' a !== undefined && a !== null ? a : 'default'
These 2 lines do the exact same. The first line is more readable and less prone to unwanted behaviour due to less type checking. The Nullish coalescing operator is perfect for adding a default value if you are unsure if a variable is defined or has a value.
With the optional chaining operator you are able to check deep nested properties without having to worry about it all being valid. Before this feature, in order to check deep nested properties it required you to validate the steps in between. Consider the following object:
let company = { employees: { john: { age: 28 } } }
In order to access the age of nested object
john before Optional Chaining you would have to write out each step like this:
company && company.employees && company.employees.john && company.employees.john.age
As you might expect this would get out of hand pretty fast if you had to access deeper nested items. With the new syntax all you need to do is add a
? before each property. With the new syntax the same line of code would look like this
company?.employees?.john?.age
Currently if we try to access a property that is not found it gives back undefined. However, if we combine optional chaining with the nullish coalescing operator, that we talked about previously, we can create a default value. Imagine we’d like to know how many hours a week John works, and the default in his company is 40, we could write something like this:
company?.employees?.john?.workhours ?? 40
It checks if the object
john has a value called workhours. If it’s not found it returns the default value 40.
If you’re a web developer that works in a team, or on large projects, there’s a good chance you work with imports a lot. They have been around since 2015, when javascript received one of the biggest updates to the language. Although imports are very handy, they do have some limits.
5 years later we can look forward to a new addition to the way we use imports, dynamic imports. Dynamic imports solve the limitations we previously faced. Their syntax is a bit different and they work within modules.
The way we currently use imports looks like this. These should look familiar, they can always be found at the top of a file.
import defaultExport from "module-name"; import * as name from "module-name"; import { exportable } from "module-name";
The new dynamic import looks like a function expression. It loads the module and returns a promise that resolves into a module object that contains all its exports. It can be declared and called from any place in the code.
Here’s an example of a module being specified and called
const moduleSpecifier = "./module.js"; import(moduleSpecifier).then(module => module.foo());
It’s also possible to use
const module = await import(modulePath) if inside an async function. The syntax for importing and using would look like this
let { func1, func2 } = await import("./modules.js"); func1(); func2();
Dynamic imports will give us more control over when and where we want to import our modules. It will help us keep a better overview and improve overall performance of our applications and websites.
In 2020 we will most likely see the coming of new static features to javascript classes. A static method is a method you define on a class but is not part of the instantiated object that is created. It does not require an instance of the class to be created in order to use it. 3 new changes we can expect are
Public fields are useful when you want a field to exist only once per class and not on every class instance you create. Static public fields are declared with the static keyword.
class Example { static staticClassProperty = "I’m a string"; } console.log(Example.staticClass) //output of this is “I’m a string”
When initializing fields, using
this refers to the class under construction. In this case using
this would always refer to
example.
class Example { static staticField = "I’m a string"; static subField = this.staticField + " subfield"; } console.log(Example.subField) //output of this is "I’m a string subfield”
But what if we have a subclass and we would like to access the static field “subfield”?. For that we can use super to access the so called superclass. Let’s take a look at how this works.
class Example { static staticField = "I’m a string"; static subField = this.staticField + " subfield"; } class ExampleExtend extends Example { static extendedField = super.subField; } console.log(ExampleExtend.extendedField) //output of this is "I’m a string"
In this case our superclass is
example. Inside our subclass “exampleExtend” we can call the super method to reference to our superclass and use its static fields. But what if we didn’t want anything from the outside to be able to access the static fields? For this we have private fields.
In almost all ways static private fields are the same as static public fields. They are however only accessible from inside the class itself.
To make a field a private field you simply just have to at a # in front of the name. If we use our previous example and would want to make the first static class private, because do not want to be able to reach it from outside our class, we could simple add a # in front of the class.
class Example { static #staticField = "I’m a string"; static subField = this.#staticField + " subfield"; } console.log(Example.subField) // outputs "I’m a string subfield"
Making class fields private ensures stronger encapsulation and prevents later hiccups by depending on internal fields, as the structure may change in different versions.
Note: you are not able to access
example.#staticField outside of example. It will give you an error.
The same way static public fields and static private fields are very alike, static private methods and static public methods are a lot alike. As you would expect from the previous, the main difference is that you can’t access the static private method from outside the
class.
class Msg { static staticField = this.#privateMethod() static #privateMethod() { return "I’m a private method!" } } console.log(Msg.staticField) //outputs "I’m a private method!"
The features ES2020 will provide us with will make our life as web developers easier. It will provide us with more structure and improve the quality of our code. They will help us avoid unexpected behaviours and it will improve the readability of our code. | https://www.sentiatechblog.com/es2020-features-for-web-developers | CC-MAIN-2020-45 | en | refinedweb |
Level of Detail¶
Using multiple levels of detail for a part of your scene can help improve performance. For example you could use LOD to simplify an Actor that is far away, saving on costly vertex skinning operations. Another use would be to combine several small objects into a simplified single object, or to apply a cheaper shader. LOD can also be used to hide objects when they are far away.
Include file:
#include "lodNode.h"
To create an
LODNode and
NodePath:
PT(LODNode) lod = new LODNode("my LOD node"); NodePath lod_np (lod); lod_np.reparent_to(render);
To add a level of detail to the LODNode:
lod->add_switch(50.0, 0.0); my_model.reparent_to LOD. | https://docs.panda3d.org/1.10/cpp/programming/models-and-actors/level-of-detail | CC-MAIN-2020-45 | en | refinedweb |
With the release of ES6 and later versions of JavaScript, there were lots of methods released with it, expanding the functionality of the language. For example, there are new array and string methods, as well as useful operators like the spread and rest operators.
However, JavaScript still doesn’t make utility libraries like Lodash obsolete because there are lots of useful methods that still aren’t available in JavaScript.
In this article, we’ll look at a few methods from Lodash that still makes development easier than with plain JavaScript, including the
times,
get,
set,
debounce,
deburr, and
keyBy methods.
_.times
The
times method lets us call a function multiple times, put all the retuned results of each function call into an array, and return it.
It takes 2 arguments, which are the number of times that the function is called and the second is the function to call.
For example, we can use it as follows:
import * as _ from "lodash"; const getRandomInteger = () => Math.round(Math.random() * 100); let result = _.times(5, getRandomInteger); console.log(result);
Then we may get the following result:
[16, 83, 35, 87, 41]
_.debounce
We can use the
debounce method to delay a call of a function by a specified amount of time. There’s no easy way to do this with JavaScript.
This is useful for event handling where we want to wait for something to be done and then call a function. For example, with a typeahead search, a debounce would wait until the user is finished typing before making the API call, removing unnecessary hits on your server.
For example, we can use it as follows. Given the following number input:
<input type="number" />
We can write the following JavaScript code:
import * as _ from "lodash"; const checkPositiveNumber = e => { console.log(+e.target.value > 0); }; const numInput = document.querySelector("input[type=number]"); numInput.addEventListener("input", _.debounce(checkPositiveNumber, 600));
The code above has the
checkPositiveNumber function that checks if the value entered is positive. Then we use the
debounce method, which takes the function and the delay before calling it in milliseconds.
The function returned by
debouce has the same parameters and content as the original function, except that it’s delayed by the given number of milliseconds before calling it.
_.get
The
get method lets us access the properties of an object in a safe way. That is, even if the path to the properties doesn’t exist, it will return
undefined or a default value instead of crashing the program.
For example, given the following object:
const obj = { foo: { bar: { baz: { a: 3 } }, foo: { b: 2 }, baz: [1, 2, 3] } };
We can access
obj‘s property as follows:
const result = _.get(obj, "foo.bar.baz.a", 1);
The first argument is the object we want to access a property’s value. The second is the path to the property. The last argument is the default value.
We should get 3 for
result.
On the other hand, if the path doesn’t exist or it’s
undefined, then we get
undefined or a default value returned.
For example, if we have:
const result = _.get(obj, "foo.bar.a", 1);
Then we get 1 for
result.
If we don’t specify a default value as follows:
const result = _.get(obj, "foo.bar.a");
Then we get
undefined.
There’s no way to safely get the value of a deeply nested property until the optional chaining operator becomes mainstream.
_.set
There’s also a
set method to assign a value to a property of an object. For example, given the same object we had before:
const obj = { foo: { bar: { baz: { a: 3 } }, foo: { b: 2 }, baz: [1, 2, 3] } };
We can set a value to a property by writing:
_.set(obj, "foo.bar.a", 1);
The
obj object is changed in place. As we can see, it can set values for properties that don’t exist yet. The original object didn’t have
foo.bar.a and it added it automatically set the value to 1.
So we get:
{ "foo": { "bar": { "baz": { "a": 3 }, "a": 1 }, "foo": { "b": 2 }, "baz": [ 1, 2, 3 ] } }
It even works if the nested object doesn’t exist, so if we write:
_.set(obj, "foo.foofoo.bar.a.b", 1);
We get:
{ "foo": { "bar": { "baz": { "a": 3 } }, "foo": { "b": 2 }, "baz": [ 1, 2, 3 ], "foofoo": { "bar": { "a": { "b": 1 } } } } }
_.deburr
To remove accents from characters with strings, we can use the
deburr method. It takes in a string and returns a new string with the characters that have accents replaced with the ones that don’t have them.
For example, if we have
“S’il vous plaît”:
const result = _.deburr("S'il vous plaît");
Then we get that
result is
"S’il vous plait" . The ‘i’ no longer has the accent.
_.keyBy
The
keyBy method takes an array and the property name and returns an object with the value of the property as the keys of the object.
For example, if we have the following array:
const people = [ { name: "Joe", age: 20 }, { name: "Jane", age: 18 }, { name: "Mary", age: 20 } ];
Then we can use
keyBy as follows:
const results = _.keyBy(people, "name");
Then
results would have the following:
{ "Joe": { "name": "Joe", "age": 20 }, "Jane": { "name": "Jane", "age": 18 }, "Mary": { "name": "Mary", "age": 20 } }
Then we get the object with name
'Joe' by writing:
results['Joe']
There’s no way to do this easily with plain JavaScript without writing multiple lines of code.
Conclusion
Lodash has many useful functions that don’t have an equivalent that are as easy to use as these methods.
There’s the
times method to call a function multiple times in one line. The
debounce function returns a new function with the same signature and code as the original but it’s delayed by the given amount of milliseconds before it’s called.
For accessing and setting object properties and values safely, there are the
get and
set methods that don’t crash when we access property paths that don’t exist or has value
undefined.
Then there’s the
deburr method to replace accented characters with the non-accented versions of these characters.
Finally, there’s
keyBy method to get massage an array into an object that has the given property’s value of each entry as the keys and the entry with the given property’s name’s values as the value of those keys. | https://thewebdev.info/2019/09/ | CC-MAIN-2020-45 | en | refinedweb |
Updated on augustus 11, 2020·
Create a React Chat-app with Firebase, React Router & Authentication (part 2)
This post will continue to finish the actual chat-part on top of our previous React Firebase setup from part 1. I apologize to anyone who was waiting a long time for the sequel of this post. But it’s finally here!
Our firebase chat app will use the real-time database from Firebase and not the Cloud Firestore. Why? Because the real-time database updates our app automatically for us, so we don’t need to do anything special to make it work!
You can find a working example of our app on chat.weichie.com and you can find the complete project on Github as well.
Where did we left our React Chat application after part 1?
I created this app more than 2 years ago and in the meantime over 1000 people registered to test the chat app! Apologies to everyone who was waiting on part 2, but a recent comment on the Part 1 article made me realize that my blog has more traffic than I thought.
So here we go! Feel free to refresh my mind in the comments if I am talking nonsense in this post. I am no longer using React for my applications but switched it for Vuejs instead.
Using authentication in our Router
Only registered users will be able to post chat-messages in our application. Otherwise… We don’t know who said something. To make sure users are logged in, we’ll change our Router component like this:
// index.js ... <Router> <div className="app"> <nav className="main-nav"> {!this.state.user && <div> <Link to="/login">Login</Link> <Link to="/register">Register</Link> </div> } {this.state.user && <a href="#!" onClick={this.logOutUser}>Logout</a> } </nav> <Switch> <Route path="/" exact render={() => <Home user={this.state.user}/>} /> <Route path="/login" exact component={Login} /> <Route path="/register" exact component={Register} /> <Route component={NoMatch} /> </Switch> </div> </Router> ...
We changed a few things in our index.js-file to check authenticated users. Let’s start with the navigation on top.
We create a navigation element main-nav with 2 navigation elements. One that will be displayed when our user is logged in, and another navigation that will be displayed when the user is logged out. So he can choose if he wants to log in with an existing account or register a new account (and talk with himself)
The other important thing we changed in our index.js file is that we swapped the
{home} component with a function, that renders our component in-line. This way we’re able to pass our logged in user as a prop to our home component.
The Home Component
Our Home component is the home screen of our application. This screen will show you the chat-app when you are logged in, or the option to create your account if you are logged out.
First the setup: Now that our router passes our user-state to our Home component, we can display authentication-based elements in this component as well. Let’s see what it looks like:
// Home.js import React from 'react'; import {Link} from 'react-router-dom'; <-- add this line class Home extends React.Component{ render(){ return( <div className="home--container"> <h1>Welcome to the chat!</h1> {this.props.user && <div className="allow-chat"> We insert our chat-component later </div> } {!this.props.user && <div className="disallow-chat"> <p><Link to="/login">Login</Link> or <Link to="/register">Register</Link> to start chatting!</p> </div> } </div> ); } } export default Home;
In our home render function, we added an if-statement to see whether or not our users are logged in. If so, we are allowed to show our chatbox. If not, we give them the option to log in or to create a new account.
Make sure to import
{Link} at the top of our Home.js file.
Chatbox.js – Where the magic happens
The most important file! Apologies again if some of you waited so long for me to finally finish up Part 2 as well… a sincere apology from my end!
So Let’s dive right in and create a Chatbox.js file inside our Home folder. To clarify, this is what our folder structure inside /src/ looks like:
- /components
- /Auth
- Auth.css
- Login.js
- Register.js
- Chatbox.js
- Home.css
- Home.js
- firebase.js
- index.css
- index.js
And then we’ll add the usual defaults for a new component:
import React from 'react'; class Chatbox extends React.Component{ render(){ return( <div className="chatbox"> <ul className='chat-list'> <li>Here we show our chat messages</li> </ul> </div> ); } } export default Chatbox;
Nothing too crazy in here yet. Just a simple component that, for now, will return a list with 1 static element. Next: Add firebase! We will create a component-state into Chatbox.js where we will insert all the messages that we’re pulling from firebase.
So what do we need? A constructor for our state that will store the firebase messages in our app. And a call to firebase to get all the messages in our application. This function will be run when our Chatbox component is mounted. Here’s the setup code:
// Chatbox.js ... class Chatbox extends React.Component{ constructor(props){ super(props); this.state = { chats: [] } } componentDidMount(){ console.log('Chatbox.js is mounted!'); } render(){ ... } }
We have a constructor with a state for our ‘chats’ and if we can see ‘Chatbox.js is mounted!’ in our console, we’re ready for the firebase integration.
The Firebase Realtime Database works with ‘refs’. Although it returns one huge JSON tree, refs will give us easy access to the data we need. Our chat app is still empty at the moment, so we need to add some test messages first before we can display our chat list.
Let’s add some messages! Back to our Home Component
To ease up development, it would also be nice if we could see our Chatbox component in our app. So let’s hook it up really quick:
// Home.js import React from 'react'; ... import Chatbox from './Chatbox'; <-- Add this line ... // Update our render method: <h1>Welcome to the chat!</h1> {this.props.user && <div className="allow-chat"> <Chatbox /> </div> } ...
This adds the Chatbox component when our user is logged in so we can see what we’re doing. Let’s continue:
We can’t pull an empty list from Firebase. I mean… we can… but we won’t see anything. So head back to our Home.js component and we’ll write some logic to add messages to our database.
// Home.js import React from 'react'; import firebase from '../../firebase'; <-- Add this line import {Link} from 'react-router-dom'; class Home extends React.Component{ constructor(props){ super(props); this.state = { message: '' } } handleChange = e => { this.setState({[e.target.name]: e.target.value}); } render() { ... <div class="allow-chat"> <form className="send-chat" onSubmit={this.handleSubmit}> <input type="text" name="message" id="message" value={this.state.message} onChange={this.handleChange} </form> <Chatbox /> </div> ... } } export default Home;
What’s happening? We created a state in our Home component and added a form in our ‘send-chat’ div. In React/Vue/Angular/… you are not allowed to have unbound forms. So our input-field has an onChange method that will keep the value in our input field in sync with the input field value in our state.
I already made you import firebase at the top of our file and gave our chat-form the onSubmit function, because we’re continuing our send-message logic right away:
// Home.js ... handleSubmit = e => { e.preventDefault(); if(this.state.message !== ''){ const chatRef = firebase.database().ref('test'); const chat = { message: this.state.message, user: this.props.user.displayName, timestamp: new Date().getTime() } chatRef.push(chat); this.setState({message: ''}); } } ...
The handleSubmit function goes above our render() method. Like how we did the handleChange function. When submitting the form, we check if the message is empty. If so, we don’t do anything (otherwise people can push empty values to your database – talking from experience…)
If we have a value to push, we create a chatRef. This one will be a firebase database reference. Note that this can be anything we’d like. In my example I used ‘test’ as ref, create a chat message object and push it to our chatRef. Then we also update our state, so the message field get cleared once the message is submitted.
The ‘chat’ object we’re pushing to firebase looks like this:
- message: Our state.message, the message that the user wrote
- user: The username from the user. We passed our user as a prop to the Home component, so we can access it like this
- timestamp: A general javascript timestamp, to know when people are posting messages
When you hit submit, you should be able to see our ‘Test’ ref and our message in the Realtime database! Booyaa.
If the test is working, you can change the ref in the
const chatRef = firebase.database().ref('test'); line from ‘test’ to whatever you want. As you can see in the image, I’ll be using ‘general’ in this example. But this can be anything you want – and you can change it on the fly! (if you want to make different chatrooms or something like that)
Pulling our messages
All righty, now that we are able to push data to our firebase database, we’re ready to pull them back into our app as well. Back in Chatbox.js we’ll complete our componentDidMount() function to pull our firebase data when our chatbox is loaded.
// Chatbox.js import React from 'react'; import firebase from '../../firebase'; <-- Add this line class Chatbox extends React.Component{ ... componentDidMount(){ const chatRef = firebase.database().ref('general'); chatRef.on('value', snapshot => { const getChats = snapshot.val(); let ascChats = []; for(let chat in getChats){ ascChats.push({ id: chat, message: getChats[chat].message, user: getChats[chat].user, date: getChats[chat].timestamp }); } const chats = ascChats.reverse(); this.setState({chats}); }); } render(){ ... } } export default Chatbox;
Ok, sooo. On componentDidMount() we get the Chat reference we created previously in our Home component. Make sure to use the same reference as where you’re posting your messages to 😉
That’s actually all there is to do! If we have a chatRef, we take the snapshot and store it in a variable. The snapshot is 1 object, containing all our messages at once.
I want to display the latest messages at the top, so I’m looping over my getChats, and push the data we need into a helperArray called ‘ascChats’. The create a new variable and set it to the reverse version of the regular ascChats array. This way the latest messages are stored at the top. Don’t forget to push the end result to our state! So we can use it in our component.
For the reversing of the array to display the latest messages at the top… I’m pretty sure firebase will have a built-in function for this. But hey… Now we’ve done some javascript array cardio today as well 🙂
Finalize our Chatbox
Now that we have our messages in the state of our Chatbox, we can list them in our chatbox! Yaay.
Update the render method in Chatbox.js like this:
// Chatbox.js ... render(){ return( <div className="chatbox"> <ul className='chat-list'> {this.state.chats.map(chat => { const postDate = new Date(chat.date); return( <li key={chat.id}> <em>{postDate.getDate() + '/' + (postDate.getMonth()+1)}</em> <strong>{chat.user}:</strong> {chat.message} </li> ); })} </ul> </div> ); } ...
We loop over the chat messages in our state and display them in our “chat-list”. Pooof! Our chat app is alive, just like that!!
This should do the trick?! A fully functioning React Chat App linked to the Realtime Database in Firebase! Let me know if you got stuck somewhere or if something is not explained correctly. I’ll adjust my tutorial.
As I said before, I switched to using Vuejs instead of React. I’ll ad a link to a Vue-firebase setup as well in the related articles. Or, if you landed on this page and missed part 1 of the React Firebase setup, that one can be found as a related article as well.
Hope you enjoyed it and that my tutorial gave you some more insights!
Peace. | https://weichie.com/nl/blog/react-firebase-chat-app-part-2/ | CC-MAIN-2020-45 | en | refinedweb |
Doc. no.: N2207=07-0067
Date: 2007-03-09
Project: Programming Language C++
Subgroup: Library
Reply to: Matthew Austern <austern@google.com>
Unicode is an industry standard developed by the Unicode Consortium, with the
goal of encoding every character in every writing system. It is synchronized
with ISO 10646, which contains the same characters and the same character
codes, and for the purposes of this paper we may treat Unicode and ISO 10646
as synonymous. Many programming languages and platforms already support
Unicode, and many standards, such as XML, are defined in terms of Unicode.
There has already been some work to add Unicode support to ISO C++.
C++ has two character types, char and wchar_t. The standard does not specify which character set either type uses, except that each is a superset of the 95-character basic execution character set. In practice char is almost always an 8-bit type, typically used either for the ASCII character set or for some 256-character superset of ASCII (e.g. ISO-8859-1). Some programs use wchar_t for Unicode characters, but wchar_t varies enough from one platform to another that it is unsuitable for portable Unicode programming.
Unicode assigns “a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.” [6] These numbers are known as code points. A character encoding form specifies the way in which a sequence of code points is represented in an actual program. Code points range from 0x000000 through 0x10ffff, so 21 bits suffice to represent all Unicode characters. No popular architecture has a 21-bit word size, so instead most programs that work with Unicode use one of the following character encoding forms for internal processing:
UTF-32 uses a 32-bit word to store each character. This encoding is attractive because of its simplicity, unattractive because it wastes 11 bits per character.
UTF-16 is a variable width character encoding form where a code point is represented by either one or two 16-bit code units. The most common characters are represented as a single code unit, and the less common characters are represented as two code units, called surrogates. It is possible to tell, without having to examine context, whether a UTF-16 code unit is a leading surrogate, a trailing surrogate, or a complete character.
UTF-8 is a variable-width character encoding form where a code point is represented by one or more 8-bit code units.
Other character encoding forms are sometimes used for serialization or external storage.
Unicode support for ISO C is described in TR 19769:2004, a Type 2 technical report. TR 19769 proposes two new character types, char16_t and char32_t, together with new syntax for character and string literals of those types, and a few additions to the C library to manipulate strings of those types. Lawrence Crowl’s paper N2149, “New Character Types in C++,” proposes that WG21 adopt TR 19769 almost unchanged; essentially the only change from TR 19769 is that char16_t and char32_t are required to be distinct from other integer types, so that it’s possible to overload on them.
This paper describes changes to the standard library that will be needed if WG21 chooses to adopt N2149. It is a proposal for C++0x, because it proposes changes in existing standard library components.
The main goal of this paper is simple: make it possible to use library facilities in combination with the two new character types char16_t and char32_t. This paper does not attempt to define new library facilities or to fix defects in existing ones, but only to make it possible to use char16_t and char32_t with existing library facilities.
This goal is important despite the existence of wchar_t. Even if wchar_t is the same size as one of those two types, it is distinct from both from the point of view of the C++ type system. It would be very poor user experience if we told users that they had to cast their Unicode strings to some other type in order to use library facilities, especially since that type would vary from one system to another. (Internally, of course, I imagine most library implementers will choose to share code between char32_t and wchar_t or between char16_t and wchar_t.) It is indeed irritating to have three distinct types when two of them will almost always be identical, but, as with char, signed char, and unsigned char, history leaves us little choice.
Minimal support for char32_t is simple: UTF-32 is a fixed width encoding, so we just need to require specializations of library facilities for char32_t in the same way that we do for char and wchar_t. Arguably a basic_string of 32-bit characters isn't all that useful, but I think just enough people would use it to make it worth having.
Minimal support for char16_t is more complicated in theory, but equally simple in practice: again, just add specializations of all library facilities for char16_t. UTF-16 is not a fixed width encoding, but, for two reasons, it can almost be treated as one. First, most text is composed only of the common characters that lie in the Basic Multilingual Plane (BMP), and for such text UTF-16 is in fact a fixed width encoding. Second, since it’s always possible to tell whether a code unit is a complete character, a leading surrogate, or a trailing surrogate, there is little danger from treating a UTF-16 string as a sequence of code units instead of a sequence of code points. Corrupting a UTF-16 string by inserting an incorrect code unit is no more likely than corrupting a UTF-32 string, and the corruption, if any, will be confined to a single character.
We don’t need to say very much about how the library handles char16_t strings. There is already language in the standard to allow facets to give errors at run time for invalid strings, and we need that for UTF-32 as well as UTF-16.
In practice, we need library support for UTF-16 because that’s the real world; if the standard library ignores UTF-16 then the standard library will be irrelevant to processing non-ASCII text. The small amount of extra simplicity that you get from using UTF-32 instead of UTF-16 just doesn’t outweigh the cost of using 4 bytes per character instead of 2+ε. Microsoft, Apple, and Java all use UTF-16 as their primary string representation, and in practice it works fine. Microsoft’s decision to use UTF-16 for wchar_t shows that there is no insuperable obstacle to using UTF-16 with the standard C++ library.
The C++ standard assigns names for many of the specializations of class templates on character types. For example, string is shorthand for basic_string<char> and wstreambuf is shorthand for basic_streambuf<wchar_t>. Our general pattern: no prefix for char specializations and the prefix ‘w’ for wchar_t specializations. What should the pattern be for specializations on char16_t and char32_t?
In principle we could use a prefix based on the “u” and “U” prefixes that N2149 proposes for Unicode string literals, or we could use a prefix or suffix based on the “16” and “32” in the type names themselves. I propose a combination of the two: a “u” prefix for the char16_t specializations and a “u32” prefix for the char32_t specializations. Rationale:
I expect that basic_string<char16_t> will be used much more often than basic_string<char32_t> or basic_string<wchar_t>, since UTF-16 is generally a good tradeoff between convenience and space efficiency. This argues that the name of basic_string<char16_t> should not be more cumbersome than that of basic_string<char32_t> or basic_string<wchar_t>, and that it should have a single-character prefix. The obvious choice is “u”.
There is an obvious one-character prefix for char32_t specializations, “U”. In general, however, the standard library avoids uppercase names, and especially avoids having two names that differ only by case. Using a “u32” prefix for char32_t specializations does mean that it will be less convenient to use basic_string<char32_t> than to use basic_string<char16_t>, but that reflects what I expect to be real-world usage. I do not expect people to use UTF-32 as often as they use UTF-16.
There is no prior art for a C++ library implementation containing four types named char, wchar_t, char16_t, and char32_t. However, there is also no doubt that the proposal is implementable. There is extensive prior art for C++ standard library implementations that use UTF-16 wide characters (wchar_t in Microsoft’s C++ implementation uses UTF-16), and there is extensive prior art for C++ standard library implementations that use UTF-32 wide characters (most Unix implementations).
Since N2149 has not been voted into the WP, building library facilities on top of it is slightly dicey. In principle a number of questions are still open: the names of the two new types (I have chosen to use char16_t and char32_t in accordance with TR 19769 and N2018), whether they are new built-in types or new user-defined types (the latter would only make sense if there are core language changes to permit string literals for user-defined types), whether char16_t and char32_t are the names of types or just the names of typedefs for underlying types with uglier names, and, if they are typedef names, which namespace the typedefs live in. Except for the names char16_t and char32_t, nothing in this paper depends on those decisions.
This document has been revised as a result of the LWG's straw polls in Portland. The LWG voted on whether to support char16_t and char32_t for various library facilities:
Two items are conspicuously missing from this paper: UTF-8 support, and explicit support for Unicode features like normalization, case conversion, and collation. I intend to address those issues in future papers.
One way to provide UTF-8 support would be a new string class whose interface is very different from basic_string, designed to preserve string validity and to encourage users to view the string as code points rather than individual bytes. Alternative approaches include UTF-8 iterator adaptors, or just user education to encourage users to store UTF-8 data in the existing string class.
Some form of UTF-8 support is important because there's an awful lot of real-world code that uses UTF-8 even internally, and programmers certainly need UTF-8 to interface with third-party libraries like libxml2.
Unicode is more than a character set and a handful of encoding schemes. It also specifies a great deal of information about each character, including script identification, character classification, and text direction, and various operations on strings, including normalization, case conversion, and collation.
Normalization is particularly important because there are cases where two different sequences of code points can represent what is conceptually the same string. For example, a string that is printed as “á” can be either the single character U+00E1 (LATIN SMALL LETTER A WITH ACUTE) or the two-character sequence U+0061 (LATIN SMALL LETTER A) U+0301 (COMBINING ACUTE ACCENT). Unicode defines several different canonical forms, and algorithms for converting to canonical form and for testing string equivalence.
In principle some of these facilities are already part of C++’s facet interface, and it might be argued that we do not need a separate mechanism just for Unicode. There is, however, an important way in which Unicode is special: since it uses a single code point space for all scripts, many operations in Unicode are locale-independent that in other encodings are necessarily locale-dependent. Since the C++ locale interface is so awkward, it would be useful to provide a locale-independent interface for common operations that do not require locales.
ICU (International Components for Unicode) is a useful source of prior art.
In clause 20.5 [lib.function.objects], in the header <functional> synopsis, add the following specializations of class template hash<>:
template<> struct hash<char16_t>;
template<> struct hash<char32_t>;
template<> struct hash<std::ustring>;
template<> struct hash<std::u32string>;
In clause 20.5.15 [lib.unord.hash],
in paragraph 1, change "and
std::string and
std::wstring" to read "and
std::string,
std::wstring,
std::ustring, and
std::u32string".
Add two new sections after 21.1.3.2 [lib.char.traits.specializations.wchar.t]:
[lib.char.traits.specializations.char16.t]
namespace std {
template<>
struct char_traits<char16_t> {
typedef char16_t char_type;
typedef uint_least_16_t int_type;
typedef streamoff off_type;
typedef u16_t.
The two-argument member assign is defined identically to the built-in operator =. The two-argument members eq and lt are defined identically to the built-in operators == and <.
The member eof() returns an implementation defined constant that cannot appear as a valid UTF-16 code unit.
[lib.char.traits.specializations.char32.t]
namespace std {
template<>
struct char_traits<char32_t> {
typedef char32_t char_type;
typedef uint_least_32_t int_type;
typedef streamoff off_type;
typedef u3232_t.
The two-argument member assign is defined identically to the built-in operator =. The two-argument members eq and lt are defined identically to the built-in operators == and <.
The member eof() returns an implementation defined constant that does not represent a Unicode code point.
In clause 21.2 [lib.string.classes], add the following to the beginning of the header <string> synopsis:
template<> struct char_traits<char16_t>;
template<> struct char_traits<char32_t>;
and the following to the end:
typedef basic_string<char16_t> ustring;
typedef basic_string<char32_t> u32string;
In Table 65 (Locale category facets) in clause 22.1 [lib.locale.category], add the following specializations:
codecvt<char16_t, char, mbstate_t>
codecvt<char32_t, char, mbstate_t>
In Table 66 (Required Specializations) in clause 22.1 [lib.locale.category], add the following specializations:
codecvt_byname<char16_t, char, mbstate_t>
codecvt_byname<char32_t, char, mbstate_t>
In clause 22.2.1.4 [lib.locale.codecvt] paragraph 3, remove the phrase “namely codecvt<wchar_t, char, mbstate_t> and codecvt<char, char, mbstate_t>.” Add the following sentence, after the one describing the wchar_t specialization: “The specialization codecvt<char16_t, char, mbstate_t> converts between the UTF-16 and UTF-8 encoding schemes, and the specialization codecvt<char32_t, char, mbstate_t> converts between the UTF-32 and UTF-8 encoding schemes.”
[1] Lawrence Crowl, Extensions for the Programming Language C++ to Support New Character Data Types. WG21 N2149, 2007.
[2] ISO. Information technology -- Universal Multiple-Octet Coded Character
Set (UCS), ISO/IEC 10646.
[3] ISO. Information technology -- Programming languages, their environments and system software inferfaces -- Extensions for the programming language C to support new character data types, ISO/IEC TR 19769:2004.
[4] ().
[5] The Unicode Consortium, Frequently Asked Questions,. See in particular for a discussion of encodings.
[6] The Unicode Consortium, What is Unicode?, | http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2207.html | CC-MAIN-2020-45 | en | refinedweb |
I have a script that lists all layers in an MXD and I have a script that lists all broken layers in an MXD. I want to list all layers, their name, source, description, and whether or not their source is broken. Can anyone help me with this?
import arcpy, os, fnmatch, csv
#Create an empty list of ArcMap documents to process...
mxd_list=["A.mxd", "B.mxd", "C.mxd"]
for mxd in mxd_list:
mxd = arcpy.mapping.MapDocument(mxd)
mapPath = mxd.filePath
fileName = os.path.basename(mapPath)
layers = arcpy.mapping.ListLayers(mxd)
filepath = "C:/Users/USERNAME/Desktop/"+ fileName[:-4]+".csv"
writer = csv.writer(file(filepath, 'wb'))
sourcelist = []
for layer in layers:
if layer.supports("dataSource"):
layerattributes = [layer.longName, layer.dataSource]
#Write the attributes to the csv file...
writer.writerow(layerattributes)
writer.writerow(sourcelist)
del writer
I figured out an easy fix: I create an array of the broken layers, then check to see if the layers in the MXD are in that array. I instruct my output to write a "yes" or "No" to determine if the layer is broken. | https://community.esri.com/thread/217113-arcpy-list-all-layers-in-mxd-and-then-make-a-note-of-whether-is-it-broken-or-not | CC-MAIN-2020-45 | en | refinedweb |
Can anybody advise, I'd appreciate some pointers.
networkn: If you want simple, no fuss and Non Techie, then I think you want a Windows Box. Higher Up front cost, lower TCO :)
Michael Murphy |
A quick guide to picking the right ISP | The Router Guide | Community UniFi Cloud Controller | Ubiquiti Edgerouter Tutorial
#include <std_disclaimer>
Any comments made are personal opinion and do not reflect directly on the position my current or past employers may have. | https://www.geekzone.co.nz/forums.asp?forumid=46&topicid=151584&page_no=1 | CC-MAIN-2018-13 | en | refinedweb |
NAME
ioperm - set port input/output permissions
SYNOPSIS
#include <sys/io.h> /* for glibc */ int ioperm(unsigned long from, unsigned long num, int turn_on);
DESCRIPTION not inherited by the child created by fork(2); following a fork(2) the child must turn on those permissions that it needs. Permissions are preserved across execve(2); this is useful for giving port access permissions to unprivileged programs. PowerPC) This call is not supported. ENOMEM Out of memory. EPERM The calling thread has insufficient privilege.
CONFORMING TO
ioperm() is Linux-specific and should not be used in programs intended to be portable.
NOTES
The /proc/ioports file shows the I/O ports that are currently allocated on the system. Glibc has an ioperm() prototype both in <sys/io.h> and in <sys/perm.h>. Avoid the latter, it is available on i386 only.
SEE ALSO
iopl(2), outb(2), capabilities(7)
COLOPHON
This page is part of release 4.04 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. | http://manpages.ubuntu.com/manpages/xenial/en/man2/ioperm.2.html | CC-MAIN-2018-13 | en | refinedweb |
ssh-http-proxy-connect(1)
ssh-socks5-proxy-connect(1)
- return the state of the NIS+ namespace using a conditional expression
nistest [-ALMP] [-a rights | -t type] object
nistest [-ALMP] [-a rights] indexedname
nistest -c dir1 op dir2:
This option is used to verify that the current process has the desired or required access rights on the named object or entries. The access rights are specified in the same way as the nischmod(1) command.
All data. This option specifies that the data within the table and all of the data in tables in the initial table's concatenation path be returned. This option is only valid when using indexed names or following links.
Follow links. If the object named by object or the tablename component of indexedname names a LINK type object, the link is followed when this switch is present.
Master server only. This option specifies that the lookup should be sent to the master server of the named data. This guarantees that the most up to date information is seen at the possible expense that the master server may be busy.
Follow concatenation path. This option specifies that the lookup should follow the concatenation path of a table if the initial search is unsuccessful. This option is only valid when using indexed names or following links.
This option tests the type of object. The value of type can be one of the following:
Return true if the object is a directory object.
Return true if the object is a group object.
Return true if the object is a link object.
Return true if the object is a private object.
Return true if the object is a table object.
Test whether or not two directory names have a certain relationship to each other, for example, higher than (ht) or lower than (lt). The complete list of values for op can be displayed by using the -c option with no arguments.
Example 1 Using.
If this variable is set, and the NIS+ name is not fully qualified, each directory specified will be searched until the object is found. See nisdefaults(1).
The following exit values are returned:
Successful operation.
Failure due to object not present, not of specified type, and/or no such access.
Failure due to illegal usage.
See attributes(5) for descriptions of the following attributes:
NIS+(1), nischmod(1), nisdefaults(1), nismatch(1), attributes(5)
NIS+ might not be supported in future releases of the Solaris operating system. Tools to aid the migration from NIS+ to LDAP are available in the current Solaris release. For more information, visit. | https://docs.oracle.com/cd/E18752_01/html/816-5165/nistest-1.html | CC-MAIN-2018-13 | en | refinedweb |
just released a new PyGObject, for GNOME 3.7.2 which is due on Wednesday.
In this version PyGObject went through some major refactoring: Some 5.000 lines of static bindings were removed and replaced with proper introspection and some overrides for backwards compatibility, and the static/GI/overrides code structure was simplified. For the developer this means that you can now use the full GLib API, a lot of which was previously hidden by old and incomplete static bindings; also you can and should now use the officially documented GLib API instead of PyGObject’s static one, which has been marked as deprecated. For PyGObject itself this change means that the code structure is now a lot simpler to understand, all the bugs in the static GLib bindings are gone, and the GLib bindings will not go out of sync any more.
Lots of new tests were written to ensure that the API is backwards compatible, but experience teaches that ther is always the odd corner case which we did not cover. So if your code does not work any more with 3.7.2, please do report bugs.
Another important change is that if you build pygobject from source, it now defaults to using Python 3 if installed. As before, you can build for Python 2 with
PYTHON=python2.7 or the new
--with-python=python2.7 configure option.
This release also brings several marshalling fixes, docstring improvements, support for code coverage, and other bug fixes.
Thanks to all contributors!
Summary of changes (see changelog for complete details):
- [API change] Drop almost all static GLib bindings and replace them with proper introspection. This gets rid of several cases where the PyGObject API was not matching the real GLib API, makes the full GLib API available through introspection, and makes the code smaller, easier to maintain. For backwards compatibility, overrides are provided to emulate the old static binding API, but this will throw a PyGIDeprecationWarning for the cases that diverge from the official API (in particular, GLib.io_add_watch() and GLib.child_watch_add() being called without a priority argument). (Martin Pitt, Simon Feltman)
- [API change] Deprecate calling GLib API through the GObject namespace. This has always been a misnomer with introspection, and will be removed in a later version; for now this throws a PyGIDeprecationWarning.
- [API change] Do not bind gobject_get_data() and gobject_set_data(). These have been deprecated for a cycle, now dropped entirely. (Steve Frécinaux) (#641944)
- [API change] Deprecate void pointer fields as general PyObject storage. (Simon Feltman) (#683599)
- Add support for GVariant properties (Martin Pitt)
- Add type checking to GVariant argument assignment (Martin Pitt)
- Fix marshalling of arrays of struct pointers to Python (Carlos Garnacho) (#678620)
- Fix Gdk.Atom to have a proper str() and repr() (Martin Pitt) (#678620)
- Make sure g_value_set_boxed does not cause a buffer overrun with GStrvs (Simon Feltman) (#688232)
- Fix leaks with GValues holding boxed and object types (Simon Feltman) (#688137)
- Add doc strings showing method signatures for gi methods (Simon Feltman) (#681967)
- Set Property instance doc string and blurb to getter doc string (Simon Feltman) (#688025)
- Add GObject.G_MINSSIZE (Martin Pitt)
- Fix marshalling of GByteArrays (Martin Pitt)
- Fix marshalling of ssize_t to smaller ints (Martin Pitt)
- Add support for lcov code coverage, and add a lot of missing GIMarshallingTests and g-i Regress tests. (Martin Pitt)
- pygi-convert: remove deprecated GLib ? GObject conversions (Jose Rostagno)
- Add support for overriding GObject.Object (Simon Feltman) (#672727)
- Add –with-python configure option (Martin Pitt)
- Do not prefer unversioned “python” when configuring, as some distros have “python” as Python 3. Use Python 3 by default if available. Add –with-python configure option as an alternative to setting $PYTHON, whic is more discoverable. (Martin Pitt)
- Fix property lookup in class hierarchy (Daniel Drake) (#686942)
- Move property and signal creation into _class_init() (Martin Pitt) (#686149)
- Fix duplicate symbols error on OSX (John Ralls)
- [API add] Add get_introspection_module for getting un-overridden modules (Simon Feltman) (#686828)
- Work around wrong 64 bit constants in GLib Gir (Martin Pitt) (#685022)
- Mark GLib.Source.get_current_time() as deprecated (Martin Pitt)
- Fix OverflowError in source_remove() (Martin Pitt) (#684526) | http://voices.canonical.com/user/29/tag/gnome/?page=1 | CC-MAIN-2018-13 | en | refinedweb |
Hi All,
I have a database with schema foo with table test
i have a schema bar with view vw_test
create view bar.vw_test
as
select x,y,z from foo.test
etc etc etc
now i add a user to the server and database and just have grant select on schema::bar to user permissions
Now, if the behaviour was consistent between the database environments I'd know where to begin (all running sql server r2 (RTM) btw)
I add a sql service account to one environment and grant select on schema, works fine. I add an AD account, works fine
I try the same on another environment and it doesn't work unless i do something like
select * from bar.[vw_test];
Im not joking. select * from bar.vw_test wont work, neither will select * from bar.[vw_test]
it needs to have a ; or go after it
The error is
The SELECT permission was denied on the object 'test', database 'xx', schema 'foo'.
Is there some database or server level option that's inconsistent across the environments? I ran the schema compare is VS2010 but it didn't pick anything up.
If i change it to quoted_identifiers off then it's the opposite. It only works if the command is by itself- cant have 'go' or ; after it.
My expectation was that i wouldnt need to grant explicit permissions to the und
View Complete Post
Hi,
Hi
I create contextmenu using that code
protected MenuItem itemAdd, itemDelete, itemSelectBranch, itemDeleteClasp;
protected MenuItem itemCut, itemCopy, itemPaste, itemAddParent, itemPasteWithChildren;
protected MenuItem itemAddTask, itemAddExtTask, itemAddMileStone;
menu = new ContextMenu();
itemAdd = new MenuItem
{
HorizontalAlignment = HorizontalAlignment.Left,
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch,
Header = "Add"
};
itemDelete = new MenuItem
{
HorizontalAlignment = HorizontalAlignment.Left,
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch,
Header = "Delete"
};
itemSelectBranch = new MenuItem
{
HorizontalAlignment = HorizontalAlignment.Left,
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch,
Header =
ÃÂ
I am currently using markup like the following:
ÃÂ <Binding diagnostics:PresentationTraceSources.TraceLevel="High" RelativeSource="{RelativeSource Self}" Path="(PatientControls:Entity
Hi guys
I'm seeing some very strange behaviour when trying to sort my series groups on a chart.
I have an Analysis Services dataset with Job Grades and Job Grade Codes, the job grade simply being a concatenation of the Job Grade and the word "GRADE", e.g.
1 | GRADE 1
2 | GRADE 2
3 | GRADE 3 etc.
I've pulled in the field Job_Grade into my Series groups section for a chart. I then tried to sort it by the key value which is the Job_Grade_Code like this:
=Fields!Job_Grade.Key
This produced the following result:
Grade 6
Grade 7
Grade 8.....
Grade 4
Grade 5
I noticed that the sorting was incorrect. I noticed that in the source the Job_Grade_Code field was a varchar value, so I changed the sorting expression to the following:
=Cint(Fields!Job_Grade.Key)
This however made no difference and still sorted my grades in the incorrect order
Hi Friends,
I am getting Strange behaviour from the for loop.
Here is the loop
for(i=1, i<=1000000, i++)
{
label1.text = string1;( string 1, 2 , 3 comming from logic)
label2.text = string2;
label3.text = string3;
label4.text = string4;
once i got them i storing in the table of sql server using following steps,
SqlConnection conn = new SqlConnection(); conn.ConnectionString = " connectionstring "; SqlCommand cmd = new SqlCommand(); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = "INSERT INTO table(value1, value2, value3, value4, value5) VALUES( @i, @value1,@value2,@value3,@value4)"; cmd.Parameters.Add(new SqlParameter("@i", i ))
In my cube I have one Time dimension that I use for filtering my data. The way I select my check boxes in the Time dimension influences the shown data. I checked the created filter
by using SQL Server Profiler and this shows that the created filter is totally wrong!
Scenario 1 (NOK)
Steps
· have trying to write a HttpHandler to Filter some content before rendering. As HttpApplication.Context.Response.OutputStream does not support manipulatiing at this stage. so, for remedy i am extending it to customize Write method
here is the code System.IO;
using System.Text.RegularExpressions;
namespace WebApplication1
{
public class StdViewStateRemover : System.Web.IHttpModule
{
private System.Web.HttpApplication mApplication;
public StdViewStateRemover()
{
}
public void Init(System.Web.HttpApplication application)
{
// Wire up beginrequest
application.BeginRequest += new System.EventHandler(BeginRequest);
// Save the application
mApplication = application;
}
public void BeginRequest(Object sender, EventArgs e)
{
//for testing purposes i just checking jpg images
if (((HttpApplication)sender).Request.Path.ToLower().Contains("jpg".ToLower()))
{
return
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/links/67431-2008r2-strange-schema-related-permission.aspx | CC-MAIN-2018-13 | en | refinedweb |
Using Streaming Assets in Unity
How does a game gain traction and become a hit? There’s no secret recipe, but letting players take full control of the game and customize it to their liking with streaming assets is a powerful selling feature for sure.
In this tutorial, you’ll use the streaming assets directory under Unity to let your users customize the game’s UI, soundtrack, player model, and even create their own levels!
Along the way, you’ll learn:
- How the Streaming Assets directory works.
- How to load resources from the Streaming Assets directory at runtime.
- How to harness the data from files added by your users.
Note: You’ll need to be familiar with some basic C# and know how to work within the Unity 2017.1 development environment. If you need some assistance getting up to speed, check out the Unity tutorials on this site.
Getting Started
Download the starter project here, and unzip and open the TankArena_Starter project in Unity. Another folder called TankArenaAllAssets is included with some sample assets you can use later on in this tutorial.
Note: Credit goes to Eric, our venerable Unity Team Leader for the tank model. I’ve been dying for find a use for that tank! The royalty-free music later in the tutorial is from the excellent Bensound. Finally, thanks to my kids who helped create some of the custom content!
Hit play and you’ll find yourself in a little tank in a little arena. Your goal is to proceed to the glimmering tower of light that constitutes the target tile. But be warned — there are a number of obstacles you need to avoid or destroy in order to reach your goal.
The game as it stands is a little “meh”, so you’ll add some on-demand assets to let the player customize the game and create some exciting levels.
There are several ways to serve up resources to Unity at runtime, and each method has its place in game development: asset bundles, resource folders, and streaming assets. Let’s look at each one in turn.
Asset Bundles
Asset bundles let you deliver content to your application outside of your Unity build. Generally, you’d host these files on a remote web server for users to access dynamically.
Why use asset bundles? When developing cross-platform games, you may need to create more than one texture or model to respect the limitations of the target platform. Asset bundles let you deliver the appropriate asset on a per-platform basis while keeping the initial game install size to a minimum.
Asset bundles can contain anything from individual assets to entire scenes, which also makes them ideal for delivering downloadable content (DLC) for your game.
Resource Folders
Unlike Asset bundles, resource folders are baked into the Unity Player as part of the game. You can do this by adding the required assets to a folder named Resources in your assets directory.
Resource folders are useful for loading assets at runtime that would not normally be part of the scene or associated with a GameObject. For example, an extremely rare event or hidden object that’s not seen often is not something you’d want to load 100% of the time.
Streaming Assets
Like Resource Folders, a Streaming Assets directory can be created by intuitively creating a folder named StreamingAssets in your project’s assets directory. Unlike Resource folders, this directory remains intact and accessible in the Unity player. This creates a unique access point for users to add their own files to the game.
Adding Streaming Assets
In the assets window, click on Create and add a new folder to your project. Rename the folder StreamingAssets.
Now click on File\Build Settings and ensure the Target Platform is correctly assigned to the platform you are working on. Click Build to build the player. Navigate to where you output the Unity player.
- On a PC, look in the accompanying folder titled <SaveName>_Data.
- On a Mac, right-click the player and click Show Package Contents. From the popup Finder window, navigate through Contents\Resources\Data.
Any file or folder you drop into there will be accessible to your game. Feel free to drop files directly into the StreamingAssets folder in your Project view so you can quickly test in the Editor as you go.
Adding your First Image
Who is going to step up the plate and take on TankArena? Is it you? Your pet? Your favorite soft toy when you were a kid? Grab a saved photo of them and drag it into the StreamingAssets directory you created in the Project Window. I chose my fearless cat Nando.
If you want to forgo collecting and/or creating a bunch of assets to import, feel free use the assets included in the starter project download under the TankArenaAllAssets folder. I’m sure Nando will not let you down either.
You need to rename your image asset for two reasons:
- The name must contain a specific key word so the game will know what to do with the image.
- The additional text in the file name will give you something to parse to give your hero a screen name.
Rename your image asset in the format “player1 <name>.png”. For example, I named my picture of Nando player1 Captain Patch.png.
Most of the files you add will have a similar format. They’ll have a tag to help identify them to the game, and subsequent text will enable you to add additional parameters to play with.
In the Project Window, navigate to Assets\Scripts and double click on the Game Manager Script to open it in the IDE of your choice.
Under the class declaration, add these public variables to reference the UI Game Objects you will customize:
public Image playerAvatar; public Text playerName;
Before you add any code to find and access the files in your streaming assets directory, you will need to add the following to the top of your GameManager script:
using System.IO;
This adds support for files and directories and allows the reading and writing of files.
Add the following to
Start() under
playerTank = GameObject.FindGameObjectWithTag("Player");:
DirectoryInfo directoryInfo = new DirectoryInfo(Application.streamingAssetsPath); print("Streaming Assets Path: " + Application.streamingAssetsPath); FileInfo[] allFiles = directoryInfo.GetFiles("*.*");
The streaming assets directory resides in different locations depending on the platform. However,
Application.streamingAssetsPath will always return the correct path. The entirely optional
streamingAssetsPath points.
The final line creates an array containing all the files in the streaming assets directory. You will create a series of conditionals as you work through this tutorial to handle the files found.
To send the player’s image to be processed, add the following under the code you just added:
foreach (FileInfo file in allFiles) { if (file.Name.Contains("player1")) { StartCoroutine("LoadPlayerUI", file); } }
The
foreach loop iterates through the files, and the conditional checks to see if the file name contains the key word “player1”. Once found, the file is passed to a Coroutine
LoadPlayerUI() which you’ll add next:
IEnumerator LoadPlayerUI(FileInfo playerFile) { //1 if (playerFile.Name.Contains("meta")) { yield break; } //2 else { string playerFileWithoutExtension = Path.GetFileNameWithoutExtension(playerFile.ToString()); string[] playerNameData = playerFileWithoutExtension.Split(" "[0]); //3 string tempPlayerName = ""; int i = 0; foreach (string stringFromFileName in playerNameData) { if (i != 0) { tempPlayerName = tempPlayerName + stringFromFileName + " "; } i++; } //4 string wwwPlayerFilePath = "file://" + playerFile.FullName.ToString(); WWW www = new WWW(wwwPlayerFilePath); yield return www; //5 playerAvatar.sprite = Sprite.Create(, new Rect(0, 0,,), new Vector2(0.5f, 0.5f)); playerName.text = tempPlayerName; } }
Why a Coroutine? Although loading this image will happen very quickly, you will soon be loading and manipulating many more files. A Coroutine runs off the main thread and will not interrupt the game loop.
On to the code:
- The conditional at the start of the function checks to ensure the file name does not contain meta. If so, the file is likely to be the Unity generated backup file and the function exits. This snippet will be repeated in subsequent file processing coroutines.
- The file name is saved without the extension and subsequently split into a string array containing the individual words.
- An empty string is created for the player’s name. The
foreachloop iterates through the
playerNameDataarray. Each item in the array except for the first one (
player1) is concatenated to the
playerNamestring.
- The full path of the file is needed to load a WWW Object.
yield returnensures execution of the function is delayed until the file is loaded.
- A sprite is created with the loaded texture and applied to
playerAvatar.
playerNameis populated using the
tempPlayerNameyou constructed.
Before you hit that play button to see the fruits of your labor, remember to connect the playerAvatar and playerName to their respective Game Objects in Unity.
In the Unity Editor, select the Game Manager from the Hierarchy Window to expose the public variables in the inspector. Hold Alt and click on the disclosure triangle next to UICanvas in the Hierarchy Window. This should expand UICanvas and all of its children’s children.
Under the GameUIPanel drag PlayerAvatar and PlayerName to their identically named public variables on the Game Manager in the Inspector:
Press the play button and check out your new avatar and name label. Nice!
But wait! There is no way your awesome new avatar would jump into their tank without their own custom soundtrack, right? On to that next.
Beat the game to your own Beats!
There’s a soundtrack.ogg bundled with the resources for your use, but if you think you can find something even more epic, use that instead.
Drag your audio file into the Project Window StreamingAssets folder and rename the file soundtrack.
Note: There are many different audio file types out there. If you have trouble, convert the file to .ogg as it is a well supported format in Unity. Have a look here for free online conversion tools, but be warned: DRM-protected files will not convert.
Add a new public variable to the GameManager:
public AudioSource musicPlayer;
With the GameManager selected in the Hierarchy Window, connect this new variable to the AudioSource on the scene’s Main Camera by dragging the whole Main Camera over the variable in the Inspector.
The Main Camera is a child of your Player’s Tank model, so it obediently follows you around. Remember, you can use the hierarchy’s search box to find any Game Object quickly in the scene.
Head back to the GameManager
Start() function and add a new conditional underneath the other one to pass the soundtrack file to a new Coroutine:
else if (file.Name.Contains("soundtrack")) { StartCoroutine("LoadBackgroundMusic", file); }
Under the
LoadPlayerUI Coroutine, add a new Coroutine titled
LoadBackgroundMusic.
IEnumerator LoadBackgroundMusic (FileInfo musicFile) { if (musicFile.Name.Contains("meta")) { yield break; } else { string musicFilePath = musicFile.FullName.ToString(); string url = string.Format("file://{0}", musicFilePath); WWW www = new WWW(url); yield return www; musicPlayer.clip =(false, false); musicPlayer.Play(); } }
This code should look pretty familiar. Loading an audio file is very similar to loading a texture. You use the URL to load the file and then apply audio to
musicPlayer's
clip property.
Finally, you call
Play() on
musicPlayer to get the soundtrack thumping.
Click play and hit that first level even harder than would have been possible before!
Player Model Customization
Now to customize the tank model. You’ll be walked through two different approaches for customizing the tank model. The first will use simple color swatches to let the user apply their favorite colors to the tank. The second will be a complete re-skin, similar to Minecraft skin mods.
Find the small 20 x 10 pixel playercolor image in the TankArenaAllAssets resources folder that came with the starter project download.
Drag the file into the Project Window StreamingAssets folder as you’ve done before.
Add the following new variables to the Game Manager, all under the new Header tag Tank Customisation:
[Header("Tank Customisation")] public Texture2D tankTexture; public Texture2D tankTreads; public Renderer tankRenderer; private Texture2D newTankTexture; private Vector3 defaultTankPrimary = new Vector3(580, 722, 467); private Vector3 defaultTankSecondary = new Vector3(718, 149, 0);
The Game Manager will need to reference the tank models’ textures and the renderers so that changes can be made and the model reassembled. Additionally, you save the military green primary and red accent secondary color values as integers in a
Vector3 for the upcoming conditional statements. You’re using Vector3 as opposed to Color, since comparing one Color to another is very unreliable.
Jump back into
Start() and add another conditional:
else if (file.Name.Contains("playercolor")) { StartCoroutine("LoadPlayerColor", file); }
Under the
LoadBackgroundMusic() Coroutine, add the following;
IEnumerator LoadPlayerColor(FileInfo colorFile) { //1 if (colorFile.Name.Contains("meta")) { yield break; } else { string wwwColorPath = "file://" + colorFile.FullName.ToString(); WWW www = new WWW(wwwColorPath); yield return www; Texture2D playerColorTexture =; //2 Color primaryColor = playerColorTexture.GetPixel(5, 5); Color secondaryColor = playerColorTexture.GetPixel(15, 5); //3 Color[] currentPixelColors = tankTexture.GetPixels(); Color[] newPixelColors = new Color[currentPixelColors.Length]; //4 float percentageDifferenceAllowed = 0.05f; int i = 0; foreach (Color color in currentPixelColors) { Vector3 colorToTest = new Vector3((Mathf.RoundToInt(color.r * 1000)), (Mathf.RoundToInt(color.g * 1000)), (Mathf.RoundToInt(color.b * 1000))); if ((colorToTest - defaultTankPrimary).sqrMagnitude <= (colorToTest * percentageDifferenceAllowed).sqrMagnitude) { newPixelColors.SetValue(primaryColor, i); } else if ((colorToTest - defaultTankSecondary).sqrMagnitude <= (colorToTest * percentageDifferenceAllowed).sqrMagnitude) { newPixelColors.SetValue(secondaryColor, i); } else { newPixelColors.SetValue(color, i); } i++; } //5 newTankTexture = new Texture2D(tankTexture.width, tankTexture.height); newTankTexture.SetPixels(newPixelColors); newTankTexture.Apply(); //6 ApplyTextureToTank(tankRenderer, newTankTexture); } }
- There's the good old meta check.
- You save the color data of a pixel on the left side and the right side of the color swatch in these two variables.
- You then create two Color arrays. The first,
currentPixelColorscontains all of the color information from the tank's default texture. The second,
newPixelColorswill be populated with same color information — but only once the custom color scheme has been applied. That's why you can instantiate it with the size of the first array.
- The
foreachloop takes each pixel from the currentPixelColors and tests it.
If the color matches the
defaultTankPrimaryyou hard coded, the new
primaryColorvalue is saved in its place to the newPixelColor array. If the color matches the
defaultTankSecondary, save the new
secondaryColor; if the color matches neither, simply save the same color back.
- Once the newPixelColors array is populated, you create a new
texture2Dand call
Apply()to save all pixel changes.
- What is this strange method? Fear not, you'll write that next.
Add the following method under the one you just created:
public void ApplyTextureToTank(Renderer tankRenderer, Texture2D textureToApply) { Renderer[] childRenderers = tankRenderer.gameObject.GetComponentsInChildren<Renderer>(); foreach (Renderer renderer in childRenderers) { renderer.material.mainTexture = textureToApply; } tankRenderer.materials[1].mainTexture = textureToApply; tankRenderer.materials[0].mainTexture = tankTreads; }
ApplyTextureToTank() takes two arguments: the tank
Renderer and the new
Texture2D that you want to apply. You use
GetComponentsInChildren to fetch all of the renderers in the tank model and apply the new modified texture.
GetComponentsInChildren, rather counter-intuitively, fetches the requested component in the parent GameObject. In this particular model, the tank treads have their own texture. You have to reapply this, otherwise your tank will have "tank" tank treads, and that's just weird!
You also place this part of the tank customization in it's own public method as you'll need identical functionality to this later.
The final step is to connect up the new public Game Manager variables in the Inspector.
Ensure Game Manager is selected in the Hierarchy Window. In the Project Window, look in the Assets\Tank Model directory. You will find the two default texture files used to skin the tank model. Drag the LowPolyTank to the Tank Texture and NewThreads to the Tank Treads variable. Back in the Hierarchy Window, drag Player\Tank to Tank Renderer.
Click play and check out your sharp new Tank:
More than One Way to Skin a Tank
The other way to customize tanks is to let the user add new skins to streaming assets and let them select and apply them at runtime.
There's a ScrollView and a Skin Object prefab situated in the Pause menu that you can use for the UI.
Each skin will be showcased by a tank, and a button will enable you to add it.
Some tank "skin" textures were included in the TankArenaAllAssets folder that you got along with the starter project download. Place them in the Project Window StreamingAssets folder now.
Head back to the Game Manager script to get this new feature working.
The skins and their names will be stored in Lists. Therefore, add the
Generic namespace at the top of the Game Manager script;
using System.Collections.Generic;
Add the following variables under your other tank customization variables;
//1 public List<Texture2D> tankSkins; public List<string> tankSkinNames; //2 public GameObject skinContainer; public GameObject skinObject; //3 private bool skinMenuAssembled = false;
- When a skin is found, this adds the texture to the
tankSkinslist and its name to the
tankSkinNameslist.
- To instantiate a Skin Object in the ScrollView, you require a reference to both the prefab to instantiate and the container which will be its parent.
- Finally a Boolean is used to determine whether you have already processed and assembled the skin list in the ScrollView. This will be used to ensure this process is not repeated unnecessarily between level restarts.
As before, add another conditional to the start function:
else if (file.Name.Contains("skin")) { StartCoroutine("LoadSkin", file); }
Create a new coroutine to process the skin files:
IEnumerator LoadSkin(FileInfo skinFile) { if (skinFile.Name.Contains("meta")) { yield break; } else { //1 string skinFileWithoutExtension = Path.GetFileNameWithoutExtension(skinFile.ToString()); string[] skinData = skinFileWithoutExtension.Split(" "[0]); string skinName = skinData[0]; //2 string wwwSkinPath = "file://" + skinFile.FullName.ToString(); WWW www = new WWW(wwwSkinPath); yield return www; Texture2D newTankSkin =; tankSkins.Add(newTankSkin); tankSkinNames.Add(skinName); } }
- The name of the skin is the first word in the filename.
- There may be multiple skin files to process. At this stage, the textures and the names are simply added to lists.
Note: For this tutorial, you simply throw up a loading screen for one second before gameplay starts as this is sufficient for demonstration purposes. For a real game, you may want to add a cool little cut scene if you expect a more involved loading stage, and perhaps a callback of some sort when loading is finally complete.
For this tutorial, you'll assume that when the loading screen dismisses, all of the streaming assets have been processed.
Add the following to the end of
RemoveLoadingScreen():
if (!skinMenuAssembled) { StartCoroutine("AssembleSkinMenu"); }
Create a new Coroutine and add the following code:
IEnumerator AssembleSkinMenu() { skinMenuAssembled = true; int i = 0; //1 foreach (Texture2D skinTexture in tankSkins) { GameObject currentSkinObject = Instantiate(skinObject, new Vector3(0, 0, 0), Quaternion.identity, skinContainer.transform); //2 currentSkinObject.transform.localPosition = new Vector3(100 + (200 * i),-80,0); //3 SkinManager currentSkinManager = currentSkinObject.GetComponent<SkinManager>(); currentSkinManager.ConfigureSkin(tankSkinNames[i], i); ApplyTextureToTank(currentSkinManager.tankRenderer, tankSkins[i]); i++; } yield return null; }
- The
foreachloop iterates through
tankSkins. For each item, you instantiate a Skin Object and add it to the content object in the ScrollView.
- The position of the Skin Object in the Scrollview is offset depending on the index of the list. This ensures all of the skins are neatly spaced out in the view.
- You fetch the SkinManager script in Skin Object and pass it the skin's name and index in the list. You reuse
ApplyTextureToTank()to apply the custom skin to the Skin Object's tank.
Navigate to the Scripts folder in the Project Window and double click on SkinManager script to open it in your IDE.
ConfigureSkin() saves the index it was passed in a private variable and the button label is customized using the skin name.
When the player presses the button to apply a skin,
ApplySkinTapped() sends the saved index back to
ApplySkin() in the GameManager.
Finish off
ApplySkin() at the bottom of the GameManager Script by adding the following code:
ApplyTextureToTank(tankRenderer, tankSkins[indexOfSkin]); PlayerUI.SetActive(true); pauseMenuCamera.SetActive(false); isPaused = false; Time.timeScale = 1.0f;
This extracts the relevant texture from the list and applies it to the players tank. You also remove the pause menu and resume gameplay.
Time to get this all hooked up!
Tap on the Game Manager in the Hierarchy to reveal the Game Manager script in the Inspector. Drag the Skin Object prefab from the Project Window Prefabs folder to the public skinObject variable in the Inspector.
Type content in the Hierarchy search field to find the ScrollView’s content object without losing the Game Manager in the inspector (or tap the lock icon at the top right in the inspector view). Finally, drag the content object into the skinContainer variable.
Tap the play button and press Escape to pause the game. Tap a button and select a new skin for the tank:
Level Design, Now you are Playing with Power!
Okay, it's time to move on to custom level design and creation. Interestingly, you won't need more skills than you've already learned.
First, have a look at the anatomy of an arena so you can get a feel of how it will be constructed.
In the Hierarchy View, double-tap on the Default Arena Game Object to select it and bring it into view in the Scene View. The Arena is constructed from hundreds of tiles, and each tile type is a prefab from the Prefab folder in the Project View. You will use these prefabs to assemble a level in any combination or permutation you can imagine.
The other day I was sitting down with my kids and I asked them if they wanted to design a level for my upcoming tutorial. It went something like this:
Suffice to say I got the kids on the computer and they created two levels from their designs.
You can find these custom levels in the included starter download TankArenaAllAssets folder.
Have a look at the files, by using any image editor a fairly complex level can be constructed...
Now you will create your own custom level and write the code to load any of these levels up.
Open the image editor of your choice and create a new document/canvas 100 px X 100 px square.
Use a hard 1 px pencil tool or line tool to create objects using the following color scheme.
Use the cursor tool to get the x and y coordinates of where you would like the player to start and where the target tile should be.
Save the file as a png when you are finished using the following naming scheme.
arena <x coordinate of player start> <y coordinate of player start> <x coordinate of target> <y coordinate of target> <Name of your level>.png
Once you are happy with your design, add the file to the Project Window StreamingAssets folder.
Head back to the Game Manager. Above the class declaration, add the following code:
[System.Serializable] public class Arena { public string arenaFilePath; public int levelNumber; public string levelName; public float startX; public float startZ; public float targetX; public float targetZ; }
This creates an
Arena class, containing all of the variables necessary to accommodate the data extracted from an arena file. The
Serializable property allows this class to be displayed in the inspector.
Add a new list to the GameManager that will hold all of the instances of the Arena class you create:
[Header("Arena")] public List<Arena> arenaList = new List<Arena>();
Add the following additional public variables to the GameManager under the
arenaList:
public Texture2D arenaTexture; [Header("Arena Prefabs")] public GameObject floorPrefab; public GameObject weakFloorPrefab; public GameObject wallPrefab; public GameObject weakWallPrefab; public GameObject mineTilePrefab; [Header("Arena Objects")] public GameObject defaultArena; public GameObject arenaTiles; public GameObject target; [Space]
These variables comprise all of the building blocks for the level and serve as references to the player and the target object so you can customize their position. You also reference the
defaultArena so we can remove it, and
arenaTiles so that you have a container for new instantiated tiles.
Just like you did previously, add a new conditional statement to the start function:
else if (file.Name.Contains("Arena")) { StartCoroutine("LoadArena", file); }
Create a new coroutine named
LoadArena():
IEnumerator LoadArena (FileInfo arenaFile) { if (arenaFile.Name.Contains(".meta")) { yield break; } else { //1 Arena arenaInstance = new Arena(); string arenaFileWithoutExtension = Path.GetFileNameWithoutExtension(arenaFile.ToString()); string[] arenaDataArray = arenaFileWithoutExtension.Split(" "[0]); arenaInstance.startX = int.Parse(arenaDataArray[1]); arenaInstance.startZ = int.Parse(arenaDataArray[2]); arenaInstance.targetX = int.Parse(arenaDataArray[3]); arenaInstance.targetZ = int.Parse(arenaDataArray[4]); //2 string levelName = ""; if (arenaDataArray.Length <= 5) { if (arenaList.Count != 0) { levelName = "Level " + (arenaList.Count + 1); } else { levelName = "Level 1"; } } else { int i = 0; foreach (string stringFromDataArray in arenaDataArray) { if (i > 4) { levelName = levelName + stringFromDataArray + " "; } i++; } } arenaInstance.levelName = levelName; //3 arenaInstance.arenaFilePath = "file://" + arenaFile.FullName.ToString(); //4 arenaList.Add(arenaInstance); } }
- Here you create a new instance of an Arena. As you've done before, the file name is split and used to populate the class variables.
- For the arena name, you test the number of items in the split file name. If it's less than 6, there is no level name and a default name is assigned based on the number of levels already loaded.
- The file path is saved with the arena instance so that the level can be loaded only when required.
- The fully populated arenaInstance is saved into the GameManagers list of arenas.
Back in
Start(), add the following to load the first level (if one exists) once all of the files have been sent to their coroutines, right after the
foreach loop:
if (arenaList.Count != 0 ) { //1 Destroy(defaultArena); StartCoroutine("LoadLevel", arenaList[0]); }
Add this final Coroutine to load an arena:
IEnumerator LoadLevel(Arena arenaToLoad) { arenaName = arenaToLoad.levelName; //2 loadingScreen.SetActive(true); gameOverScreen.SetActive(false); winScreen.SetActive(false); //3 foreach (Transform child in arenaTiles.transform) { GameObject.Destroy(child.gameObject); } //4 WWW www = new WWW(arenaToLoad.arenaFilePath); yield return www; arenaTexture =; Color[] arenaData = arenaTexture.GetPixels(); //5 int x = 0; foreach (Color color in arenaData) { int xPosition = ((x + 1) % 100); if (xPosition == 0) { xPosition = 100; } int zPosition = (x / 100) + 1; //6 if (color.a < 0.1f) { GameObject.Instantiate(floorPrefab, new Vector3(xPosition / 1.0f, 0.0f, zPosition / 1.0f), Quaternion.Euler(90, 0, 0), arenaTiles.transform); } else { if (color.r > 0.9f && color.g > 0.9f && color.b < 0.1f) { } else if (color.r > 0.9f && color.g < 0.1f && color.b < 0.1f) { GameObject.Instantiate(mineTilePrefab, new Vector3(xPosition / 1.0f, 0.0f, zPosition / 1.0f), Quaternion.identity, arenaTiles.transform); } else if (color.r < 0.1f && color.g > 0.9f && color.b < 0.1f) { GameObject.Instantiate(weakWallPrefab, new Vector3(xPosition / 1.0f, 0.0f, zPosition / 1.0f), Quaternion.identity, arenaTiles.transform); } else if (color.r < 0.1f && color.g < 0.1f && color.b > 0.9f) { GameObject.Instantiate(weakFloorPrefab, new Vector3(xPosition / 1.0f, 0.0f, zPosition / 1.0f), Quaternion.identity, arenaTiles.transform); } else { GameObject.Instantiate(wallPrefab, new Vector3(xPosition / 1.0f, 0.0f, zPosition / 1.0f), Quaternion.identity, arenaTiles.transform); } } x++; } //7 StartCoroutine("RemoveLoadingScreen"); Time.timeScale = 1.0f; //8 playerTank.transform.position = new Vector3(arenaToLoad.startX / 1.0f, 1.0f, (100 - arenaToLoad.startZ) / 1.0f); playerTank.transform.localRotation = Quaternion.Euler(0.0f, 0.0f, 0.0f); target.transform.position = new Vector3(arenaToLoad.targetX / 1.0f, 0.6f, (100 - arenaToLoad.targetZ) / 1.0f); }
- I bet you have been looking forward to this.
Destroythe default arena!
- Since this method could also be called when you complete a level, you reapply the loading screen and remove the win or game over screen.
- Remove any existing Arena tiles in the scene.
- You load the texture from the saved file path and
getPixelscaptures all of the pixel data. This process reduces the 2D 100 x 100 pixels image into a 1D list of color values.
- Iterate over the list of pixel data. You use the index value to determine where the pixel would be in 2D space. The correct tile can then be instantiated in the correct position in the scene.
- The color value of the pixel will determine which tile you should instantiate. Since some image editors may bleed adjacent pixels, you include a small margin of error. The conditionals check the pixel’s color value and instantiate the applicable tile in the correct position.
- Once you've processed all the pixel data, call
RemoveLoadingScreen()to drop the screen after a second and resume gameplay.
- Move the player’s tank and the target tile into their respective positions as recorded in their
Arenainstance.
You're almost there! Find the empty function
StartNextLevel and add the following code:
//1 if (arenaList.Count >= currentLevel + 1) { currentLevel++; StartCoroutine("LoadLevel", arenaList[currentLevel - 1]); } else { SceneManager.LoadScene("MainScene"); } //2 Rigidbody playerRB = playerTank.GetComponent<Rigidbody>(); playerRB.isKinematic = true; playerRB.isKinematic = false;
- Once a level is completed, check to see if another level exists. If so, pass it to
LoadLevel(). Otherwise, reload the entire scene to start over at the first level.
- There may be residual input applied to the tank when restarting or transitioning between levels. Toggle the player's Rigidbody from kinematic to non-kinematic to zero this out.
Now that
StartNextLevel() is fleshed out a little, type "Next" into the Hierachy Window Searchbar in Unity. This should filter down to a single Game Object named Next Level Button. Click to select it, and in the inspector tick interactable under the Button component.
You now need to make a few code amendments to accommodate the fact that you can now have multiple levels (and not just the original starter level).
Replace
SceneManager.LoadScene("MainScene"); in
RestartLevel() with the following:
if (arenaList.Count != 0) { StartCoroutine("LoadLevel", arenaList[currentLevel - 1]); } else { SceneManager.LoadScene("MainScene"); }
This code ensures that instead of just loading the game scene with the default starter level on level restart, the
LoadLevel() coroutine is called instead, which destroys the default arena, and replaces it with the content of the custom level that was loaded from streaming assets.
Also replace
timerText.text = arenaName + " " + formattedTime; in
UpdateTimerUI() with the following line:
timerText.text = arenaList[currentLevel-1].levelName + " " + formattedTime;
This bit of code will ensure that the level name text label in the game UI is updated with the custom level name.
Before you get excited and press Play, don't forget to connect up the prefab outlets in the inspector.
Select the Prefabs folder in the Project Window, and select the Game Manager in the Hierarchy Window. This should expose everything you need.
In the Inspector, you will find the variables for the prefab arena tiles under the Arena Prefabs heading. Each of these has an identically named prefab in the Prefabs folder in the Project Window. Drag each one from the Prefab folder to their respective variable.
Next, take a look at the Arena Objects header in the Inspector. These three GameObject variables are found in the Hierarchy Window. Drag the Target, Default Arena and ArenaTiles from the Hierarchy Window to their respective variables in the Inspector.
Click play and see your designs come to life!
Adding Custom Assets to a Real Build
To wrap this tutorial up, you'll add some custom assets to a real build. After all, that's what your users will be doing!
Remove all of the custom assets from the Project Window StreamingAssets folder and click on File\Build Settings. Ensure the Target Platform is correctly assigned to the platform you are working on and click Build and Run.
You're back to square one! However, the code is still in place to handle any customizations you many want to add.
Navigate to the StreamingAssets folder in the Player Build. On a PC, have a look in the accompanying folder named <SaveName>_Data. On the Mac, right-click the player and click Show Package Contents. From the popup Finder window, navigate to Contents\Resources\Data.
Drop in any or all of the custom assets you've used from the starter project download (under the TankArenaAllAssets folder).
Launch the player again; the customizations should be correctly applied and custom levels loaded. Perfect. :]
Where to Go From Here?
Here's a link to the completed project from this tutorial.
In this tutorial, you learned how to use the streaming assets to customize an existing game in a number of ways. Now you can open that door to your users!
I hope you found this tutorial useful! I'd love to know how it helped you develop something cool. Questions, thoughts or improvements are most welcome in the comments below!
One last thing.).
Team
Each tutorial at is created by a team of dedicated developers so that it meets our high quality standards. The team members who worked on this tutorial are:
- Author
Mark Placzek
- Tech Editor
Mitch Allen
- Editor
Chris Belanger
- Final Pass Editor
Sean Duffy
- Team Lead
Eric Van de Kerckhove | https://www.raywenderlich.com/165809/using-streaming-assets-unity | CC-MAIN-2018-13 | en | refinedweb |
MODGPS
MODGPS is an easy to use library that allows you to get basic time/date and location information from an attached GPS module.
Connecting up the GPS module¶
The MODGPS library only requires you to connect the TX serial out from your GPS module to one of the three available RX serial inputs on the Mbed.
Optionally, if your GPS module has a One Pulse Per Socond (1PPS) output you can connect this to any of the Mbed pins that is supported as an InterruptIn. Without this the GPS the library will return the time to within +/-0.5 of a second. However, connecting the 1PPS signal if available will increase the acuracy to +/-0.001 of a second. Note, the 1PPS output is sometimes incompatible with the Mbed input. In this case you may need to buffer the signal using a transistor or FET. Buffering the signal will often turn a default 1PPS active leading edge to an active trailing edge. More on this later.
Using the MODGPS library¶
First, import the library into the online compiler.
Import libraryMODGPS
Allows for a GPS module to be connected to a serial port and exposes an easy to use API to get the GPS data. New feature, added Mbed/LPC17xx RTC synchronisation
Once imported, change your projects main.cpp to:-
#define COMPILE_EXAMPLE_CODE_MODGPS #define PCBAUD 115200 #define GPSRX p25 #define GPSBAUD 9600 //#define PPSPIN p29 #include "/MODGPS/example1.cpp"
Note, please set PCBAUD to whatever you normally connect your Mbed to Pc/Mac/Linux box. The GPSBAUD is set to 9600 which is common among many GPS modules. If it is different set that too. The PC serial isn't required but you will get more information. Optionally define PPSPIN if you have connected it. If it's not connected leave the #define commented out, otherwise remove the leading comment.
Now switch everything on. LED1 should begin slowly flashing. If you connected any optional 1PPS singal then LED2 will flash once per second.
When the library receives a GPS NMEA RMC data packet LED3 flashes and when a NMEA GGA packet is received LED4 flashes.
If you have a PC connected to the USB serial port on the Mbed, additional data is displayed.
Using the MODGPS library¶
First, create an instance of the GPS object and pass in the RX pin it's connected to:-
#include "mbed.h" #include "GPS.h" GPS gps(NC, p25);
Getting data from the MODGPS library is very simple. There are several ways, the simplest of them shown below.
- To get location data:-
double latitude = gps.latitude(); double longitude = gps.longitude(); double altitude = gps.altitude();
- Or, to get all data together:-
GPS_Geodetic g; gps.geodetic(&g); double latitude = g.lat; double longitude = g.lon; double altitude = g.alt;
- To get time data:-
GPS_Time t; gps->timeNow(&t); pc.printf("%02d:%02d:%02d %02d/%02d/%04d\r\n", t.hour, t.minute, t.second, t.day, t.month, t.year);
The API contains many more functions such as Julian Date, Sidereal time and more. Follow the link to find the full list and documentation. | https://os.mbed.com/cookbook/MODGPS | CC-MAIN-2018-13 | en | refinedweb |
Using Inheritance
Inheritance in C# gives us the ability to create classes which are derived from existing classes. In new derived classes, we only have to specify the methods that are new or changed. All the others are provided automatically from the base class we inherit from. To see how this works, lets consider writing a simple Rectangle class that draws itself on a form window. This class has only two methods, the constructor and the draw method.
namespace CsharpPats
{
public class Rectangle {
private int x, y, w, h;
protected Pen rpen;
public Rectangle(int x_, int y_, int w_, int h_)
x = x_; //save coordinates
y = y_;
w = w_;
h = h_;
//create a pen
rpen = new Pen(Color.Black);
}
//-----------------
public void draw(Graphics g) {
//draw the rectangle
g.DrawRectangle (rpen, x, y, w, h);
Shashi Ray
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/kb/404-using-inheritance.aspx | CC-MAIN-2018-13 | en | refinedweb |
import scala.actors.Actor
case class Trade(id: Int, security: String, principal: Int, commission: Int)
case class TradeMessage(message: Trade)
case class AddListener(a: Actor)
class TradingService extends Actor {
def act = loop(Nil)
def loop(traders: List[Actor]) {
react {
case AddListener(a) => loop(a :: traders)
case msg@TradeMessage(t) => traders.foreach(_ ! msg); loop(traders)
case _ => loop(traders)
}
}
}
An implementation of the Observer design pattern using message passing. Interested traders can register as observers and observe every trade that takes place. But without any mutable state for maintaining the list of observers. Not a very familiar paradigm to the programmers of an imperative language. The trick is to have the list of observers as an argument to the
loop()function which is tail called.
Nice .. asynchronous, referentially transparent, side-effect-free functional code. No mutable state, no need of explicit synchronization, no fear of race conditions or deadlocks, since no shared data are being processed concurrently by multiple threads of execution.
7 comments:
Hey, did you ever benchmark Rabbit MQ against other contenders? ActiveMQ, Qpid?
Just a small quibble, but the code is not really referentially transparent since it depends on the side effected react. React takes a partial function as a parameter and passes to it a message which is neither a parameter to react nor a value in the lexical scope.
That's not to say anything bad about the code. This kind of "state via recursion" programming is a great way to keep actors nice and clean.
It's just to recognize that message passing concurrency, and indeed most forms of concurrency that aren't simple parallel computation like data flow variables/futures, are inherently side effected.
Sir,
Just wondered what you thought of this :
and the package on which it is based :
The above to me looks more approachalbe instead of abandoning the Java language (if i take up Scala) or the entire eco-system (if I take up Erlang).
Regards,
@James: Thanks for pointing it out. I have posted a small update here.
@AnActor: I have not yet looked at Functional Java in detail. But why bend Java to do something which it was not designed for. Scala offers a much cleaner programming model - a neat actor implementation in a library, with much usable syntax (thanks to its better type system). And above all it's all on the JVM !
@anactor - though functional java looks quite brilliant, it still relies on closures, which are not yet shipping with java. in the recent neil grafter interview (up on infoQ), neil says he does not think closures will make it into java7. i'm not sure what ramifications that would entail should functional java's notion and dependency on a particular closure model get out of sync with what actually ships.
if you are stuck on java and need an actor framework, kilim might also be worth investigating. it appears very performant and well thought out.
or... scala is here now. the book will probably hit the press within next 30 days, and buzz will surely abound.
@JHerber: Thank you for the directives. Yes I intend to give Kilim a try one of these days.
Its not that I am stuck with Java but just exploring the options. I am trying to soften the communication I would need to deliver to management and still try out FP. If I pitch Scala or Erlang, for sure I would face understandable questions like :
1. Why the heck are we spending so much moolah trying to get our programmers competent on the Java platform ?
2. So we are not going to tap into the wealth of experience and competence gained on the Java ecosystem ?
3. Uhh so would we miss deadlines and therefore revenue targets for the next quarter because of this new stuff ?
4. How are you going to get your teams of young programmers (3-4 yrs of experience) to shift to a totally different way of programming/thinking - not just a new language, and finally deliver performant, maintainable, production quality systems that need to replace well established existing ones ?
5. Are you sure Scala or Erlang are not nitch players and would become mainstream and we would not need to pay a bomb just to hire/retain a bunch of average programmers ? | http://debasishg.blogspot.com/2008/08/asynchronous-functional-and.html | CC-MAIN-2018-13 | en | refinedweb |
Exercises
- Type in and run the five programs presented in this chapter. Compare the output produced by each program with the output presented after each program in the text.
Which of the following are invalid variable names? Why?
Int char 6_05 Calloc Xx alpha_beta_routine floating _1312 z ReInitialize _ A$
Which of the following are invalid constants? Why?
123.456 0x10.5 0X0G1 0001 0xFFFF 123L 0Xab05 0L -597.25 123.5e2 .0001 +12 98.6F 98.7U 17777s 0996 -12E-12 07777 1234uL 1.2Fe-7 15,000 1.234L 197u 100U 0XABCDEFL 0xabcu +123
Write a program that converts 27° from degrees Fahrenheit (F) to degrees Celsius (C) using the following formula:
C = (F - 32) / 1.8
What output would you expect from the following program?
#include <stdio.h> int main (void) { char c, d; c = 'd'; d = c; printf ("d = %c\n", d); return 0; }
Write a program to evaluate the polynomial shown here:
3x
3- 5x
2+ 6
for x = 2.55.
Write a program that evaluates the following expression and displays the results (remember to use exponential format to display the result):
(3.31 x 10
-8x 2.01 x 10
-7) / (7.16 x 10
-6+ 2.01 x 10
-8)
To round off an integer i to the next largest even multiple of another integer j, the following formula can be used:
Next_multiple = i + j - i % j
For example, to round off 256 days to the next largest number of days evenly divisible by a week, values of i = 256 and j = 7 can be substituted into the preceding formula as follows:
Next_multiple = 256 + 7 - 256 % 7 = 256 + 7 - 4 = 259
Write a program to find the next largest even multiple for the following values of i and j: | http://www.informit.com/articles/article.aspx?p=2246402&seqNum=6 | CC-MAIN-2018-13 | en | refinedweb |
There are three types of commenting syntax in C#multiline, single-line, and XML.
Multiline Comments
Multiline comments have one or more lines of narrative within a set of comment delimiters. These comment delimiters are the begin comment /* and end comment */ markers. Anything between these two markers is considered a comment. The compiler ignores comments when reading the source code. Lines 1 through 4 of Listing 1 show a multiline comment. For convenience, Lines 1 through 4 of Listing 1 are repeated here.
1: /* 2: * FileName: HowdyParner.cs 3: * Author: Joe Mayo 4: */
Some languages allow embedded multiline comments, but C# does not. Consider the following example:
1: /* 2: Filename: HowdyPartner.cs 3: Author: Joe Mayo 4: /* 5: Initial Implementation: 04/01/01 6: Change 1: 05/15/01 7: Change 2: 06/10/01 8: */ 9: */
The begin comment on Line 1 starts a multiline comment. The second begin comment on line 4 is ignored in C# as just a couple characters within the comment. The end comment on Line 8 matches with the begin comment on line 1. Finally, the end comment on Line 9 causes the compiler to report a syntax error because it doesn't match a begin comment.
Single-Line Comments
Single-line comments allow narrative on only one line at a time. They begin with the double forward slash marker, //. The single-line comment can begin in any column of a given line. It ends at a new line or carriage return. Lines 6, 9, and 12 of Listing 1 show single-line comments. These lines are repeated here for convenience.
6: // Program start class 7: public class HowdyPartner 8: { 9: // Main begins program execution 10: public static void Main() 11: { 12: // Write to console 13: System.Console.WriteLine("Howdy, Partner!");
Single-line comments may contain other single-line comments. Because they're all on the same line, subsequent comments will be treated as comment text.
XML Documentation Comments
XML documentation comments start with a triple slash, ///. Comments are enclosed in XML tags. The .NET C# compiler has an option that reads the XML documentation comments and generates XML documentation from them. This XML documentation can be extracted to a separate XML file. Then XML style sheets can be applied to the XML file to produce fancy code documentation for viewing in a browser. Table 1 shows all standard XML documentation tags.
Table 1 XML Documentation Tags
To provide a summary of an item, use the <summary> tag. Here's what one might look like for a Main() method:
/// <summary> /// Prints "Howdy, Partner" to the console. /// </summary>
Documentation comments can be extremely useful in keeping documentation up-to-date. How many programmers do you know who conscientiously update their documentation all the time? Seriously, when meeting a tight deadline, documentation is the first thing to go. Now there's help. While in the code, it's easy to update the comments, and the resulting XML file is easy to generate. The following line of code will extract documentation comments from the HowdyPartner.cs file and create an XML document named HowdyPartner.xml.
csc /doc:HowdyPartner.xml HowdyPartner.cs
For C++ Programmers
C# has XML documentation comments that can be extracted to separate XML files. Once in an XML file, XML style sheets can be applied to produce fancy code documentation for viewing in a browser. | http://www.informit.com/articles/article.aspx?p=23211&seqNum=3 | CC-MAIN-2018-13 | en | refinedweb |
Gradient..
A standard approach to solving this type of problem is to define an error function (also called a cost function) that measures how “good” a given line is. This function will take in a
(m,b) pair and return an error value based on how well the line fits our data. To compute this error for a given line, we’ll iterate through each
(x,y) point in our data set and sum the square distances between each point’s
y value and the candidate line’s
y value (computed at
mx + b). It’s conventional to square this distance to ensure that it is positive and to make our error function differentiable.:
Lines that fit our data better (where better is defined by our error function) will result in lower error values. If we minimize this function, we will get the best line for our data. Since our error function consists of two parameters (
m and
b) we can visualize it as a two-dimensional surface. This is what it looks like for our data set:
Each point in this two-dimensional space represents a line. The height of the function at each point is the error value for that line. You can see that some lines yield smaller error values than others (i.e., fit our data better).. To compute it, we will need to differentiate our error function. Since our function is defined by two parameters (
m and
b), we will need to compute a partial derivative for each. These derivatives work out to be:
We now have all the tools needed to run gradient descent. We can initialize our search to start at any pair of
m and
b values (i.e., any line) and let the gradient descent algorithm march downhill on our error function towards the best line. Each iteration will update
m and
b to a line that yields slightly lower error than the previous iteration.. Each iteration
m and
b are updated to values that yield slightly lower error than the previous iteration. The left plot displays the current location of the gradient descent search (blue dot) and the path taken to get there (black line). The right plot displays the corresponding line for the current search location. Eventually we ended up with a pretty accurate fit..
108?
Hi Matt,
about Chris’s comment:
Look at the fift image: The y-intercept in the left graph (about 2.2) doesn’t correspond with the y-intercept in the right graph (about -8).
Best,
jalil
the y-intercept in the right graph is not -8. For the y-intercept, you need to find the position where x=0.
hie sir, where should i run this project, i mean in centos.
I did check on the internet so many times to find a way of applying the gradient descent and optimizing the coefficient on logistic regression the way u did explain it here. I’d like to see another work for you explaining this or if you have any other link
Dear Matt:
I ran your simulation (m=-1, b=0, with 2000 iterations), but the final slope and intercept were not the same as the ones you listed. Also, I ran my own best fit and it matches what you have graphically. Anyway, I am just trying to get the best fit line from your gradient algorithm. Maybe I am missing something??
Dave Paper
I think I have got it now. I was able to create a ‘best fit’ line with the final slope and intercept (from your gradient descent algorithm) that matched the ‘best line’ fit from running numpy ‘polyfit’. Thx for the great example!
dave
Hello, what improvements did you do to the code to match a solution from let’s say, Excel with slope = 1.3224 and interceptio = 7.991? I had to make the code do a lot of iterations to achieve that. Did you managed to do it in 2000 iterations?.
sometime we do gradient descent and optimization based on each single vector like the case in NN. how would you explain this..
In OLS cost function (J(theta)) you don’t have to worry about local minimum issues. That is exactly the reason we use convex function to derive it.
Also want to understand how the differentiation is always arriving at a descent.
Vinsent, gradient descent is able to always move downhill because it uses calculus to compute the slope of the error surface at each iteration.
It is my understanding that the gradient of a function at a point A evaluated at that point points in the direction of greatest increase. If you take the negative of that gradient you get the direction of greatest decrease. The gradient vector is derived from the several partial derivatives of the function with respect to its variables. This is why differentiation leads to the direction of greatest descent.
Keeping this in mind, if you are given an error function; by finding the gradient of that function and taking its negative you get the direction in which you have to “move” to decrease your error.
Hope this makes sense.:
How do i use this code to find value of Y for a new value of x?
Nicely explained!! Enjoyed the post.Thanks
That was such an awesome explanation !! Can you also explain logistic regression and gradient descent
Thanks Praveen, glad you liked it. Also, thanks for the logistic regression suggestion, I may consider writing a post on that in the future.
Matt, this is a boss-level post. Really helped me understand the concept. Gold stars and back-pats all round.
I really liked the post and the work that you’ve put in. I suggest you add a like button to your posts.
Hi Matt,
Overall your article is very clear, but I want to clarify one important moment. The real m and b are 1.28 and 9.9 respectively for the data you ran on your code (e.g. data.csv). But your code gives us totally different results, why is that?
I know we can get that true result above by giving different random m and b, but shouldn’t our code work for any random m and b?
Would be kind clarifying that moment please, it is very important for me.
Thank you in advance.
Hi Altay, how are you computing 1.28 and 9.9 for the real m and b?
Hi,
I’ve just simply used excel to compute that linear regression. Also vusualized that line graphically to check.
It’s important to understand that there is no “true” or “correct” answer (e.g., m and b values). We are trying to model data using a line, and scoring how well the model does by defining an objective function (error function) to minimize. It’s very possible that Excel is using a different objective function than I used. It’s also possible that I did not run gradient descent for enough iterations, and the error difference between my answer and the excel answer is very small. Ideally, you would have some test data that you could score different models against to determine which approach produces the best result.
Hi Matt,
Sorry for my late reply.
But I thought that Gradient Descent should give us the exact and most optimal fitting m and b for training data, at least because we have only one independent variable X in the example you gave us.
If I miss smth, correct me please.
If you compare the error for the (m,b) result I got above after 2000 iterations, it is slightly larger than the (m,b) example you reported from excel (call the compute_error_for_line_given_points function in my code with the two lines and compare the result). Had I ran it for more than 2000 iterations it would have eventually converged at the line you posted above.
What I was trying to say above is that gradient descent will in theory give us the most optimal fitting for m and b for a defined objective function. Of course, this comes with all sorts of caveats (e.g., how searchable is the space, are there local minima, etc.).
I am terribly sorry Matt, but there was a slight error with data selection when I was creating my regression formula in excel, so I corrected it and results are m = 1.32 and b = 7.9. And this result is achieved using your python code when I gave m = 2 and b = 8 as initial parameters.
And I played with some other different values as an initial m and b and number of iterations, after which I realized that the best starting values were m = 2 and b = 8.
And I made conclusion that the main point is to give right starting m and b which I do not know how to do.
So I want to thank you for your your article and your replies to my comments which was a sort of short discussion.
Assuming it is the true minimum, it should eventually converge to (1.32, 7.9) regardless of what initial (m,b) value you use. It may take a very long time to do so however.
In the error surface above you can see a long blue ridge (near the bottom of the function). My guess is that the search moves into this ridge pretty quickly but then moves slowly after that. My guess is that you just aren’t running it long enough if you are getting different results for different starting values.
Hi Matt,
Thank you once again. I got correct results just by increasing number of iterations to 1000000 and more.
Hi Matt.
Thanks for efforts. I’m trying to refresh my knowledge with your article.
Can you please explain what do you mean by “Each point in this two-dimensional space represents a line. The height of the function at each point is the error value for that line.” Does that mean each point IS line or what? I cant understand.
Thanks
I am also confused by this point / line vocabulary here. Too bad you did not get any answer.
I believe the 2 dimensions in this 2-dimensional space are m (slope of the line) and b (the y-intercept of the line). Therefore any point in the m,b space will map into a line in the x-y space. I suppose Matt added the 3rd dimension to the m,b space by showing the error associated with the line associated with the m,b pair.
Matt,
Thanks for your blog, especially using PDE and converting into function is quite useful. BTW, this is quite useful for people who is taking CS.190.x on EDX.
Cheers
Hey Matt, just wanted to say a huge “THANK YOU!!” this is the best simple explanation of linear regression + gradient on the Web so far.
Hi, Matt
can you please give an example or an explanation og how gradient descent helps or works in text classification problems.
Hi, this is really interesting, could you also make an article about stochastic gradient descent, please. Thanks.
Matthew,
What is the license for your code examples?
@Michael – great question, I’ve added an MIT license.
Is gradient descent algorithm applied in hadoop….if so how ??
can you explain more about defferentiating the error function specifically?
hi
is there any body who knows some information about shape topology optimization by phase field method ?
best regards
thanks for your web and reply
I’m beginning to study data science and this blog is very helpful. Thanks Matt. Just one question, could you explain how you derive the partial derivative for m and b? thanks a lot.
Can only say: fantastic !!!
Thankyou. I’ve never seen a better explanation in any of my class (I’m a UG Bioinformatics student struggling to understand such concepts) and now I understand this concept thoroughly.
Excellent explanation.
Are you using this to spot a trend in a stock? I have coded something in easy language for Trade Station and what I have found is that there is no correct chart size for the day.
In other words no matter what chart size I use I will know if I should be a buyer or a seller based on the trend for the day.
I then take a measurement and can make a logical decision about what the big boys are doing and then I do what they do.
For instance……I was 100 percent sure that buying EMINI’s above 2060 was a terrible decision and I had calculated that the stall out was going to be 2063.50 …
I also was a seller of oil futures above 42.76 and then I hit it again on the retrace above 42.40.
Are you interested in this type of thing or is this outside the realm of what you are doing?
Great post! I’m trying to understand the type of math behind neural networks through examples and this helped a whole bunch! I did my own implementation of your code in Google Spreadsheets/Google Script (7.5MB GIF)
Hello,
Thanks for the explanation. Does the error function remain same for exponential curve i.e (y – w * e^(lambda * x))^2? If not how does it change when I try to fit a curve using exponential curve and similarly for a hypo exponential – convolution of exponential’s. I am trying to fit curve which is a probability density function using exponential PDF.
To start with I am trying single exponential curve.
I tried implementing the same algorithm for exponential curve but it doesn’t work. The matlab code for the same can be found here –
Thanks for writing this! I’m actually taking Andrew Ng’s MOOC, and I was looking for an explanation of gradient descent that would go into a little more detail than he gave (at least initially…I haven’t finished the course) and show me visually what gradient descent looked like and what the graph for the error function looked like. Your explanation was really helpful and helped me picture what was going on. Thanks!
Me too. I studied regression analysis once a long time ago but I could not recall the details. I searched a lot of other websites and I could not find the explanation that I needed there either. Oddly, conventional presentations of elementary machine learning methods seem to have a meta-language that is half way between mathematics and programming that are riddled with little but significant explanatory gaps.Some details are so important that they should be pointed out in order to make a consistent presentation.
Awesome! Thank you.
At my current job we are using this algorithm specifically. without your example, I would not have been able to figure it out so easily.
What I am trying to figure out is what would be a good way to generate example data for a multi-point(x, y, z) approach using a quadratic in three dimensions?
Matt, This is the best and the most practical explanation of this algorithm. Kudos!! Thanks a lot.
Awesome article………. I was trying to get my head around Neural Networks and came through Gradient Descent……of all article I searched this is the most well explained Article. Thanks a ton.
On a lighter note there is a saying “You do not really understand something unless you can explain it to your grandmother.”…….Well now I can explain my grandmother this stuff :D
Thank you for this valuable article.
I have a problem with my code, I’m using (Simple Regression Problem//
F(a)= a^4+ a^3+ a^2+ a)
but there is no convergence
its about Cartesian genetic programming
my question is
should i use the gradient with it to solve the problem or?????
thanks
Thank you. All i every well detailed but one “line” has no explanation, and this is ( to me the core of the algorithm):
Why on each iteration do you determine that
new_b = b_current – (learningRate * b_gradient)
( same for m : why is the new value = the old value minus the new calculated one )
or, to use your wording: why is this meaning going downhill ?
Thanks for such an fantastic article.
I am attending online course of Prof. Andrew Ng from Coursera.
Your article has contributed to remove many confusions.
In your example I could not find where you are using “learning rate”?
Where you use 0.0001 ?
Thanks in advance for reply.
Bharat.
hello sir, i want to know that if i am training one robot that identify handwitten alphabet character and if i am giving training of character ‘A’ , 50 different training latter A given to robot. then here gradient descent is used or any other?
Can you share the code to generate the gif? Did you just call the matplot lib everytime you compute the values of intercept and slope? I don’t seem to find it on the GitHub
Hello,
In statistics, we use the “Centroid” point to fix at least a point of the line ” Y=m X + b.
very useful, after with only one other point we have the full equation.
(see linear regression in statistics)
But I see in machine learning that you jump to Cost Fonction type of problem to minimize.
and yes, it has to search for both m, and B, the slope and the “Bias” in same time.
Would you please help, explain why they don’t use CENTROID methode ?
thanks
does it work for multi linear regression? if it does, can you please show me how it works? thanks
I am confused in one thing. We have to take the partial derivative of the cost function continuously again and again until we get the local minimum or the derivative will be taken only once?
Is it that once we get the equations
b_gradient += -(2/N) * (points[i].y – ((m_current*points[i].x) + b_current))
m_gradient += -(2/N) * points[i].x * (points[i].y – ((m_current * points[i].x) + b_current))
by taking the partial derivative once and then it will calculate the parameters by itself each time in a loop?
I hope you understand my question..
thanks
Hi Matt:
When I run your code with initial m = -1 and b = 2 for 2000 iterations, I get the following:
b = 0.0607
m = 1.478
When I use polyfit and lineregress functions, I get the following:
b = 7.99
m = 1.322
I believe that I am running your code correctly. Maybe I am doing something wrong??
dave
awesome explanation.
thanks so much
Thanks for the post Matt.. very well explained.
Amazing post. Exactly what I needed to get started. This beautiful explanation of yours give a feel of the mathematics and logic behind the machine learning concept.
Thanks,
Khalid
Hello,
Very Nicely written.
Thank You for this.
Just Curious–Do you have a similar example for a logistic regression model?
If not- Then Can you please share a similar example for logistic regression.
Thank You Again.
hello
can anyone help me
how can i run this in eclipse
Hi Matt, Thanks for this tutorial. I have been searching for clear and consice explanation to machine learning for a while until I read your article. The animation is great and the explanation is excellent. After reading through it I have managed to replicate it with your data set using T-SQL.I am.over the moon.and so grateful to you for making me understand the concepts of gradient descent. If you do have any other machine learning tutorials kindly send me the links in your response.Thanks
Michael
Hey Matt,
Sorry if I am repeating a question. I havent read all the comments but how do you come up with the value learningRate? is it Hit and trial?
Yes, it’s largely trial and error. Plotting the error after each iteration can help you visualize how the search is converging – check out this SO post
Great explanation! Thanks a lot.
Awesome .
Please include an article for stochastic gradient too .
A very good introduction. Covers the essential basics and gives just about enough explantion to understand the concepts well.
One quick question. Apologies if this is a repeat!
You did mention that there can be situations in which we might be stuck in a “Local Minima” & to resolve this we can use “Stochastic Gradient Descent”. But, how do we realize OR understand in the first place, that we are stuck at a local minima and have not already reached the best fitting line?
why do u increment the gradient?
is there someone to let me know what this X is for… in 2nd equation????
why is not it in other equation:
b_gradient += -(2/N) * (y – (m*x) + b))
m_gradient += -(2/N) * x * (y – ((m*x) + b)
i am talking about the x over this dotted place
-(2/N)*……………*(y – ((m * x) + b))
Thanks for the very clear example of linear regression. I’d like to do the surface plot shown just below the error function using matplotlib. I’m having a lot of trouble. I wonder if anyone else has tried this or if Matt is still reading comments.
-2/N should be put out of the for loop right ?
Exactly my thought, but you havent got response, I the -2/N part should go outside the loop too
I am facing problem with a particular data-set even with your python example:
2104,400
1600,330
2400,369
1416,232
3000,540
def computeErrorForLineGivenPoints(b, m, points):
totalError = 0
for i in range(0, len(points)):
totalError += (points[i].y – (m * points[i].x + b)) ** 2
return totalError / float(len(points))
in the above code, for the function “computeErrorForLineGivenPoints(b, m, points)”, what are the parameter values you give for b(y-intercept) and m(slope) parameters. How do you choose b and m ?
I can see from the gradient descent plot that you take only the values between -2 and 4 for both y and m. Why cant it take any other values outside that range ?
The “computeErrorForLineGivenPoints” function is just used to compute an error value for any (m, b) value (i.e., line). I’m using it to show that the error decreases during each iteration of the gradient descent search.
Great page!!! I have one question. How do you put the code in your html? Looks really cool. I want to do the same thing.
Very well written and explained. You inspired me to read and explore more on ML algorithms . Thanks a lot!!!
Clear and well written, however, this is not an introduction to Gradient Descent as the title suggests, it is an introduction tot the USE of gradient descent in linear regression. Gradient descent is not explained, even not what it is. It just states in using gradient descent we take the partial derivatives. The links to Wikipedia are of little use, because these pages are not at all introductory, that’s why I came here. Again, the content is good, but not what it is supposed to be.
Great Explanation!
The only Thing I don’t understand:
Where did you get those Derivatives from?
“These derivatives work out to be:” is not that helpful :(
Thank you very much for fluent and great explanations !!!
At last, I got the Gradient Descent for you.
After a couple of months of studying missing puzzle on Gradient Descent, I got very clear idea from you.
Thanks!! | https://spin.atomicobject.com/2014/06/24/gradient-descent-linear-regression/ | CC-MAIN-2018-13 | en | refinedweb |
From Documentation
Introduction
For Spring application developers, Spring Data project has support for MongoDB that allows mapping Java objects to/from mongoDB documents. In this article I will rewrite the same TODO application sample code described in Part 1 and Part 2 of this series using Spring data for mongoDB.
Spring Data for MongoDB
Spring Data
To include Spring Data for mongodb, add Spring milestone repository in pom.xml like illustrated below as we will use its latest 1.0.0.M5 milestone release
<repository> <id>spring-milestone</id> <name>Spring Maven MILESTONE Repository</name> <url></url> </repository>
Then add Spring data mongoDB dependency in pom.xml as shown below;
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.6.5</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.0.0.M5</version> </dependency>
View
View part remains the same as described in earlier articles. Only change here is that the controller applied to the window is now managed by Spring so we use ZK’s spring variable resolver to resolve controller instance
<?variable-resolver … </window> </zk>
Model
There are two ways in which Spring data for mongodb can support mapping of model/domain objects. One is without using annotations and other is with annotations. Here for the sake of keeping our example code simple I will NOT use annotations so our Task model class simply consists of few fields with corresponding getter/setter methods.
public class Task { private String id; private String name; private Integer priority; private Date executionDate; … // constructor and getter/setter methods
Now I need some supporting service that will handle CRUD of Task instances. First I need to create com.mongodb.Mongo instance and register it with Spring IoC container. Here I will use XML based bean metadata using mongo schema in a separate mongo-config.xml file to achieve this.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="" xmlns: <!-- Default bean name is 'mongo' --> <mongo:mongo …
As you can see from above, default connection settings for com.mongodb.Mongo instance is used. Next, MongoTemplate is the central class in Spring data for mongoDB that provides rich set of features to interact with mongoDB database. I will use XML bean meatadata to register MongoTemplate so I can auto-wire it to use within task service class to perform CRUD operations on task mongoDB documents. Add the following XML fragment into mongo-config.xml.
<!-- Offers convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. --> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg <constructor-arg </bean>
I pass com.mongodb.Mongo bean to MongoTamplate and the database name. Note that MongoTemplate is thread-safe and can be reused in multiple instances.
Now let’s define our TaskService class to work with Model Task instances mapping to/from Task documents in mongoDB.
@Service("taskService") @Transactional public class TaskService { @Resource(name="mongoTemplate") private MongoTemplate mongoTemplate; …
I inject MongoTempalte instance in TaskService class using the @Resource annotation. Now I can use MongoTemplate instance and use its convenient APIs to access mongodb database. Let’s use it to get the list of all previously created tasks in the database.
public List<Task> findAll() { Query query = new Query(where("id").exists(true)); List<Task> tasks = mongoTemplate.find(query, Task.class); return tasks; }
In the above findAll() method, I used where static factory method to create a Criteria instance which in turn is used to create a Query instance. I then pass this Query instance to MongoTamplate find(Query, Class) API. Note that I also pass Task.class to find() API so that MongoTamplate can perform the mapping of Task documents in mongodDBto our Task model class.
Similarly, I implement methods to add, delete and update task documents in simpltasks mongoDB database as shown below;
public void add(Task task) { try { mongoTemplate.insert(task); } catch(Exception e) {} }
Adding new document is simple. Just create a new Task instance and pass it to insert(Object) API of MongoTemplate.
public void update(Task task) { Query query = new Query(where("id").is(task.getId())); try { Update update = new Update(); update.set("name", task.getName()); update.set("priority", task.getPriority()); update.set("executionDate", task.getExecutionDate()); mongoTemplate.updateMulti(query, update, Task.class); } catch(Exception e) {} }
Updating existing mongoDB document is simple as well. First of all, create a Query to identify which document(s) you want to update and create an Update instance which is a map and set the document properties as key and their new value in the form of Key-Value pair. Finally, pass this Query and Update object and model class to updateMulti() API of MongoTemplate so MongoTemplate can map all the document properties accordingly. Note that you can also use updaeFirst() if you only want to update only the first result that matches given query.
public void delete(Task task) { try { Query query = new Query(where("id").is(task.getId())); // Run the query and delete the entry mongoTemplate.remove(query, Task.class); } catch(Exception e) {} }
For deleting, again, create a Query using where factory static method and pass it to remove() API of MongoTemplate.
Controller
@org.springframework.stereotype.Component("todoCtrl") @Scope("prototype") public class SpringTODOController extends GenericForwardComposer { @Resource(name="taskService") private TaskService taskService;
Once TaskService is ready I inject it into todoCtrl bean which is a controller class that is applied to todo application window. Now rest of the application behavior can be easily implemented by defining add,update and delete button event handlers and using above defined TaskSerivce CRUD methods. Please check the SpringTODOController.java source code for reference.
Summary
In this article I demonstrated how Spring application developers can use Spring data for mongoDB support to interact with mongoDB database. There are lot of advanced features in Spring data for mongoDB and it is recommended to refer its documentation.
Download Sample Code
You can download/clone the complete source code for this Part 1 application from its github repository here. | http://books.zkoss.org/wiki/Small_Talks/2012/January/ZK_With_MongoDB_Part_3_-_Using_Spring_Data | CC-MAIN-2015-32 | en | refinedweb |
Figure 1 - First XAML App
Introduction
I finally got to playing around with XAML. I think Microsoft is on the right track here, but they have a way to go. The visual designer is lacking many of the features of the current .NET. There are missing properties in controls, inability to double click on buttons to insert events and other missing features. Also many of the property names changed in controls going from Window Controls in .NET 2.0 to XAML controls in .NET 3.0, so there is definitely a learning curve getting up to speed in XAML. I suspect with the release of "Orcas", many of these inadequacies will be remedied. In the meantime, hold on to your hats, its going to be a bumpy ride!
Installing XAML in Visual Studio 2005
In order to use XAML, in addition to Visual Studio 2005, you need to install the .NET Framework 3.0 redistributable and the Visual Studio 2005 extensions for .NET 3.0 (WPF and WCF). Once you have these installed, you are off and running. You do not need to have VISTA to run .NET 3.0 apps. .NET 3.0 will run on XP with SP2. VISTA just has the added advantage of already having the .NET 3.0 framework installed.
XAML Paradigm
XAML(Extensibility Application Markup Language) allows you to code your controls up in a well formed XML document. (Kinda reminds me of the old rc files in VC++, except with XML tags). Not only can you define properties of your controls in attributes, but you can hookup events into the controls as well using attributes. Below is the XAML text representation for an about box button:
<Button Click="btnAbout_Click" Name="btnAbout" Foreground="#FF0000FF" ToolTip="About Box">About</Button>
The nice thing about XAML is that it is fairly clear from the tags that the element is a button and the attributes Name, Foreground, and ToolTip are easily defined with strings. The Click event is wired to C# using an attribute (note: you still have the option to wire the Click event using the += operator.)
If you want to add an Image to your button, you can embed an child image tag inside your button:
Xaml Windows Project Structure
When you create a new .NET 3.0 Windows Application, the project consists of four files and about a dozen .NET references.
The files are:
App.xamlApp.xaml.csWindow1.xamlWindow1.xaml.cs
The references include the following .NET 3.0 Assembly references:
SystemSystem.DataSystem.XmlWindowsBasePresentationCorePresentationFrameworkUIAutomationProviderUIAutomationTypesReachFrameworkSystem.PrintingSystem.ServiceModelSystem.Runtime.SerializationSystem.IdentityModel
App.xaml is the xaml application file containing the following markup structure
Listing 1 - Application XAML definition
<Application x: <Application.Resources>
</Application.Resources></Application>
This structure defines the name of the application class as well as the starting window for this application (Window1.xaml). Note that everything that was done in code and C# attributes for the Windows application in .NET 2.0 are now done in XML.
Any code that needs to execute is done inside a code-behind partial class under App.xaml.cs. For example, if you wanted to read a database as soon as the app started up, you could do this in the Activation event of the application:
Listing 2 - App.xml to wire up Activation event to event handler App_Activated:
<Application x: <Application.Resources> </Application.Resources></Application>
Listing 3 - App.xml.cs code-behind:
using System;using System.Windows;using System.Data;using System.Xml;using System.Configuration;
namespace WindowsApplication1{ /// <summary> /// Interaction logic for App.xaml /// </summary>
public partial class App : System.Windows.Application { void App_Activated(object sender, EventArgs e) { MessageBox.Show("Read Database."); }
}}
The XAML Window uses the exact same paradigm. Windows controls are contained within the nested tags of the XAML window file. You can put as many controls in here as you want. The designer gives you the ability to drag and drop controls onto a XAML Window and also edit the controls in a XAML text file. In my application I dragged an InkCanvas, a Button, and a Toolbar. The Toolbar resides inside a ToolbarTray control. All the controls are inside a Grid control. The ToolBarTray and Grid control serve as containers for the child controls they hold.
The Button
I wanted my button to act as a way to clear out my InkCanvas, so I can remove the ugly picture I had drawn in the window and attempt to draw a better ugly picture. I had a little trouble at first with my XAML Button on my form. After incessantly clicking the button in the designer and realizing that the event handler code was never going to show up, I went ahead and hooked up the code by hand. I think Microsoft is planning to fix this in "Orcas". To hook up the button, you can either put the event handler wiring in XAML and declare the method in your code as shown in the listing below:
Listing 4 - Wiring a Button to a Button Event Handler in XAML
<Button Click="OnClearButton" Margin="100,0,117,2" Name="button1" Height="23" VerticalAlignment="Bottom">Clear</Button>
void OnClearButton(object sender, RoutedEventArgs e) { inkCanvas1.Strokes.Clear(); }
Or you can wire it the old way using += inside your code behind.
Listing 5 - Wiring a Button to a Button Event Handler in code behind
public Window1() { InitializeComponent(); button1.Click += new RoutedEventHandler(OnClearButton); }
The Toolbar
Adding the ToolBar is a bit more complicated. You need to first add a ToolbarTray to the designer. Then you add the ToolBar inside the ToolBarTray. To add buttons to the ToolBar, you have to add them manually, because the Items collection inside the toolbar doesn't seem to work properly in the designer (again we look forward to "Orcas"). Listing 6 shows the XAML for the toolbar in our sample application. Note that the XAML ToolBar uses the same Button tag as a regular Windows Button.
Listing 6 - XAML Toolbar
<ToolBarTray Height="18" Margin="21,1,24,0" Name="toolBarTray1" VerticalAlignment="Top" > <ToolBar Band="1" BandIndex="1"> <Button IsEnabled ="True"> </Button> <Button Click="btnAbout_Click" Name="btnAbout" Foreground="#FF0000FF" ToolTip="About Box"> <Image Source="about.bmp"></Image> </Button> <Separator/> <Button ToolTip="new file" Name="btnNew">new</Button> <Separator/> <Button> </Button> <Button Name="btnOpen">open</Button> </ToolBar></ToolBarTray>
Also note that in order to create an Image Button, we simply add an Image node as a child node to our button node. The Source attribute tells the button the name of the file in which to get its image.
Conclusion
XAML allows us to express a lot of the visual part of our application in XML. XML is much easier to manipulate than code when it comes to static presentation information. The XAML architecture also allows us to hook our code directly into the XML itself using event tags and code-behind. Hopefully we will see some improvements in the designer in the near future so that it is at least on par with the current Visual Studio 2005 performance. Either way, XAML is the future, so jump in and get your feet wet now with this hot new technology.. | http://www.c-sharpcorner.com/Blogs/143/ | CC-MAIN-2015-32 | en | refinedweb |
Difference between pages "Bash by Example, Part 2" and "User:Xtyangjie" (Difference between pages) Revision as of 12:50, February 25, 2011 (view source)Rh1 (Talk) (→Resources)== More bash programming fundamentals ==+{{Person − +|Full name=YangJie −=== Accepting arguments ===+|Email=xtyangjie@gmail.com −Let's start with a brief tip on handling command-line arguments, and then look at bash's basic programming constructs. +|Nick=xtyangjie − +|Geoloc=40.04894694168396, 116.29540354013443 −In the sample program in the [[Bash by example, Part1|introductory article]], we used the environment variable "$1", which referred to the first command-line argument. Similarly, you can use "$2", "$3", etc. to refer to the second and third arguments passed to your script. Here's an example: +|Location name=北京, 中华人民共和国 −<source lang="bash">+|Roles={{Role −#!/usr/bin/env bash+|Role type=User − +|Role desc=use funtoo as my main work environment −echo name of script is $0+|Start date=2010/05/01 −echo first argument is $1+}} −echo second argument is ${2}+|Maintains= −echo seventeenth argument is ${17}+|Blogs={{Blog −echo number of arguments is $#+|Name=狂想空间 −</source>+|URL=hi.baidu.com/xtyangjie −The.+}} − +}} −Sometimes,. + − + −=== Bash programming constructs ===+ −If. + − + −=== Conditional love ===+ −If "<span style="color:green">$myvar</span> is greater than 4". + − + −The following table lists the most frequently used bash comparison operators. You'll also find an example of how to use every option correctly. The example is meant to be placed immediately after the "if". For example: + −<source lang="bash">+ −if [ -z "$myvar" ]+ −then+ − echo "myvar is not defined"+ −fi+ −</source>+ −Sometimes, there are several different ways that a particular comparison can be made. For example, the following two snippets of code function identically: + −<source lang="bash">+ −if [ "$myvar" -eq 3 ]+ −then + − echo "myvar equals 3"+ −fi+ − + −if [ "$myvar" = "3" ]+ −then+ − echo "myvar equals 3"+ −fi+ −</source>+ −In the above two comparisons do exactly the same thing, but the first uses arithmetic comparison operators, while the second uses string comparison operators. + − + −=== String comparison caveats ===+ −Most: + −<source lang="bash">+ −if [ $+ −[: too many arguments+ −</source>+ −In this case, the spaces in "$myvar" (which equals "foo bar oni") end up confusing bash. After bash expands "$myvar", it ends up with the following comparison: + −<source lang="bash">+ −[ foo bar+ −if [ "$myvar" = "foo bar oni" ]+ −then+ − echo "yes"+ −fi+ −</source>+ −The above code will work as expected and will not create any unpleasant surprises. + − + −{{fancynote|If you want your environment variables to be expanded, you must enclose them in double quotes, rather than single quotes. Single quotes disable variable (as well as history) expansion.}}+ − + −=== Looping constructs: "for" ===+ −OK, we've covered conditionals, now it's time to explore bash looping constructs. We'll start with the standard "for" loop. Here's a basic example: + −<source lang="bash">+ −#!/usr/bin/env bash+ − + −for x in one two three four+ −do+ − echo number $x+ −done+ − + −Output:+ −number one+ −number two + −number three + −number four+ −</source>+ −What: + −<source lang="bash">+ −#!/usr/bin/env bash+ − + −for myfile in /etc/r*+ −do+ − if [ -d "$myfile" ] + − then+ − echo "$myfile (dir)"+ − else+ − echo "$myfile"+ − fi+ −done+ − + −output:+ − + −/etc/rc.d (dir)+ −/etc/resolv.conf+ −/etc/resolv.conf~+ −/etc/rpc+ −</source>+ −The. + − + −We can also use multiple wildcards and even environment variables in the word list: + −<source lang="bash">+ −for x in /etc/r??? /var/lo* /home/drobbins/mystuff/* /tmp/${MYPATH}/*+ −do+ − cp $x /mnt/mydira+ −done+ −</source>+ −Bash will perform wildcard and variable expansion in all the right places, and potentially create a very long word list. + − + −While all of our wildcard expansion examples have used absolute paths, you can also use relative paths, as follows: + −<source lang="bash">+ −for x in ../* mystuff/*+ −do+ − echo $x is a silly file+ −done+ −</source>+ − <span style="color:green">for x in *</span>), the resultant list of files will not be prefixed with any path information. Remember that preceding path information can be stripped using the <span style="color:green">basename</span> executable, as follows: + −<source lang="bash">+ −for x in /var/log/*+ −do+ − echo `basename $x` is a file living in /var/log+ −done+ −</source>+ −Of course, it's often handy to perform loops that operate on a script's command-line arguments. Here's an example of how to use the "$@" variable, introduced at the beginning of this article: + −<source lang="bash">+ −#!/usr/bin/env bash+ − + −for thing in "$@"+ −do+ − echo you typed ${thing}.+ −done+ − + −output:+ − + −$ allargs hello there you silly+ −you typed hello.+ −you typed there.+ −you typed you.+ −you typed silly.+ −</source>+ −=== Shell arithmetic ===+ −Before: + −<source lang="bash">+ −$ echo $(( 100 / 3 ))+ −33+ −$+ −while [ condition ]+ −do+ − statements+ −done+ −</source>+ −"While" statements are typically used to loop a certain number of times, as in the following example, which will loop exactly 10 times: + −<source lang="bash">+ −myvar=0+ −while [ $myvar -ne 10 ]+ −do+ − echo $myvar+ − myvar=$(( $myvar + 1 ))+ −done+ −</source>+ −You can see the use of arithmetic expansion to eventually cause the condition to be false, and the loop to terminate. + − + −"Until" statements provide the inverse functionality of "while" statements: They repeat as long as a particular condition is false. Here's an "until" loop that functions identically to the previous "while" loop: + −<source lang="bash">+ −myvar=0+ −until [ $myvar -eq 10 ]+ −do+ − echo $myvar+ − myvar=$(( $myvar + 1 ))+ −done+ −</source>+ − + −=== Case statements ===+ −"Case" statements are another conditional construct that comes in handy. Here's an example snippet: + −<source lang="bash">+ −case "${x##*.}" in+ − gz)+ − gzunpack ${SROOT}/${x}+ − ;;+ − bz2)+ − bz2unpack ${SROOT}/${x}+ − ;;+ − *)+ − echo "Archive format not recognized."+ − exit+ − ;;+ −esac+ −</source>+ −Above,". + − + −=== Functions and namespaces ===+ −: + −<source lang="bash">+ −tarview() {+ − echo -n "Displaying contents of $1 "+ − if [ ${1##*.} = tar ]+ − then+ − echo "(uncompressed tar)"+ − tar tvf $1+ − elif [ ${1##*.} = gz ]+ − then+ − echo "(gzip-compressed tar)"+ − tar tzvf $1+ − elif [ ${1##*.} = bz2 ]+ − then+ − echo "(bzip2-compressed tar)"+ − cat $1 | bzip2 -d | tar tvf -+ − fi+ −}+ −</source>+ −{{fancynote|Another case: The above code could have been written using a "case" statement. Can you figure out how?}}+ −Above,): + −<pre>+ −$ tarview shorten.tar.gz+ −Displaying contents of shorten.tar.gz (gzip-compressed tar)+ −drwxr-xr-x ajr/abbot 0 1999-02-27 16:17 shorten-2.3a/+ −-rw-r--r-- ajr/abbot 1143 1997-09-04 04:06 shorten-2.3a/Makefile+ −-rw-r--r-- ajr/abbot 1199 1996-02-04 12:24 shorten-2.3a/INSTALL+ −-rw-r--r-- ajr/abbot 839 1996-05-29 00:19 shorten-2.3a/LICENSE+ −....+ −</pre>+ −. + − + −{{fancynote|Use'em interactively: Don't forget that functions, like the one above, can be placed in your ~/.bashrc or ~/.bash_profile so that they are available for use whenever you are in bash.}}+ − + −=== Namespace ===+ −Often,. + − + −While true in C, this isn't true in bash. In bash, whenever you create an environment variable inside a function, it's added to the global namespace. This means that it will overwrite any global variable outside the function, and will continue to exist even after the function exits: + −<source lang="bash">+ −#!/usr/bin/env bash+ − + −+ −#!/usr/bin/env bash+ − + −myvar="hello"+ − + −myfunc() {+ − local x+ − local myvar="one two three"+ − for x in $myvar+ − do+ − echo $x+ − done+ −}+ − + −myfunc+ − + −echo $myvar $x+ −</source>+ −This. + − + −=== Wrapping it up ===+ −Now that we've covered the most essential bash functionality, it's time to look at how to develop an entire application based in bash. In my next installment, we'll do just that. See you then! + − + −== Resources ==+ − + −*Read [[Bash by Example, Part 1]].+ −*Read [[Bash by Example, Part 3]].+ −*Visit [ GNU's bash home page].+ − + −__NOTOC__+ −[[Category:Linux Core Concepts]]+ −[[Category:Articles]]+ Latest revision as of 09:06, May 3, 2013 Contact freenode: xt Retrieved from ‘’ Hidden categories: Pages with a map rendered by the Maps extensionPeople | http://www.funtoo.org/index.php?title=Compiz&diff=2704&oldid=1104 | CC-MAIN-2015-32 | en | refinedweb |
Integrate changes from setuptools trunk
Once a 0.6 release is made and we get a maintenance branch for it, we should look into the changes made on setuptools trunk and apply them again.
I reviewed all the changesets made since the original 0.6 branch was created and found the following changesets which were unique to the trunk.
It seems to be three changes:
- A new test_runner option
- Integration / cleanup work done when Python 2.5 can be required
- Lazy importing of namespace packages
I consider all of these safe to do, though the Python 2.5 changes may need another review or tweaks now.
The full revision log is:
r65966 | phillip.eby | 2008-08-21 23:54:16 +0200 (Thu, 21 Aug 2008) | 3 lines
Added 'test_runner'. (Note: this is a new feature and should not be backported to the 0.6 branch.)
r50921 | phillip.eby | 2006-07-29 01:58:14 +0200 (Sat, 29 Jul 2006) | 2 lines
Sync pkgutil from trunk
r45514 | phillip.eby | 2006-04-18 05:03:16 +0200 (Tue, 18 Apr 2006) | 9 lines
Backport pkgutil, pydoc, and doctest from the 2.5 trunk to setuptools
0.7 trunk. (Sideport?) Setuptools 0.7 will install these in place of
the 2.3/2.4 versions (at least of pydoc and doctest) to let them work
properly with eggs. pkg_resources now depends on the 2.5 pkgutil, which
is included here as _pkgutil, to work around the fact that some system
packagers will install setuptools without overriding the stdlib modules.
But users who install their own setuptools will get them, and the system packaged people probably don't need them.
r45405 | phillip.eby | 2006-04-14 21:38:38 +0200 (Fri, 14 Apr 2006) | 4 lines
First round of prepping setuptools for inclusion in Python 2.5: move site.py to setuptools/site-patch.py; reinstate 'python -m easy_install' support; use distutils' "upload" command when running under 2.5.
r45404 | phillip.eby | 2006-04-14 21:17:37 +0200 (Fri, 14 Apr 2006) | 2 lines
Namespace package doc tweaks.
r45403 | phillip.eby | 2006-04-14 21:13:24 +0200 (Fri, 14 Apr 2006) | 4 lines
Don't eagerly import namespace packages. This was the big reason for branching to 0.7 now, as I wanted this wart gone before anything went into Python 2.5. But it's gone now, yay!
These are really changes not appropriate for the 0.6 branch. As long as we are keeping Python 2.3+ support these cannot go in, as they rely on a minimum requirement of Python 2.5. | https://bitbucket.org/tarek/distribute/issues/14?sort=version&priority=major | CC-MAIN-2015-32 | en | refinedweb |
jGuru Forums
Posted By:
Raj_K
Posted On:
Wednesday, December 11, 2002 02:27 PM
I have properties in my ActionForm which are Arrays and I do not know the size of the array until the Action is executed. How do I implement this. I believe that in struts 1.1, I can use nested tags and indexed properties but how do I do it in struts 1.0? can I use nested forms? is there a way to do it.
Thanks.
Re: Repeating multiple Form Fields using Struts 1.02
Posted By:
Ron_Monson
Posted On:
Friday, December 13, 2002 10:53 AM
package mypackage;import org.apache.struts.action.*;import java.util.List;import java.util.ArrayList;import mypackage.AddressForm;public class PersonForm extends ActionForm{ private List addresses; public AddressForm getAddress(int index) { checkListSize(index, addresses); return addresses.get(index); } public List getAddresses() { if (addresses == null) addresses = new ArrayList(); return addresses; } public void setAddress(int index, AddressForm in) { checkListSize(index, addresses); addresses.set(index, value); } public void setAddresses(List in) { addresses = in; } private void checkListSize(int index, List list) { if (list == null) list = new ArrayList(); try { for (int i = list.size(); i <= index; i++) list.add(i, null); } catch (Exception e) { //Handle exception } } }
checkListSize
, | http://www.jguru.com/forums/view.jsp?EID=1036884 | CC-MAIN-2015-32 | en | refinedweb |
pthread_key_create - thread-specific data key creation
#include <pthread.h> int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
This will stores the newly created key value at *key and returns zero. Otherwise, an error number is returned to indicate the error.
The pthread_key_create() function will will not return an error code of [EINTR].
None.
None.
None.
pthread_getspecific(), pthread_setspecific(), pthread_key_delete(), <pthread.h>.
Derived from the POSIX Threads Extension (1003.1c-1995) | http://pubs.opengroup.org/onlinepubs/7990989775/xsh/pthread_key_create.html | CC-MAIN-2015-32 | en | refinedweb |
Eclipse Community Forums - RDF feed Eclipse Community Forums dynamic jasper osgi bundle <![CDATA[I am trying to use dynamic jasper in virgo, I have not found an osgied dynamicjasper bundle, and when I tried to create one myself using maven-bundle-plugin ( I also tried bundlor but even with less success) that includes jasper reports and dynamic jasper, I keep on getting this error: d:\virgo\DynamicReport_1339161554051_414506.java:4: package net.sf.jasperreports.engine does not exist import net.sf.jasperreports.engine.*; ^ d:\virgo\DynamicReport_1339161554051_414506.java:5: package net.sf.jasperreports.engine.fill does not exist import net.sf.jasperreports.engine.fill.*; ^ d:\virgo\DynamicReport_1339161554051_414506.java:18: cannot find symbol symbol: class JREvaluator public class DynamicReport_1339161554051_414506 extends JREvaluator Is there an existing dynamic jasper bundle in an open repository somewhere? has anyone managed to create such a bundle successfully ? ]]> jacob hameiri 2012-06-08T13:49:24-00:00 Re: dynamic jasper osgi bundle <![CDATA[You might try asking on a jasper mailing list as those with a keen interest in jasper may know of such a bundle.]]> Glyn Normington 2012-06-13T07:29:43-00:00 Re: dynamic jasper osgi bundle <![CDATA[Solved by adding: Import-Bundle: com.springsource.org.apache.commons.digester;version="[1.8.0,2.0.0)"]]> jacob hameiri 2012-06-14T18:15:48-00:00 Re: dynamic jasper osgi bundle <![CDATA[Thanks for reporting back Jacob! Glad you're sorted.]]> Glyn Normington 2012-06-15T09:05:21-00:00 Re: dynamic jasper osgi bundle <![CDATA[Hi jacob hameiri, Do you have the sources of the bundle project to create the DynamicJasper? I'm trying to create this bundle but with any success. Best regards]]> Miguel Salinas Gancedo 2012-10-30T12:43:20-00:00 | http://www.eclipse.org/forums/feed.php?mode=m&th=360024&basic=1 | CC-MAIN-2015-32 | en | refinedweb |
Java SE 8's New Language Features, Part 2: Predefined Functional Interfaces, Method References, and More
- Predefined Functional Interfaces
- Method References
- Enhanced Generic Type Inference / Type Annotations
In Part 1 of this two-part series on new language features in Java 8, I introduced you to interface default and static methods as well as lambda expressions (anonymous methods) and functional interfaces. This article completes the series by introducing you to the java.util.function package of predefined functional interfaces, method (and constructor) references, enhanced generic type inference, and type annotations.
I developed this article's applications with the 64-bit version of JDK 8 build 132 on a Windows 7 platform. You can download the code from this article here.
Predefined Functional Interfaces
In Part 1, I mentioned that lambdas simplify the use of interfaces that declare single abstract methods, and that these interfaces are known as functional interfaces. I presented Runnable as an example of a functional interface located in the standard class library, and I discussed custom Converter and Justifier functional interfaces.
Some kinds of functional interfaces are more commonly used than others. To help you avoid reinventing the wheel by repeatedly introducing the same kind of functional interface, Oracle has added to Java 8 the java.util.function package of commonly used functional interfaces, including the following two examples:
- Predicate<T>: Represent a predicate (Boolean-valued function) of one argument. The lambda must conform to the parameter and return types of this interface's boolean test(T t) single abstract method.
- Consumer<T>: Represent an operation that accepts a single input argument and returns no result. The lambda must conform to the parameter and return types of this interface's void accept(T t) single abstract method. Unlike most of java.util.function's other functional interfaces, Consumer is expected to operate via side-effects.
Listing 1 presents an application that demonstrates Predicate and Consumer.
Listing 1 PCDemo.java
import java.util.function.Consumer; import java.util.function.Predicate; class Salesperson { private String name; private int salary; private int numsales; Salesperson(String name, int salary, int numsales) { this.name = name; this.salary = salary; this.numsales = numsales; } void addBonus(int amount) { salary += amount; } int getNumSales() { return numsales; } @Override public String toString() { return "name: " + name + ", salary: " + salary + ", numsales: " + numsales; } } public class PCDemo { public static void main(String[] args) { Salesperson[] salespersons = { new Salesperson("John Doe", 40000, 549), new Salesperson("Jane Doe", 39000, 1500) }; for (Salesperson salesperson: salespersons) { applyBonus(salesperson, salesperson_ -> salesperson_.getNumSales() > 1000, salesperson_ -> salesperson_.addBonus(2500)); System.out.println(salesperson); } } public static void applyBonus(Salesperson salesperson, Predicate<Salesperson> predicate, Consumer<Salesperson> consumer) { // Use predicate to determine whether or not to add bonus. // Use consumer to add the bonus if (predicate.test(salesperson)) consumer.accept(salesperson); } }
Listing 1 presents a Salesperson class that describes a salesperson in terms of name, salary, and number of sales. Along with a constructor, this class presents methods for adding a bonus (presumably based on number of sales exceeding a threshold), returning the number of sales, and returning a string representation of a Salesperson instance.
The PCDemo class in Listing 1 demonstrates the Predicate and Consumer functional interfaces. This class provides a main() method that creates an array of two Salesperson instances and iterates over this array to apply a bonus to eligible salespersons. PCDemo also provides an applyBonus() method.
The applyBonus() method is declared with three parameters having Salesperson, Predicate<Salesperson>, and Consumer<Salesperson> types. Arguments are passed to the final two parameters via lambdas whose compiler-inferred target types match these parameter types. (Each lambda's formal type parameter list specifies salesperson_ instead of salesperson because a formal type parameter list cannot introduce a new local variable with the same name as an existing variable in the enclosing scope.)
Consider predicate lambda salesperson_ -> salesperson_.getNumSales() > 1000. This lambda matches the Predicate<T> (with a Salesperson actual type argument) functional interface's boolean test(T t) single abstract method parameter and return types. Similarly, consumer lambda salesperson_ -> salesperson_.addBonus(2500) matches the Consumer<T> (with a Salesperson actual type argument) functional interface's void accept(T t) single abstract method parameter and return types.
When applyBonus() is invoked, the current salesPerson instance is passed to this method as its first argument. Furthermore, an instance of an implementation of the Predicate<Salesperson> functional interface that executes salesperson_.getNumSales() > 1000 is passed to this method as its second argument, and an instance of an implementation of the Consumer<Salesperson> functional interface that executes salesperson_.addBonus(2500) is passed to this method as its third argument.
Within applyBonus(), if (predicate.test(salesperson)) executes the predicate instance's test() method, which has been implemented to execute return salesperson.getNumSales() > 1000;, with applyBonus()'s salesperson argument. If test() returns true, consumer.accept(salesperson); executes, which has been implemented to execute salesperson.addBonus(2500);. The bonus is added to the salesperson who achieved more than 1000 sales.
Compile Listing 1 as follows:
javac PCDemo.java
Run the PCDemo application as follows:
java PCDemo
You should observe the following output:
name: John Doe, salary: 40000, numsales: 549 name: Jane Doe, salary: 41500, numsales: 1500 | http://www.informit.com/articles/article.aspx?p=2191424 | CC-MAIN-2015-32 | en | refinedweb |
SETMODE(3) BSD Programmer's Manual SETMODE(3)
getmode, setmode - modify mode bits
#include <unistd.h> mode_t getmode(const void *set, mode_t mode); void * setmode(const char *mode_str);
The getmode() function returns a copy of the file permission bits mode as altered by the values pointed to by set. While only the mode bits are al- tered, other parts of the file mode may be examined. The setmode() function takes an absolute (octal) or symbolic value, as described in chmod(1), as an argument and returns a pointer to mode values to be supplied to getmode(). Because some of the symbolic values are relative to the file creation mask, setmode() may call umask(2). If this occurs, the file creation mask will be restored before setmode() re- turns. If the calling program changes the value of its file creation mask after calling setmode(), setmode() must be called again if getmode() is to modify future file modes correctly. If the mode passed to setmode() is invalid, setmode() returns NULL. The caller is responsible for freeing the pointer that setmode() returns.
The setmode() function may fail and set errno for any of the errors specified for the library routine malloc(3) or to ERANGE if an invalid octal value was specified.
chmod(1), stat(2), umask(2), malloc(3)
The getmode() and setmode() functions first appeared in 4.4BSD.. | http://www.mirbsd.org/htman/sparc/man3/getmode.htm | CC-MAIN-2015-32 | en | refinedweb |
TimerService startup issue in JBoss AS 6Abdur Rahman Apr 12, 2012 7:12 AM
I am using JBoss AS 6. I have created a timer service listed bellow:
package com.mycompany.infrastructure.notification.service;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.Timer;
@Stateless
public class NotificationTimerService {
@Schedule(second = "*/30", minute = "*", hour = "*", dayOfWeek = "*", timezone = "GMT")
public void executeSomeMethod(Timer timer) {
System.out.println("Invoking daily event notification ...");
/ / call some session bean here
}
}
Issues:
1. When I restart jboss server the timer service starts execution before the conatainer/application is loaded completely. I want it start execution onces all the session beans (and other classes) are loaded.
2. It executes all the previous invocations that were missed when jboss server was offline. I want it ignore missing calls due to offline mode.
Thanks.
1. Re: TimerService startup issue in JBoss AS 6Wolf-Dieter Fink Apr 12, 2012 9:07 AM (in response to Abdur Rahman)
You should inject the reference to other session beans via @EJB instead of lookup it,this should set a dependency.
The @Schedule timer event is catch up all missing events if it is persistent (by default). If you don't want that behaviour you should set @Schedule(... persistent=false) this will avoid any catch up as long as the bean is down.
2. Re: TimerService startup issue in JBoss AS 6Abdur Rahman Apr 12, 2012 10:44 AM (in response to Wolf-Dieter Fink)
Thanks, This resolved the startup issue.
1. About setting persistent=false, Will turning persistent off guaranty a single invocation at a particular interval in a clustered environment (multiple jboss instances)?
2. I have also noticed receiving multiple invocations on single JVM at a specific interval. Can you guide about this too? Sorry for asking in the same thread.
3. Re: TimerService startup issue in JBoss AS 6Wolf-Dieter Fink Apr 12, 2012 10:51 AM (in response to Abdur Rahman)
1.
Nevertheless how persistence is set, the schedule is per instance. That mean if you deploy the application in a cluster with X nodes the bean is called X-times
This is still the same as in former versions and still an issue (there are JIRA enhancements).
A naive expectation is that it is a unique application event in a cluster, but it isn't the EJB spec does not specify the behaviour in a cluster.
2.
Can you explain a bit more, I don't understand what you meant ...
4. Re: TimerService startup issue in JBoss AS 6Abdur Rahman Apr 12, 2012 12:11 PM (in response to Wolf-Dieter Fink)
I mean the executeSomeMethod(Timer timer) is invoked multiple times after every 30 seconds. Thanks.
5. Re: TimerService startup issue in JBoss AS 6Wolf-Dieter Fink Apr 12, 2012 12:20 PM (in response to Abdur Rahman)
Oh, ok
that smell like a solved bug (in AS7) with persistence=true.
You should stop the server and remove all entries from the timers database or even drop the TIMERS tables. | https://community.jboss.org/message/729649 | CC-MAIN-2015-32 | en | refinedweb |
Clear-RemoteAccessInboxAccountingStore
Clear-RemoteAccessInboxAccountingStore
Syntax
Detailed Description
The Clear-RemoteAccessInboxAccountingStore cmdlet clears the inbox accounting store for the specified time period.
The store for inbox accounting resides locally on every Remote Access server and the clearing operation happens at the server level. Therefore this cmdlet is not impacted by a multi-site deployment.
Note: If neither a start date nor an end date is specified, then the entire inbox accounting store is cleared.
When a store is cleared more space becomes available to record accounting data.
This cmdlet can be used to clear portions of the store even if inbox accounting is Disabled. This is because the store exists even when inbox accounting is later disabled.. When this parameter is specified the store residing on that Remote Access server is cleared.
-EndDateTime<DateTime>
Specifies the time duration for which the store should be emptied and indicates the end date. If no start date is specified, then the time stamp of the last record entry in the accounting store is used by default.
-Force
Forces the command to run without asking for user confirmation.
When this parameter is specified, the cmdlet assumes user confirmation for the clearing of the store.
-PassThru
Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output.
-StartDateTime<DateTime>
Specifies the time duration for which the store should be emptied and indicates the start date. If no start date is specified, then the time stamp of the first record entry in the accounting store is used by#RemoteAccessInboxAccounting
The
Microsoft.Management.Infrastructure.CimInstanceobject is a wrapper class that displays Windows Management Instrumentation (WMI) objects. The path after the pound sign (
#) provides the namespace and class name for the underlying WMI object.
The RemoteAccessInboxAccounting object consists of the following properties:
-- Status of inbox accounting (Enabled or Disabled).
-- Time span of the store.
-- Number of used bytes.
-- Percentage of used bytes.
-- Number of free bytes.
-- Percentage of free bytes.
-- Time stamp of the first record in the database.
-- Time stamp of the last record in the database.
Examples
EXAMPLE 1
This example deletes the data between the specific dates provided. The remaining data will be preserved.
EXAMPLE 2
This example clears the accounting store and removes all data.
Related topics | https://technet.microsoft.com/en-us/library/hh918429.aspx | CC-MAIN-2015-32 | en | refinedweb |
Frees a Slapi_Mutex structure from memory.
#include "slapi-plugin.h" void slapi_destroy_mutex( Slapi_Mutex *mutex );
This function takes the following parameters:
Pointer to the Slapi_Mutex structure that you want to free from memory.
This function frees a Slapi_Mutex structure from memory. The calling function must ensure that no thread is currently in a lock-specific function. Locks do not provide self-referential protection against deletion. | http://docs.oracle.com/cd/E19528-01/820-2492/aaifb/index.html | CC-MAIN-2015-32 | en | refinedweb |
Author: Ken Cochrane Fork of: Fork Description: I reorganized the code, added caching, and made a few tweaks here and there. Description: Django middleware and view decorator to detect phones and small-screen devices Version: 0.1.6 Last Update: 9/30/2011
Requirements:
Django 1.1 or newer Django caching to be enabled if you want to cache the objects
How to use:
Using django-mobi is very simple. Simply place the mobi package into your project's path, and then do one of the following:
Using the mobi.MobileDetectionMiddleware Middleware
This middleware will scan all incoming requests to see if it is a mobile device. If it is it will set the request.mobile property to True.
To use all you have to do is add mobi.MobileDetectionMiddleware to your MIDDLEWARE_CLASSES tuple in your settings.py
Then in your view you can check request.mobile - if it's True then treat it like a small screen device. If it's False then it's probably a desktop browser, or a spider or something else.
If you want to have some items not triggered by the middleware (for example iPad) then add a settings called MOBI_USER_AGENT_IGNORE_LIST and add the item to the list.
MOBI_USER_AGENT_IGNORE_LIST = ['ipad',]
Using the mobi.MobileRedirectMiddleware Middleware
This middleware will scan all incoming requests to see if it is a mobile device, if so it will redirect the request to a different URL. This is good if you want to force all mobile traffic to a mobile only version of your site.
To use all you have to do is add mobi.MobileRedirectMiddleware to your MIDDLEWARE_CLASSES tuple in your settings.py, and also add MOBI_REDIRECT_URL = "" where is the website you want to redirect all mobile traffic.
Not using the Middleware
If you only have certain views that need the distinction, you can choose not to search every request you receive. All you need to do is wrap the relevant views like this:
from mobi.decorators import detect_mobile
@detect_mobile def my_mobile_view(request):
- if request.mobile:
- #do something with mobile | https://bitbucket.org/kencochrane/django-mobi/src/51cf1cb09961/?at=default | CC-MAIN-2015-32 | en | refinedweb |
If you are considering inheritance there is another access modifier – sealed. If you apply the sealed modifier to a class then the class cannot be used as a base class for a new class. Many programmers think that sealed is a great idea because they don't want to make a gift of their class to use as the basis for something new – but software reuse is the basis of the object-oriented method and using sealed breaks this. Just like private and protected, sealed is not a code security measure – it is easy enough to decompile a sealed class.
That is if you define two classes as:
public sealed class MyClass1 { void MyMethod1(){} } public class MyClass2 : MyClass1 { }
You will see a compile time error saying that you cannot derive from a sealed type.
Many, perhaps most, of the classes that make up the .NET framework are sealed and this is a mistake as it causes many a programmer to have to reinvent the wheel when a derived class would be the simplest way of creating something that does the job.
Notice that you can add new behaviour to any class using extension methods but this isn't as powerful or elegant as using inheritance.
The only good reason for using sealed is if the class you have just created contains something low level that would most likely break a class that extended them – however it is difficult to find any really convincing example. Even so some programmers, and the .NET design team in particular, take the attitude that all of their public classes should be marked as sealed.
You could then ask why C# supports inheritance at all if every class has inheritance turned off? Indeed as discussed in the introduction many programmers are of the opinion that inheritance is not the best way to reuse code. Interface inheritance and composition, for example, are design alternatives to inheritance that are simpler to manage.
It is also argued that allowing classes that are in the framework to be extended is inviting misuse and hence bugs that would bring the entire system into disrepute. The effort needed to create classes that can be safely extended by inheritance in a manner that stops the inexperienced from doing damage is just too much. Far better to have a library of code that can be used in a narrow, well-defined, way with a high degree of confidence that the code does exactly what it claims to.
Another reason for sealing a class is that it permits the compiler to perform optimisations by making all of the methods non-virtual. So using sealed as a default option is easy, safe and rewarding - to the class implementer not as much the class consumer.
On the other hand if the code doesn't quite do what you want, it isn't quite complete, and adding some additional methods and properties would make it just right then to discover that the class is sealed is annoying. The only solutions to the problem involves a lot of work. You can recreate the code for the base class and then extend it – a task that is relatively easy if you have the source code of the base class. Even if you are able to implement a copy and paste form of source code inheritance you have made the system more error prone by there being two copies of essentially the same code.
A better approach is to use object composition or containment. Simply create the object that needs to be extended as an object property of a new class and then provide methods that that mirror the methods of the contained class and which simply call the contained class's methods. Because the containing class's methods call the contained class's methods to get things done this is also called the delegation pattern.
For example if you have the class:
public sealed class MyClass1{ public void MyMethod1() { Console.WriteLine("Method1"); } }
then it can be extended using containment:
public class MyClass2{ private MyClass1 MyContained= new MyClass1(); void MyMethod1() { MyContained.MyMethod1(); }}
In a more complex case you would have to add methods and properties corresponding to all of the methods and properties exposed as public by the contained class – and this could be a lot of work.
You can also make use of a constructor to create the contained class and this opens up the possibility of dynamically selecting the class to be contained.
There is also the lazy way of achieving containment – to allow the contained object to be public. For example:
public class MyClass2{ public MyClass1 MyContained= new MyClass1(); void MyMethod1() { MyContained.MyMethod1(); }}
With this change you no longer have to implement methods and properties to re-expose the contained class's members you simply have to use a double qualified name as in:
MyClass2 myObj = new MyClass2();myObj.MyContained.MyMethod1();
The disadvantages of this approach are fairly obvious and if you really want to create a new class that looks and behaves in a similar way to an existing class then simply making the contained class public isn't good enough.
All of this seems like a lot of trouble to go to just to defeat "sealed". Indeed many of the approaches are reinventions of types of programming that inheritance was supposed to replace. The key issue is that with a sealed class there can be no new classes in the type hierarchy that derive from it and as such no complications with polymorphism and references can always be resolved at compile time.
There is a second and less well known use of the sealed modifier. You can use sealed on a method that overrides a virtual method. This stops the chain of overriding of virtual methods at the first derived class that applies sealed. For example given the class:
public class MyClass1{ public virtual void MyMethod1() { Console.WriteLine("Method1"); }}
then a derived class can override the virtual method:
public class MyClass2:MyClass1{ public sealed override void MyMethod1() { Console.WriteLine("Method1"); }}
but, as the sealed modifier has been applied, a class derived from MyClass2 cannot override MyMethod1.
Of course, if you want to stop the chain of virtual overriding at the first class, e.g. MyClass1, simply don't declare the method as virtual!
<ASIN:1590598733>
<ASIN:0672330164> | http://i-programmer.info/ebooks/deep-c/559-chapter-five.html?start=2 | CC-MAIN-2015-32 | en | refinedweb |
/* ** (c) COPYRIGHT MIT 1995. ** Please first read the full copyright statement in the file COPYRIGH. */
Chunked transfer encoding and decoding is new in HTTP/1.1. It allows applications to use persistent connections while not knowing the content length a priori to the response header is generated.
Both the encoder and the decoder are of type HTCoder which is defined in the Stream Pipe Builder. This means that bot the encoder and the decoder are registered dynamically and called by the Stream Pipe Builder if required.
Note: These streams are not set up by default. They must be
registered by the application. You can use the default initialization function
HTEncoderInit() function in the
initialization interface.
This module is implemented by HTTChunk.c, and it is a part of the W3C Sample Code Library.
#ifndef HTTCHUNK_H #define HTTCHUNK_H #include "HTFormat.h"
extern HTCoder HTChunkedDecoder, HTChunkedEncoder;
#endif /* HTTCHUNK_H */ | http://www.w3.org/Library/src/HTTChunk.html | CC-MAIN-2015-32 | en | refinedweb |
Difference between revisions of "CRV2 SessionHandling"
Revision as of 15:42, 31 May 2014
- 1 Session Management
- 1.1 Recommendation: Require cookies.
- 1.2 Custom Session frameworks
- 1.3 Session Expiration
- 1.4 Session Logout/Ending.
- 1.5 Session Attacks
- 1.6 Session Hijacking
- 1.7 Session Fixation
- 1.8 Session Elevation
- 1.9 Server-Side Defenses for Session Management.
Session Management
A web session is a sequence of network HTTP request and response transactions associated to the same user. Session management or state is needed by web applications that.
Code reviewer needs to understand what session techniques the developers used, and how to spot vulnerabilities that may create potential security risks..
The session ID or token binds the user authentication credentials (in the form of a user session) to the user HTTP traffic and the appropriate access controls enforced by the web application. The complexity of these three components (authentication, session management, and access control) in modern web applications, plus the fact that its implementation and binding resides on the web developer’s hands (as web development framework do not provide strict relationships between these modules), makes the implementation of a secure session management module very challenging..
With the goal of implementing secure session IDs, the generation of identifiers (IDs or tokens) must meet the following properties:
- The name used by the session ID should not be extremely descriptive nor offer unnecessary details about the purpose and meaning of the ID.
- It is recommended to change the default session ID name of the web development framework to a generic name, such as “id”.
- The session ID length must be at least 128 bits (16 bytes) (The session ID value must provide at least 64 bits of entropy).
- The session ID content (or value) must be meaningless to prevent information disclosure attacks, where an attacker is able to decode the contents of the ID and extract details of the user, the session, or the inner workings of the web application.
- It is recommended to create cryptographically strong session IDs through the usage of cryptographic hash functions such as SHA1 (160 bits).
Require cookies when your application includes authentication. Code reviewer needs to understand what information is stored in the application cookies. Risk management is needed to address if sensitive information is stored in the cookie requiring SSL for the cookie
.Net ASPX
The following example shows how to specify in the Web.config file that Forms Authentication requires a cookie that is transmitted over SSL.
<authentication mode="Forms"> <forms loginUrl="member_login.aspx" cookieless="UseCookies" requireSSL="true" path="/MyApplication" /> </authentication>
The ASP.NET session identifier is a randomly generated number encoded into a 24-character string consisting of lowercase characters from a to z and numbers from 0 to 5.
The SessionID value by default is sent in a cookie with each request to the ASP.NET application.
Custom Session frameworks.
This code shows a developer who is replacing the default session management in .Net with his own custom class. The secure code reviewer needs to understand why a custom session class is being used and if if a risk assessment has been done on the custom session management class.
.Net ASPX
<httpModules> <remove name="SessionID" /> <add name="SessionID" type="Samples.AspNet.Session.GuidSessionIDManager" /> </httpModules>
Session Expiration
In review session handling code the reviewer needs to understand what expiration timeouts are needed by the web application or if default session timeout are being used. Insufficient session expiration by the web application increases the exposure of other session-based attacks, as for the attacker to be able to reuse a valid session ID and hijack the associated session, it must still be active. Remember for secure coding one of our goals is to reduce the attack surface of our application.
.Net ASPX
ASPX the developer can change the default time out for a session. This code in the web.config file sets the timeout session to 15 minutes. The default timeout for a aspx session is 30 minutes.
<configuration> <system.web> <sessionState mode="InProc" cookieless="true" timeout="15" /> </system.web> </configuration>
Session Logout/Ending.
Web applications should provide mechanisms that allow security aware users to actively close their session once they have finished using the web application.
.Net ASPX Session.Abandon() method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out. You should use it when the user logs out. Session.Clear() Removes all keys and values from the session. Does not change session ID. Use this command if you if you don't want the user to relogin and reset all the session specific data.
Session Attacks
Generally three sorts of session attacks are possible:
- Session Hijacking: stealing someone's session-id, and using it to impersonate that user.
- Session Fixation: setting someone's session-id to a predefined value, and impersonating them using that known value
- Session Elevation: when the importance of a session is changed, but its ID is not.
Session Hijacking
- Mostly done via XSS attacks, mostly can be prevented by HTTP-Only session cookies (unless Javascript code requires access to them).
- (charly proposes to eliminate this...) It's generally a good idea for Javascript not to need access to session cookies, as preventing all flavors of XSS is usually the toughest part of hardening a system.
- Session-ids should be placed inside cookies, and not in URLs. URL informations are stored in browser's history, and HTTP Referrers, and can be accessed by attackers.
- (...and add this) As cookies can be accessed by default from javascript and preventing all flavors of XSS is usually the toughest part of hardening a system, there is an attribute called "HTTPOnly", that forbids this access. The session cookie should has this attribute set. Anyway, as there is no need to access a session cookie from the client, you should get suspicious about client side code that depends on this access.
- Geographical location checking can help detect simple hijacking scenarios. Advanced hijackers use the same IP (or range) of the victim.
- An active session should be warned when it is accessed from another location.
- An active users should be warned when s/he has an active session somewhere else (if the policy allows multiple sessions for a single user).
Session Fixation
- If the application sees a new session-id that is not present in the pool, it should be rejected and a new session-id should be advertised. This is the sole method to prevent fixation.
- All the session-ids should be generated by the application, and then stored in a pool to be checked later for. Application is the sole authority for session generation.
Session Elevation
- Whenever a session is elevated (login, logout, certain authorization), it should be rolled.
- Many applications create sessions for visitors as well (and not just authenticated users). They should definitely roll the session on elevation, because the user expects the application to treat them securely after they login.
- When a down-elevation occurs, the session information regarding the higher level should be flushed.
- Sessions should be rolled when they are elevated. Rolling means that the session-id should be changed, and the session information should be transferred to the new id.
Server-Side Defenses for Session Management.
.NET ASPX
Generate a new session ID
Generating new session Id's helps prevent, session rolling, fixation, hijacking.
public class GuidSessionIDManager : SessionIDManager { public override string CreateSessionID(HttpContext context){ return Guid.NewGuid().ToString(); } public override bool Validate(string id) { try{ Guid testGuid = new Guid(id); if (id == testGuid.ToString()) return true; }catch(Exception e) { throw e } return false; } } | https://www.owasp.org/index.php?title=CRV2_SessionHandling&diff=prev&oldid=176127 | CC-MAIN-2015-32 | en | refinedweb |
.
I have been using various ways to implement logging when was that required in an ASP.Net application. I used the Enterprise Library Logging Application Block but only recently I discovered how easy and flexible Log4Net is.It is very easy to use, well documented and open source (Apache Software Foundation). I will create a very simple example where I open a connection to a database and print on the screen a simple message, if the connection was opened successfully or not. At the same time I will log various information to a text file. folder inside the App_Code special folder and name it DataAccess.>. Ιn my case it like the one below. In your case you must set the Data Source property to your SQL server instance.
) In the Default.aspx page add a Label control. Leave the default name.
8) Do not forget to add this line of code in the top of the Default.aspx.cs file
using System.Data.SqlClient;using System.Data.SqlClient;
9) We need to add the Log4Net assembly to our website.I will use VS to add this assembly to our website. From visual studio Tools –> Library Package Manager –> Manage NuGet Packages… In Manage NuGet Packages… windows, search Log4Net then install log4net package to your project.The log4net.dll will be added to the Bin folder.Have a look at the picture below
10) Add a new item to your application, a Global.asax file.In the Application_Start() type
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup log4net.Config.XmlConfigurator.Configure(); }
We initialise log4net at application start up.
11) We need to make changes to the web.config file.I provide the information where log4net configuration parameters are defined.
In the configSections type the following
<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/> </configSections>
Now we need to add more settings in the web.config regarding the LogFileAppender and the path to the actual log file. Type the following in the web.config file
>
The complete web.config follows.
<?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit --> <configuration> <configSections> <section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/> </configSections> <connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind; Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> > <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> </configuration>
12) In the Page_Load event handling routine of the Default.aspx page type
protected void Page_Load(object sender, EventArgs e) { log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default)); if (!IsPostBack) { Label1.Text = "We will test the connection to the database."; try { logger.Info("Open Connection "); SqlConnection connection = Connection.GetDBConnection(); connection.Close(); Label1.Text = "We opened and closed the connection to the database"; logger.Info("We opened and closed the connection to the database"); } catch (SqlException ex) { Label1.Text = "We cannot connect to the database" + ex.Message; logger.Error("Error in opening the connection"); } } }
The code is very easy to understand. We create an instance of the log4net object and use the Info and Error methods to log the information to the text file.
Do not forget to add this line of code
using log4net;
13) Run your application and then have a look at the test.log file.Have a look in the picture below to see what was logged when I run the example
I ran the application the first time and everything was successful and the information I wanted was logged.The second time I intentionally changed the connection string to point to a non-existing SQL Server instance and then run again the application.This time the error message was logged in the log file.
Hope it helps!!! | http://weblogs.asp.net/dotnetstories/using-log4net-in-an-asp-net-application | CC-MAIN-2015-32 | en | refinedweb |
Distributed Cache On Steroids: Amazon ElastiCache
Web applications can often be made to perform better and run faster by caching critical pieces of data in memory. Frequently accessed data, results of time-consuming/expensive database queries, search results, session data and results of complex calculations are usually very good candidates for cache storage. We will understand basics of caching post which we will deep dive in Amazon ElastiCache
Types of Caching Architectures
Local In-Memory Caching
The Cache objects are stored locally in-memory (example Java Heap) of the application servers. Open source frameworks like EHCache, OSCache can be used inside Java Application Servers for serving cached items from the heap. Since the cache items are accessed from the same process heap of the application programs, this model offers very fast “Set/Get” operations for cache items. On the other hand because of the limited nature of RAM only few GB can be cached in the Local In-Memory Caching model.
Network Attached Caching
The Cache objects are stored in a separate Cache Server accessible over TCP network. Cache Clients or Cache Drivers need to be embedded on the Application Servers which enable the GET/PUT/Sync operations. Cache behaves like a network attached RAM. Terracotta Cache is an example of network attached RAM caching. Since the cache operations need to travel over the network, few milliseconds of latency can be felt on “Set/Get” operations. Since the cache is centralized and consolidated it is easy manage, extend and maintain this tier.
Distributed Caching
Distributed caching may run on multiple cache servers so that it can grow in size and in transactional capacity. It is mainly used to store application data residing in database and web session data. The web applications may access the distributed cache deployed locally or remotely using a client library. The most popular distributed caching software is Memcached. Deploying large farms of Memcached has become possible because memory is affordable and cheap now and networks have become very fast. Distributed cache works well on low cost commodity machines and cloud providers. One such popular distributed cache on AWS we are going to discuss in this article is Amazon ElastiCache.
Introducing Amazon ElastiCache:
Amazon ElastiCache is a managed distributed caching service provided by Amazon Web services. Amazon ElastiCache currently uses memcached as the caching engine, so memcached compatible programs can be easily ported to Amazon ElastiCache usually without code change. With Amazon ElastiCache operating as a separate tier, AWS team offloads typical cache tier management tasks like the ones listed below from the application and infrastructure teams of the customer:
- Managing the work involved in setting up a distributed in-memory cache tier
- Provisioning the server resources you request to installing the caching software
- Common administrative tasks such as failure detection, recovery and software patching
- Adding / removing Cache nodes from the cluster
Now lets us explore in detail the major components of Amazon ElastiCache.
Components of Amazon ElastiCache
Amazon ElastiCache node:
Amazon ElastiCache node is a memcached instance with a unique endpoint URL and port. You can configure the memcached configuration file used by the popular memcached clients with this endpoint URL(s) provided. Memcached clients are available for all popular programming languages and the latest list can be found here. Amazon ElastiCache nodes are protocol compliant with memcached server and usually the same memcached client mentioned above can be switched to Amazon ElastiCache nodes without requiring code changes. You can use standard Memcached operations like get, set, incr and decr in exactly the same way as you would in your existing Memcached deployments and as well perform requests using both Binary and Text messages over TCP protocol.
A sample pseudo code illustrating SET operation in Text TCP protocol using Java SpymemcachedTextTCPSet { public void setTextValue() throws IOException { MemcachedClient memcachedClient = new MemcachedClient( new DefaultConnectionFactory(),AddrUtil.getAddresses("ecache1a.sqjbuo.0001.use1.cache.amazonaws.com:11211")); String key = "1000002"; String value = "1000002-Test value in Text"; Integer expires = Integer.parseInt("1000"); try { Future<Boolean> result = memcachedClient.set(key, expires, value); ………… ………… } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } memcachedClient.shutdown(); } }
A sample program illustrating GET operation in Text TCP protocol using Java Spymemcached library and Amazon ElastiCache Tier:
import java.io.IOException; import net.spy.memcached.AddrUtil; import net.spy.memcached.ConnectionFactory; import net.spy.memcached.DefaultConnectionFactory; import net.spy.memcached.HashAlgorithm; import net.spy.memcached.MemcachedClient; import java.util.*; public class ElastiCacheTextTCPGet { public void getTextValue() throws Exception { MemcachedClient memcachedClient = new MemcachedClient( new DefaultConnectionFactory(),AddrUtil.getAddresses("ecache1a.sqjbuo.0001.use1.cache.amazonaws.com:11211")); String key = "1000002"; Object obj=null; try { obj = memcachedClient.get(key); System.out.println("Value = :"+obj.toString()); } catch (Exception e) { e.printStackTrace(); } memcachedClient.shutdown(); } }
You can also communicate with Amazon ElastiCache using Binary protocol of Memcached. A sample program illustrating SET operation using Java Spymemcached-TCP Binary Protocol and Amazon ElastiCache Tier:
import java.io.IOException; import java.util.concurrent.ExecutionException; import net.spy.memcached.AddrUtil; import net.spy.memcached.DefaultConnectionFactory; import net.spy.memcached.BinaryConnectionFactory; import net.spy.memcached.MemcachedClient; import net.spy.memcached.*; import java.util.*; public class ElastiCacheBinaryTCPSet { public void setBinaryValue() throws Exception { MemcachedClient memcachedClient = new MemcachedClient( new BinaryConnectionFactory(),AddrUtil.getAddresses("ecache1a.sqjbuo.0001.use1.cache.amazonaws.com:11211")); String key = "1000004"; String value = "1000004-Test value in Binary-TCP protocol"; Integer expires = Integer.parseInt("1000"); try { Future<Boolean> result = memcachedClient.set(key, expires, value); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } memcachedClient.shutdown(); } }
Memcached software version 1.4.5 is used as the cache engine in the Amazon ElastiCache nodes. Cache nodes accept connections on port 11211 and only for Amazon EC2 network. In order to allow network requests to your Cache Nodes from web/application EC2 instances, you will need to authorize access in AWS security groups. Amazon ElastiCache provides variety of cache node types (capacities) and pricing models to suit the customer requirements. The latest cache node type information can be found here
Amazon ElastiCache Cluster:
An Amazon ElastiCache Cluster is a collection of one or more Amazon ElastiCache Nodes. All Cache Nodes within a Cache Cluster will be of the same Node Type (capacity). A node type is an associated memory size of the cache nodes to be deployed in your cache cluster. Currently cache nodes come in 11 different capacities in AWS to suit a variety of your needs, new capacity types will be added by AWS in future. If you need cache nodes of different capacities in your application systems you need to create multiple cache clusters in your account. The Cache Cluster should be supplied with an Identifier name by the customer during its creation process. For example: if you give a name “ecache1a” for the cache cluster, the endpoint URL of a particular cache node may look like this ecache1a.sqjbuo.0001.use1.cache.amazonaws.com:11211.This name identifies a particular Cache Cluster when interacting with the Amazon ElastiCache API and commands. The Cache Cluster Identifier must be unique for that customer in an AWS region.
While configuring a cluster you need to mention the availability zone in in which you would prefer to deploy your Cache Cluster. Currently a single Amazon ElastiCache Cluster cannot span multiple Availability zones inside an Amazon EC2 region. It is advised to keep the cache cluster and related web/application ec2 instances in the same Availability zone for better latency. Refer here for common Amazon ElastiCache deployment architectures in AWS infrastructure. Parameters and Security group settings of all the nodes inside the Amazon ElastiCache cluster can be grouped and controlled at cluster level. This clustering/grouping of cache nodes helps in easy management and maintenance of huge farms of cache nodes. Amazon ElastiCache Clusters are can be created, using the AWS Management Console, Amazon ElastiCache APIs, or Command Line Tools. In addition to the above you can specify whether you would like to receive SNS notifications related to your cache nodes/cluster using Amazon Simple Notification Service (SNS) system. You can either select an existing SNS topic or disable notifications completely as well for the entire Amazon ElastiCache Cluster.
Amazon ElastiCache Parameter Group:
Amazon ElastiCache Parameter Groups allows you to control the runtime parameters and cache engine configuration values of your Nodes. The values configured will get passed to memcached nodes during startup and gets applied to all the nodes associated in the Amazon ElastiCache Cluster. If you do not specify a Cache Parameter Group for your Cache Cluster, then a default Cache Parameter Group (default.memcached1.4) will be used. Usually the default parameter group contains engine defaults and Amazon ElastiCache system defaults optimized for the Cache Cluster nodes you are running. Since Amazon ElastiCache by default chooses the optimal configuration parameters for your Cache Cluster taking into account the Node Type’s memory/compute resource capacity, it does not require change for most use cases. However, if you want your Cache Cluster to run with your custom configuration values, you can simply create a new Cache Parameter Group, modify the desired parameters and use it for new or existing clusters. In event the custom parameter group is applied to running cache cluster the changes will not be applied to the Cache Nodes until the Cache Cluster is rebooted.
Amazon ElastiCache Security Group:
An Amazon ElastiCache Security Group acts like a firewall, controlling network access to your Cache Cluster. Since IP-range based access control is currently not enabled for Amazon ElastiCache Clusters, All clients to a Cache Cluster must be within the EC2 network and authorized via security groups. If you want your Web application EC2 instances to access your Cache Cluster, you must explicitly enable access from hosts in their specific EC2 security groups. For example: To allow network access to your Cache Cluster, you first need to create a Cache Security Group and link the desired EC2 security groups (which in turn specify the EC2 instances allowed) to it.
What features Amazon ElastiCache offers over MemCached on EC2
Operation 1: Modification of Cache Cluster
An Amazon ElastiCache cluster can be modified anytime. Properties like Cache Security group, Cache Parameter group, Maintenance window period, SNS notifications and Auto Minor version upgrade can be modified at cluster level applying to all nodes. Security group changes may take a few minutes to be applied to the cluster. Parameter Group changes will take effect only after you reboot your Cache Nodes. Instance capacity type of a Cache Node cannot be modified at runtime.
Operation 2: Reboot
Using this option you can reboot a single cache node or the entire cache cluster. The cache nodes will not be available during the cluster reboot operation. In case a single cache node alone is rebooted, other cache nodes are available for processing requests. Reboot operation can be done using the AWS console or API. Reboot is usually performed:
- When a cache node(s) is not responsive
- Parameter Group changes applied need to take effect on all the nodes of the cache cluster
In our tests, we found reboot of 5 X m1.large cache node type in Amazon EC2 US-EAST region takes around ~140 seconds. This may vary time to time depending upon the cache node type and Amazon EC2 regions in consideration. Because of the ephemeral nature of the Cache, the cache node begin empty (also called “cold”) after reboot operation, and depending on your workload pattern, it may take some time to be re-populated with data (also called “warming up” phase).
Operation 3: Delete and Removal
You can remove a one or more nodes from a cache cluster or delete the entire cluster. In case only one node is present in the cache cluster, you need to delete the cache cluster itself. Deleting one or more nodes takes ~200 seconds. This may vary time to time depending upon the cache node type and Amazon EC2 regions in consideration. In case a cluster is deleted, you can recreate a cache cluster in the same name at later point of time in the same Amazon EC2 region.
Operation 4: Addition of Cache Nodes
Amazon ElastiCache as the name suggests you can automatically/manually add cache nodes to the existing ElastiCache cluster making the whole tier elastic. One or more cache nodes can be added to the existing cache cluster at a time. In our tests, we found adding 5 X m1.large cache node type in Amazon EC2 US-EAST region takes around ~320 seconds. This may vary time to time depending upon the cache node type and Amazon EC2 regions in consideration. While adding new cache nodes in existing cluster, the cache node type should be the same size as the existing node type. You cannot change that size, in case you need different cache node capacity a new cache cluster needs to be created.
With a normal hashing algorithm, increasing the number of memcached cache nodes can cause many keys to be remapped to different cache node resulting in huge set of cache misses. Imagine you have 10 Amazon ElastiCache Nodes in your cache Cluster, adding an eleventh server may cause ~40%+ of your keys to suddenly point to different servers than normal. This activity may cause cache misses and swamp your backend Database with requests. To minimize this remapping process it is recommended to follow consistent Hashing in your cache clients. Consistent Hashing allows for more stable distribution of keys and minimal remapping when new cache nodes are added. Using this algorithm, adding an eleventh server should cause less than 10% of your keys to be reassigned. This % may vary in production but it is far more efficient in such elastic scenarios compared to normal hash algorithms. It is also advised to keep cache node ordering and number of cache node entries same in all the client configurations while using consistent Hashing algorithm. Java Applications can use “Ketama library” through Spymemcached library to integrate this algorithm into their applications. Refer URL to know more about consistent Hashing in memcached.
A sample Pseudo code illustrating SET operation in TEXT-TCP protocol using Java Spymemcached –Ketama HashingKetamaTCPSet { public void setValue() throws IOException { ConnectionFactory connFactory = new DefaultConnectionFactory( DefaultConnectionFactory.DEFAULT_OP_QUEUE_LEN, DefaultConnectionFactory.DEFAULT_READ_BUFFER_SIZE, HashAlgorithm.KETAMA_HASH); MemcachedClient memcachedClient = new MemcachedClient(connFactory,AddrUtil.getAddresses("ecache1a.sqjbuo.0001.use1.cache.amazonaws.com:11211")); String key = "1000001"; String value = "1000001-Test value in Consistent Hashing"; Integer expires = Integer.parseInt("1000"); try { Future<Boolean> result = memcachedClient.set(key, expires, value); ……………….. ……………….. } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } memcachedClient.shutdown(); } }
Learn the basics of programming with the web's most popular language - JavaScript | https://www.sitepoint.com/amazon-elasticache-cache-on-steroids/ | CC-MAIN-2022-05 | en | refinedweb |
The last used rectangle.
Get the rectangle last used by GUILayout for a control.
Note that this only works during the Repaint event.
function OnGUI() { GUILayout.Button( "My button" ); if(Event.current.type == EventType.Repaint && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition )) { GUILayout.Label( "Mouse over!" ); } else { GUILayout.Label( "Mouse somewhere else" ); } }
using UnityEngine; using System.Collections;
public class ExampleClass :: | https://docs.unity3d.com/2017.2/Documentation/ScriptReference/GUILayoutUtility.GetLastRect.html | CC-MAIN-2022-05 | en | refinedweb |
Before reading this section, we suggest you reading Getting Started and Fundamentals to grasp the basics of Onsen UI. Don’t worry, it won’t take more than 5 minutes.
React bindings for Onsen UI provide React components that wrap the core Web Components and expose a React-like API to interact with them.
React bindings are distributed in
react-onsenui package. You can download it via NPM:
$ npm install onsenui react-onsenui --save
It is also available via CDN. The latest core release also contains React bindings.
You can load Onsen UI with normal tags as follows:
<script src="react.js"></script> <script src="react-dom.js"></script> <script src="onsenui.js"></script> <script src="react-onsenui.js"></script> <script src=""></script>
Or you can use React and Onsen UI from npm with CommonJS module system like Browserify or Webpack. In this case, use the
onsenui and
react-onsenui packages, in addition to react and
react-dom npm packages. In the example below
ons contains Onsen UI core instance, and
Ons contains React components.
var React = require('react'); var ReactDOM = require('react-dom'); var ons = require('onsenui'); var Ons = require('react-onsenui');
Alternatively, you can also use ES6 imports to specify the modules you want to use in
react-onsenui package.
import { Page, Toolbar, Button } from 'react-onsenui'; // Only import the necessary components // import * as Ons from 'react-onsenui'; // Import everything and use it as 'Ons.Page', 'Ons.Button'
The CSS can be included normally with
<link> tags in
index.html or can be imported by Webpack:
// Webpack CSS import import 'onsenui/css/onsenui.css'; import 'onsenui/css/onsen-css-components.css';
To get started, let’s create a simple Hello World application. The following sample code is a React version of Onsen UI HelloWorld.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="stylesheet" href="css/onsenui.css"> <link rel="stylesheet" href="css/onsen-css-components.css"> <script src="react.js"></script> <script src="react-dom.js"></script> <script src="onsenui.js"></script> <script src="react-onsenui.js"></script> <script src=""></script> </head> <body> <div id="app"></div> <script type="text/babel"> var App = React.createClass({ handleClick: function() { ons.notification.alert('Hello world!'); }, render: function() { return ( <Ons.Page> <Ons.Button onClick={this.handleClick}>Tap me!</Ons.Button> </Ons.Page> ); } }); ReactDOM.render(<App />, document.getElementById('app')); </script> </body> </html>
In
<body> tag, there is only a
<div> tag having app id. This is where React will render the content into, and you can see it in the very bottom of JS code.
Also notice
<script></script> tag has
text/babel type. This means this script is not a pure JavaScript that browser supports (most commonly ECMAScript5), but is a ECMAScript6 (ES2015) with JSX format. Babel will transpile this code into ES5 in the browser. To get better performance, we can use Node.js to transpile the code.
Inside the script,
React.createClass() function defines a React Component called “App”. It has one method called render, and this is the function that is called when the app is rendered. The returning object is described in JSX, which is a XML like language that extends JavaScript. In this case, it is returning
<Ons.Page> component that has an
<Ons.Button> component. The
onClick prop is used to call the
handleClick method when the user taps the button.
return ( <Ons.Page> <Ons.Button onClick={this.handleClick}>Tap me!</Ons.Button> </Ons.Page> );
As you can see in this example, all <Ons.*> components are React Components, and they are loaded by
react-onsenui.js. For a full list of React Components, see the reference page.
Putting together, when
index.html is loaded into the browser, it will compile JSX code, inject into the body, and render the content.
For more information about React itself or JSX format, we recommend reading the official React docs. | https://onsen.io/v2/guide/react/ | CC-MAIN-2022-05 | en | refinedweb |
Do you want simpler Python code? You always start a project with the best intentions, a clean codebase, and a nice structure. But over time, there are changes to your apps, and things can get a little messy.
If you can write and maintain clean, simple Python code, then it’ll save you lots of time in the long term. You can spend less time testing, finding bugs, and making changes when your code is well laid out and simple to follow.
In this tutorial you’ll learn:
- How to measure the complexity of Python code and your applications
- How to change your code without breaking it
- What the common issues in Python code that cause extra complexity are and how you can fix them
Throughout this tutorial, I’m going to use the theme of subterranean railway networks to explain complexity because navigating a subway system in a large city can be complicated! Some are well designed, and others seem overly complex.
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
Code Complexity in Python
The complexity of an application and its codebase is relative to the task it’s performing. If you’re writing code for NASA’s jet propulsion laboratory (literally rocket science), then it’s going to be complicated.
The question isn’t so much, “Is my code complicated?” as, “Is my code more complicated than it needs to be?”
The Tokyo railway network is one of the most extensive and complicated in the world. This is partly because Tokyo is a metropolis of over 30 million people, but it’s also because there are 3 networks overlapping each other.
There are the Toei and Tokyo Metro rapid-transport networks as well as the Japan Rail East trains going through Central Tokyo. To even the most experienced traveler, navigating central Tokyo can be mind-bogglingly complicated.
Here is a map of the Tokyo railway network to give you some perspective:
If your code is starting to look a bit like this map, then this is the tutorial for you.
First, we’ll go through 4 metrics of complexity that can give you a scale to measure your relative progress in the mission to make your code simpler:
After you’ve explored the metrics, you’ll learn about a tool called
wily to automate calculating those metrics.
Metrics for Measuring Complexity
Much time and research have been put into analyzing the complexity of computer software. Overly complex and unmaintainable applications can have a very real cost.
The complexity of software correlates to the quality. Code that is easy to read and understand is more likely to be updated by developers in the future.
Here are some metrics for programming languages. They apply to many languages, not just Python.
Lines of Code
LOC, or Lines of Code, is the crudest measure of complexity. It is debatable whether there is any direct correlation between the lines of code and the complexity of an application, but the indirect correlation is clear. After all, a program with 5 lines is likely simpler than one with 5 million.
When looking at Python metrics, we try to ignore blank lines and lines containing comments.
Lines of code can be calculated using the
wc command on Linux and Mac OS, where
file.py is the name of the file you want to measure:
$ wc -l file.py
If you want to add the combined lines in a folder by recursively searching for all
.py files, you can combine
wc with the
find command:
$ find . -name \*.py | xargs wc -l
For Windows, PowerShell offers a word count command in
Measure-Object and a recursive file search in
Get-ChildItem:
PS C:\> Get-ChildItem -Path *.py -Recurse | Measure-Object –Line
In the response, you will see the total number of lines.
Why are lines of code used to quantify the amount of code in your application? The assumption is that a line of code roughly equates to a statement. Lines is a better measure than characters, which would include whitespace.
In Python, we are encouraged to put a single statement on each line. This example is 9 lines of code:
1x = 5 2value = input("Enter a number: ") 3y = int(value) 4if x < y: 5 print(f"{x} is less than {y}") 6elif x == y: 7 print(f"{x} is equal to {y}") 8else: 9 print(f"{x} is more than {y}")
If you used only lines of code as your measure of complexity, it could encourage the wrong behaviors.
Python code should be easy to read and understand. Taking that last example, you could reduce the number of lines of code to 3:
1x = 5; y = int(input("Enter a number:")) 2equality = "is equal to" if x == y else "is less than" if x < y else "is more than" 3print(f"{x} {equality} {y}")
But the result is hard to read, and PEP 8 has guidelines around maximum line length and line breaking. You can check out How to Write Beautiful Python Code With PEP 8 for more on PEP 8.
This code block uses 2 Python language features to make the code shorter:
- Compound statements: using
;
- Chained conditional or ternary statements:
name = value if condition else value if condition2 else value2
We have reduced the number of lines of code but violated one of the fundamental laws of Python:
“Readability counts”
— Tim Peters, Zen of Python
This shortened code is potentially harder to maintain because code maintainers are humans, and this short code is harder to read. We will explore some more advanced and useful metrics for complexity.
Cyclomatic Complexity
Cyclomatic complexity is the measure of how many independent code paths there are through your application. A path is a sequence of statements that the interpreter can follow to get to the end of the application.
One way to think of cyclomatic complexity and code paths is imagine your code is like a railway network.
For a journey, you may need to change trains to reach your destination. The Lisbon Metropolitan railway system in Portugal is simple and easy to navigate. The cyclomatic complexity for any trip is equal to the number of lines you need to travel on:
If you needed to get from Alvalade to Anjos, then you would travel 5 stops on the linha verde (green line):
This trip has a cyclomatic complexity of 1 because you only take 1 train. It’s an easy trip. That train is equivalent in this analogy to a code branch.
If you needed to travel from the Aeroporto (airport) to sample the food in the district of Belém, then it’s a more complicated journey. You would have to change trains at Alameda and Cais do Sodré:
This trip has a cyclomatic complexity of 3, because you take 3 trains. You might be better off taking a taxi!
Seeing as how you’re not navigating Lisbon, but rather writing code, the changes of train line become a branch in execution, like an
if statement.
Let’s explore this example:
x = 1
There is only 1 way this code can be executed, so it has a cyclomatic complexity of 1.
If we add a decision, or branch to the code as an
if statement, it increases the complexity:
x = 1 if x < 2: x += 1
Even though there is only 1 way this code can be executed, as
x is a constant, this has a cyclomatic complexity of 2. All of the cyclomatic complexity analyzers will treat an
if statement as a branch.
This is also an example of overly complex code. The
if statement is useless as
x has a fixed value. You could simply refactor this example to the following:
x = 2
That was a toy example, so let’s explore something a little more real.
main() has a cyclomatic complexity of 5. I’ll comment each branch in the code so you can see where they are:
# cyclomatic_example.py import sys def main(): if len(sys.argv) > 1: # 1 filepath = sys.argv[1] else: print("Provide a file path") exit(1) if filepath: # 2 with open(filepath) as fp: # 3 for line in fp.readlines(): # 4 if line != "\n": # 5 print(line, end="") if __name__ == "__main__": # Ignored. main()
There are certainly ways that code can be refactored into a far simpler alternative. We’ll get to that later.
Note: The Cyclomatic Complexity measure was developed by Thomas J. McCabe, Sr in 1976. You may see it referred to as the McCabe metric or McCabe number.
In the following examples, we will use the
radon library from PyPI to calculate metrics. You can install it now:
$ pip install radon
To calculate cyclomatic complexity using
radon, you can save the example into a file called
cyclomatic_example.py and use
radon from the command line.
The
radon command takes 2 main arguments:
- The type of analysis (
ccfor cyclomatic complexity)
- A path to the file or folder to analyze
Execute the
radon command with the
cc analysis against the
cyclomatic_example.py file. Adding
-s will give the cyclomatic complexity in the output:
$ radon cc cyclomatic_example.py -s cyclomatic_example.py F 4:0 main - B (6)
The output is a little cryptic. Here is what each part means:
Fmeans function,
Mmeans method, and
Cmeans class.
mainis the name of the function.
4is the line the function starts on.
Bis the rating from A to F. A is the best grade, meaning the least complexity.
- The number in parentheses,
6, is the cyclomatic complexity of the code.
Halstead Metrics
The Halstead complexity metrics relate to the size of a program’s codebase. They were developed by Maurice H. Halstead in 1977. There are 4 measures in the Halstead equations:
- Operands are values and names of variables.
- Operators are all of the built-in keywords, like
if,
else,
foror
while.
- Length (N) is the number of operators plus the number of operands in your program.
- Vocabulary (h) is the number of unique operators plus the number of unique operands in your a program.
There are then 3 additional metrics with those measures:
- Volume (V) represents a product of the length and the vocabulary.
- Difficulty (D) represents a product of half the unique operands and the reuse of operands.
- Effort (E) is the overall metric that is a product of volume and difficulty.
All of this is very abstract, so let’s put it in relative terms:
- The effort of your application is highest if you use a lot of operators and unique operands.
- The effort of your application is lower if you use a few operators and fewer variables.
For the
cyclomatic_complexity.py example, operators and operands both occur on the first line:
import sys # import (operator), sys (operand)
import is an operator, and
sys is the name of the module, so it’s an operand.
In a slightly more complex example, there are a number of operators and operands:
if len(sys.argv) > 1: ...
There are 5 operators in this example:
if
(
)
>
:
Furthermore, there are 2 operands:
sys.argv
1
Be aware that
radon only counts a subset of operators. For example, parentheses are excluded in any calculations.
To calculate the Halstead measures in
radon, you can run the following command:
$ radon hal cyclomatic_example.py cyclomatic_example.py: h1: 3 h2: 6 N1: 3 N2: 6 vocabulary: 9 length: 9 calculated_length: 20.264662506490406 volume: 28.529325012980813 difficulty: 1.5 effort: 42.793987519471216 time: 2.377443751081734 bugs: 0.009509775004326938
Why does
radon give a metric for time and bugs?
Halstead theorized that you could estimate the time taken in seconds to code by dividing the effort (
E) by 18.
Halstead also stated that the expected number of bugs could be estimated dividing the volume (
V) by 3000. Keep in mind this was written in 1977, before Python was even invented! So don’t panic and start looking for bugs just yet.
Maintainability Index
The maintainability index brings the McCabe Cyclomatic Complexity and the Halstead Volume measures in a scale roughly between zero and one-hundred.
If you’re interested, the original equation is as follows:
In the equation,
V is the Halstead volume metric,
C is the cyclomatic complexity, and
L is the number of lines of code.
If you’re as baffled as I was when I first saw this equation, here’s it means: it calculates a scale that includes the number of variables, operations, decision paths, and lines of code.
It is used across many tools and languages, so it’s one of the more standard metrics. However, there are numerous revisions of the equation, so the exact number shouldn’t be taken as fact.
radon,
wily, and Visual Studio cap the number between 0 and 100.
On the maintainability index scale, all you need to be paying attention to is when your code is getting significantly lower (toward 0). The scale considers anything lower than 25 as hard to maintain, and anything over 75 as easy to maintain. The Maintainability Index is also referred to as MI.
The maintainability index can be used as a measure to get the current maintainability of your application and see if you’re making progress as you refactor it.
To calculate the maintainability index from
radon, run the following command:
$ radon mi cyclomatic_example.py -s cyclomatic_example.py - A (87.42)
In this result,
A is the grade that
radon has applied to the number
87.42 on a scale. On this scale,
A is most maintainable and
F the least.
Using
wily to Capture and Track Your Projects’ Complexity
wily is an open-source software project for collecting code-complexity metrics, including the ones we’ve covered so far like Halstead, Cyclomatic, and LOC.
wily integrates with Git and can automate the collection of metrics across Git branches and revisions.
The purpose of
wily is to give you the ability to see trends and changes in the complexity of your code over time. If you were trying to fine-tune a car or improve your fitness, you’d start off with measuring a baseline and tracking improvements over time.
Installing
wily
wily is available on PyPI and can be installed using pip:
$ pip install wily
Once
wily is installed, you have some commands available in your command-line:
wily build: iterate through the Git history and analyze the metrics for each file
wily report: see the historical trend in metrics for a given file or folder
wily graph: graph a set of metrics in an HTML file
Building a Cache
Before you can use
wily, you need to analyze your project. This is done using the
wily build command.
For this section of the tutorial, we will analyze the very popular
requests package, used for talking to HTTP APIs. Because this project is open-source and available on GitHub, we can easily access and download a copy of the source code:
$ git clone $ cd requests $ ls AUTHORS.rst CONTRIBUTING.md LICENSE Makefile Pipfile.lock _appveyor docs pytest.ini setup.cfg tests CODE_OF_CONDUCT.md HISTORY.md MANIFEST.in Pipfile README.md appveyor.yml ext requests setup.py tox.ini
Note: Windows users should use the PowerShell command prompt for the following examples instead of traditional MS-DOS Command-Line. To start the PowerShell CLI press Win+R and type
powershell then Enter.
You will see a number of folders here, for tests, documentation, and configuration. We’re only interested in the source code for the
requests Python package, which is in a folder called
requests.
Call the
wily build command from the cloned source code and provide the name of the source code folder as the first argument:
$ wily build requests
This will take a few minutes to analyze, depending on how much CPU power your computer has:
Collecting Data on Your Project
Once you have analyzed the
requests source code, you can query any file or folder to see key metrics. Earlier in the tutorial, we discussed the following:
- Lines of Code
- Maintainability Index
- Cyclomatic Complexity
Those are the 3 default metrics in
wily. To see those metrics for a specific file (such as
requests/api.py), run the following command:
$ wily report requests/api.py
wily will print a tabular report on the default metrics for each Git commit in reverse date order. You will see the most recent commit at the top and the oldest at the bottom:
This tells us that the
requests/api.py file has:
- 158 lines of code
- A perfect maintainability index of 100
- A cyclomatic complexity of 9
To see other metrics, you first need to know the names of them. You can see this by running the following command:
$ wily list-metrics
You will see a list of operators, modules that analyze the code, and the metrics they provide.
To query alternative metrics on the report command, add their names after the filename. You can add as many metrics as you wish. Here’s an example with the Maintainability Rank and the Source Lines of Code:
$ wily report requests/api.py maintainability.rank raw.sloc
You will see the table now has 2 different columns with the alternative metrics.
Graphing Metrics
Now that you know the names of the metrics and how to query them on the command line, you can also visualize them in graphs.
wily supports HTML and interactive charts with a similar interface as the report command:
$ wily graph requests/sessions.py maintainability.mi
Your default browser will open with an interactive chart like this:
You can hover over specific data points, and it will show the Git commit message as well as the data.
If you want to save the HTML file in a folder or repository, you can add the
-o flag with the path to a file:
$ wily graph requests/sessions.py maintainability.mi -o my_report.html
There will now be a file called
my_report.html that you can share with others. This command is ideal for team dashboards.
wily as a
pre-commit Hook
wily can be configured so that before you commit changes to your project, it can alert you to improvements or degradations in complexity.
wily has a
wily diff command, that compares the last indexed data with the current working copy of a file.
To run a
wily diff command, provide the names of the files you have changed..
pre-commit inserts a hook into your Git configuration that calls a script every time you run the
git commit command.
To install
pre-commit, you can install from PyPI:
$ pip install pre-commit
Add the following to a
.pre-commit-config.yaml in your projects root directory:
repos: - repo: local hooks: - id: wily name: wily entry: wily diff verbose: true language: python additional_dependencies: [wily]
Once setting this, you run the
pre-commit install command to finalize things:
$ pre-commit install
Whenever you run the
git commit command, it will call
wily diff along with the list of files you’ve added to your staged changes.
wily is a useful utility to baseline the complexity of your code and measure the improvements you make when you start to refactor.
Refactoring in Python
Refactoring is the technique of changing an application (either the code or the architecture) so that it behaves the same way on the outside, but internally has improved. These improvements can be stability, performance, or reduction in complexity.
One of the world’s oldest underground railways, the London Underground, started in 1863 with the opening of the Metropolitan line. It had gas-lit wooden carriages hauled by steam locomotives. On the opening of the railway, it was fit for purpose. 1900 brought the invention of the electric railways.
By 1908, the London Underground had expanded to 8 railways. During the Second World War, the London Underground stations were closed to trains and used as air-raid shelters. The modern London Underground carries millions of passengers a day with over 270 stations:
It’s almost impossible to write perfect code the first time, and requirements change frequently. If you would have asked the original designers of the railway to design a network fit for 10 million passengers a day in 2020, they would not design the network that exists today.
Instead, the railway has undergone a series of continuous changes to optimize its operation, design, and layout to match the changes in the city. It has been refactored.
In this section, you’ll explore how to safely refactor by leveraging tests and tools. You’ll also see how to use the refactoring functionality in Visual Studio Code and PyCharm:
Avoiding Risks With Refactoring: Leveraging Tools and Having Tests
If the point of refactoring is to improve the internals of an application without impacting the externals, how do you ensure the externals haven’t changed?
Before you charge into a major refactoring project, you need to make sure you have a solid test suite for your application. Ideally, that test suite should be mostly automated, so that as you make changes, you see the impact on the user and address it quickly.
If you want to learn more about testing in Python, Getting Started With Testing in Python is a great place to start.
There is no perfect number of tests to have on your application. But, the more robust and thorough the test suite, the more aggressively you can refactor your code.
The two most common tasks you will perform when doing refactoring are:
- Renaming modules, functions, classes, and methods
- Finding usages of functions, classes, and methods to see where they are called
You can simply do this by hand using search and replace, but it is both time consuming and risky. Instead, there are some great tools to perform these tasks.
Using
rope for Refactoring
rope is a free Python utility for refactoring Python code. It comes with an extensive set of APIs for refactoring and renaming components in your Python codebase.
rope can be used in two ways:
- By using an editor plugin, for Visual Studio Code, Emacs, or Vim
- Directly by writing scripts to refactor your application
To use rope as a library, first install
rope by executing
pip:
$ pip install rope
It is useful to work with
rope on the REPL so that you can explore the project and see changes in real time. To start, import the
Project type and instantiate it with the path to the project:
>>> from rope.base.project import Project >>> proj = Project('requests')
The
proj variable can now perform a series of commands, like
get_files and
get_file, to get a specific file. Get the file
api.py and assign it to a variable called
api:
>>> [f.name for f in proj.get_files()] ['structures.py', 'status_codes.py', ...,'api.py', 'cookies.py'] >>> api = proj.get_file('api.py')
If you wanted to rename this file, you could simply rename it on the filesystem. However, any other Python files in your project that imported the old name would now be broken. Let’s rename the
api.py to
new_api.py:
>>> from rope.refactor.rename import Rename >>> change = Rename(proj, api).get_changes('new_api') >>> proj.do(change)
Running
git status, you will see that
rope made some changes to the repository:
$ git status On branch master Your branch is up to date with 'origin/master'. Changes not staged for commit: (use "git add/rm <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: requests/__init__.py deleted: requests/api.py Untracked files: (use "git add <file>..." to include in what will be committed) requests/.ropeproject/ requests/new_api.py no changes added to commit (use "git add" and/or "git commit -a")
The three changes made by
rope are the following:
- Deleted
requests/api.pyand created
requests/new_api.py
- Modified
requests/__init__.pyto import from
new_apiinstead of
api
- Created a project folder named
.ropeproject
To reset the change, run
git reset.
There are hundreds of other refactorings that can be done with
rope.
Using Visual Studio Code for Refactoring
Visual Studio Code opens up a small subset of the refactoring commands available in
rope through its own UI.
You can:
- Extract variables from a statement
- Extract methods from a block of code
- Sort imports into a logical order
Here is an example of using the Extract methods command from the command palette:
Using PyCharm for Refactoring
If you use or are considering using PyCharm as a Python editor, it’s worth taking note of the powerful refactoring capabilities it has.
You can access all the refactoring shortcuts with the Ctrl+T command on Windows and macOS. The shortcut to access refactoring in Linux is Ctrl+Shift+Alt+T.
Finding Callers and Usages of Functions and Classes
Before you remove a method or class or change the way it behaves, you’ll need to know what code depends on it. PyCharm can search for all usages of a method, function, or class within your project.
To access this feature, select a method, class, or variable by right-clicking and select Find Usages:
All of the code that uses your search criteria is shown in a panel at the bottom. You can double-click on any item to navigate directly to the line in question.
Using the PyCharm Refactoring Tools
Some of the other refactoring commands include the ability to:
- Extract methods, variables, and constants from existing code
- Extract abstract classes from existing class signatures, including the ability to specify abstract methods
- Rename practically anything, from a variable to a method, file, class, or module
Here is an example of renaming the same
api.py module you renamed earlier using the
rope module to
new_api.py:
The rename command is contextualized to the UI, which makes refactoring quick and simple. It has updated the imports automatically in
__init__.py with the new module name.
Another useful refactor is the Change Signature command. This can be used to add, remove, or rename arguments to a function or method. It will search for usages and update them for you:
You can set default values and also decide how the refactoring should handle the new arguments.
Summary
Refactoring is an important skill for any developer. As you’ve learned in this chapter, you aren’t alone. The tools and IDEs already come with powerful refactoring features to be able to make changes quickly.
Complexity Anti-Patterns
Now that you know how complexity can be measured, how to measure it, and how to refactor your code, it’s time to learn 5 common anti-patterns that make code more complex than it need be:
If you can master these patterns and know how to refactor them, you’ll soon be on track (pun intended) to a more maintainable Python application.
1. Functions That Should Be Objects
Python supports procedural programming using functions and also inheritable classes. Both are very powerful and should be applied to different problems.
Take this example of a module for working with images. The logic in the functions has been removed for brevity:
# imagelib.py def load_image(path): with open(path, "rb") as file: fb = file.load() image = img_lib.parse(fb) return image def crop_image(image, width, height): ... return image def get_image_thumbnail(image, resolution=100): ... return image
There are a few issues with this design:
It’s not clear if
crop_image()and
get_image_thumbnail()modify the original
imagevariable or create new images. If you wanted to load an image then create both a cropped and thumbnail image, would you have to copy the instance first? You could read the source code in the functions, but you can’t rely on every developer doing this.
You have to pass the image variable as an argument in every call to the image functions.
This is how the calling code might look:
from imagelib import load_image, crop_image, get_image_thumbnail image = load_image('~/face.jpg') image = crop_image(image, 400, 500) thumb = get_image_thumbnail(image)
Here are some symptoms of code using functions that could be refactored into classes:
- Similar arguments across functions
- Higher number of Halstead
h2unique operands
- Mix of mutable and immutable functions
- Functions spread across multiple Python files
Here is a refactored version of those 3 functions, where the following happens:
.__init__()replaces
load_image().
crop()becomes a class method.
get_image_thumbnail()becomes a property.
The thumbnail resolution has become a class property, so it can be changed globally or on that particular instance:
# imagelib.py class Image(object): thumbnail_resolution = 100 def __init__(self, path): ... def crop(self, width, height): ... @property def thumbnail(self): ... return thumb
If there were many more image-related functions in this code, the refactoring to a class could make a drastic change. The next consideration would be the complexity of the consuming code.
This is how the refactored example would look:
from imagelib import Image image = Image('~/face.jpg') image.crop(400, 500) thumb = image.thumbnail
In the resulting code, we have solved the original problems:
- It is clear that
thumbnailreturns a thumbnail since it is a property, and that it doesn’t modify the instance.
- The code no longer requires creating new variables for the crop operation.
2. Objects That Should Be Functions
Sometimes, the reverse is true. There is object-oriented code which would be better suited to a simple function or two.
Here are some tell-tale signs of incorrect use of classes:
- Classes with 1 method (other than
.__init__())
- Classes that contain only static methods
Take this example of an authentication class:
# authenticate.py class Authenticator(object): def __init__(self, username, password): self.username = username self.password = password def authenticate(self): ... return result
It would make more sense to just have a simple function named
authenticate() that takes
username and
password as arguments:
# authenticate.py def authenticate(username, password): ... return result
You don’t have to sit down and look for classes that match these criteria by hand:
pylint comes with a rule that classes should have a minimum of 2 public methods. For more on PyLint and other code quality tools, you can check out Python Code Quality and Writing Cleaner Python Code With PyLint.
To install
pylint, run the following command in your console:
$ pip install pylint
pylint takes a number of optional arguments and then the path to one or more files and folders. If you run
pylint with its default settings, it’s going to give a lot of output as
pylint has a huge number of rules. Instead, you can run specific rules. The
too-few-public-methods rule id is
R0903. You can look this up on the documentation website:
$ pylint --disable=all --enable=R0903 requests ************* Module requests.auth requests/auth.py:72:0: R0903: Too few public methods (1/2) (too-few-public-methods) requests/auth.py:100:0: R0903: Too few public methods (1/2) (too-few-public-methods) ************* Module requests.models requests/models.py:60:0: R0903: Too few public methods (1/2) (too-few-public-methods) ----------------------------------- Your code has been rated at 9.99/10
This output tells us that
auth.py contains 2 classes that have only 1 public method. Those classes are on lines 72 and 100. There is also a class on line 60 of
models.py with only 1 public method.
3. Converting “Triangular” Code to Flat Code
If you were to zoom out on your source code and tilt your head 90 degrees to the right, does the whitespace look flat like Holland or mountainous like the Himalayas? Mountainous code is a sign that your code contains a lot of nesting.
Here’s one of the principles in the Zen of Python:
“Flat is better than nested”
— Tim Peters, Zen of Python
Why would flat code be better than nested code? Because nested code makes it harder to read and understand what is happening. The reader has to understand and memorize the conditions as they go through the branches.
These are the symptoms of highly nested code:
- A high cyclomatic complexity because of the number of code branches
- A low Maintainability Index because of the high cyclomatic complexity relative to the number of lines of code
Take this example that looks at the argument
data for strings that match the word
error. It first checks if the
data argument is a list. Then, it iterates over each and checks if the item is a string. If it is a string and the value is
"error", then it returns
True. Otherwise, it returns
False:
def contains_errors(data): if isinstance(data, list): for item in data: if isinstance(item, str): if item == "error": return True return False
This function would have a low maintainability index because it is small, but it has a high cyclomatic complexity.
Instead, we can refactor this function by “returning early” to remove a level of nesting and returning
False if the value of
data is not list. Then using
.count() on the list object to count for instances of
"error". The return value is then an evaluation that the
.count() is greater than zero:
def contains_errors(data): if not isinstance(data, list): return False return data.count("error") > 0
Another technique for reducing nesting is to leverage list comprehensions. This common pattern of creating a new list, going through each item in a list to see if it matches a criterion, then adding all matches to the new list:
results = [] for item in iterable: if item == match: results.append(item)
This code can be replaced with a faster and more efficient list comprehension.
Refactor the last example into a list comprehension and an
if statement:
results = [item for item in iterable if item == match]
This new example is smaller, has less complexity, and is more performant.
If your data is not a single dimension list, then you can leverage the itertools package in the standard library, which contains functions for creating iterators from data structures. You can use it for chaining iterables together, mapping structures, cycling or repeating over existing iterables.
Itertools also contains functions for filtering data, like
filterfalse().
For more on Itertools, check out Itertools in Python 3, By Example.
4. Handling Complex Dictionaries With Query Tools
One of Python’s most powerful and widely used core types is the dictionary. It’s fast, efficient, scalable, and highly flexible.
If you’re new to dictionaries, or think you could leverage them more, you can read Dictionaries in Python for more information.
It does have one major side-effect: when dictionaries are highly nested, the code that queries them becomes nested too.
Take this example piece of data, a sample of the Tokyo Metro lines you saw earlier:
data = { "network": { "lines": [ { "name.en": "Ginza", "name.jp": "銀座線", "color": "orange", "number": 3, "sign": "G" }, { "name.en": "Marunouchi", "name.jp": "丸ノ内線", "color": "red", "number": 4, "sign": "M" } ] } }
If you wanted to get the line that matched a certain number, this could be achieved in a small function:
def find_line_by_number(data, number): matches = [line for line in data if line['number'] == number] if len(matches) > 0: return matches[0] else: raise ValueError(f"Line {number} does not exist.")
Even though the function itself is small, calling the function is unnecessarily complicated because the data is so nested:
>>> find_line_by_number(data["network"]["lines"], 3)
There are third party tools for querying dictionaries in Python. Some of the most popular are JMESPath, glom, asq, and flupy.
JMESPath can help with our train network. JMESPath is a querying language designed for JSON, with a plugin available for Python that works with Python dictionaries. To install JMESPath, do the following:
$ pip install jmespath
Then open up a Python REPL to explore the JMESPath API, copying in the
data dictionary. To get started, import
jmespath and call
search() with a query string as the first argument and the data as the second. The query string
"network.lines" means return
data['network']['lines']:
>>> import jmespath >>> jmespath.search("network.lines", data) [{'name.en': 'Ginza', 'name.jp': '銀座線', 'color': 'orange', 'number': 3, 'sign': 'G'}, {'name.en': 'Marunouchi', 'name.jp': '丸ノ内線', 'color': 'red', 'number': 4, 'sign': 'M'}]
When working with lists, you can use square brackets and provide a query inside. The “everything” query is simply
*. You can then add the name of the attribute inside each matching item to return. If you wanted to get the line number for every line, you could do this:
>>> jmespath.search("network.lines[*].number", data) [3, 4]
You can provide more complex queries, like a
== or
<. The syntax is a little unusual for Python developers, so keep the documentation handy for reference.
If we wanted to find the line with the number
3, this can be done in a single query:
>>> jmespath.search("network.lines[?number==`3`]", data) [{'name.en': 'Ginza', 'name.jp': '銀座線', 'color': 'orange', 'number': 3, 'sign': 'G'}]
If we wanted to get the color of that line, you could add the attribute in the end of the query:
>>> jmespath.search("network.lines[?number==`3`].color", data) ['orange']
JMESPath can be used to reduce and simplify code that queries and searches through complex dictionaries.
5. Using
attrs and
dataclasses to Reduce Code
Another goal when refactoring is to simply reduce the amount of code in the codebase while achieving the same behaviors. The techniques shown so far can go a long way to refactoring code into smaller and simpler modules.
Some other techniques require a knowledge of the standard library and some third party libraries.
What Is Boilerplate?
Boilerplate code is code that has to be used in many places with little or no alterations.
Taking our train network as an example, if we were to convert that into types using Python classes and Python 3 type hints, it might look something like this:
from typing import List class Line(object): def __init__(self, name_en: str, name_jp: str, color: str, number: int, sign: str): self.name_en = name_en self.name_jp = name_jp self.color = color self.number = number self.sign = sign def __repr__(self): return f"<Line {self.name_en}" def __str__(self): return f"The {self.name_en} line" class Network(object): def __init__(self, lines: List[Line]): self._lines = lines @property def lines(self) -> List[Line]: return self._lines
Now, you might also want to add other magic methods, like
.__eq__(). This code is boilerplate. There’s no business logic or any other functionality here: we’re just copying data from one place to another.
A Case for
dataclasses
Introduced into the standard library in Python 3.7, with a backport package for Python 3.6 on PyPI, the dataclasses module can help remove a lot of boilerplate for these types of classes where you’re just storing data.
To convert the
Line class above to a dataclass, convert all of the fields to class attributes and ensure they have type annotations:
from dataclasses import dataclass @dataclass class Line(object): name_en: str name_jp: str color: str number: int sign: str
You can then create an instance of the
Line type with the same arguments as before, with the same fields, and even
.__str__(),
.__repr__(), and
.__eq__() are implemented:
>>> line = Line('Marunouchi', "丸ノ内線", "red", 4, "M") >>> line.color red >>> line2 = Line('Marunouchi', "丸ノ内線", "red", 4, "M") >>> line == line2 True
Dataclasses are a great way to reduce code with a single import that’s already available in the standard library. For a full walkthrough, you can checkout The Ultimate Guide to Data Classes in Python 3.7.
Some
attrs Use Cases
attrs is a third party package that’s been around a lot longer than dataclasses.
attrs has a lot more functionality, and it’s available on Python 2.7 and 3.4+.
If you are using Python 3.5 or below,
attrs is a great alternative to
dataclasses. Also, it provides many more features.
The equivalent dataclasses example in
attrs would look similar. Instead of using type annotations, the class attributes are assigned with a value from
attrib(). This can take additional arguments, such as default values and callbacks for validating input:
from attr import attrs, attrib @attrs class Line(object): name_en = attrib() name_jp = attrib() color = attrib() number = attrib() sign = attrib()
attrs can be a useful package for removing boilerplate code and input validation on data classes.
Conclusion
Now that you’ve learned how to identify and tackle complicated code, think back to the steps you can now take to make your application easier to change and manage:
- Start off by creating a baseline of your project using a tool like
wily.
- Look at some of the metrics and start with the module that has the lowest maintainability index.
- Refactor that module using the safety provided in tests and the knowledge of tools like PyCharm and
rope.
Once you follow these steps and the best practices in this article, you can do other exciting things to your application, like adding new features and improving performance. | https://realpython.com/python-refactoring/ | CC-MAIN-2022-05 | en | refinedweb |
The Abstract Windowing Toolkit (AWT) is the first set of nontrivial, publicly available, basic objects with which to build Java programs, with the focus on graphical user interfaces, or GUls. The AWT was built by Sun’s JavaSoft unit and is provided free for anyone to use for any reason whatsoever, in binary form. There is some controversy as to whether the AWT in its present condition will survive, but it does have three things going for it:
• It is the first Java toolkit available,
• It has gained rapid acceptance, and
• JavaSoft is committed to it.
The Java Foundation Class (JFC) provides two frameworks for building GUI-based Applications Abstract Window Toolkit (AWT) and swings.
The AWT package can be used by importing java.awt.* as follows:
import java.awt.*
The AWT has a set of Java classes that provide the standard set of user-interface elements (windows, menus, boxes, buttons, lists and so on). That is, AWT provides several facilities for drawing two-dimensional shapes, controlling colours and controlling fonts. Before using Java AWT classes, understanding the Java coordinate system is essential. By default, the top left comer of the component has coordinates (0,0). Here, the x-coordinate denotes the horizontal distance and the y-coordinate is the vertical distance from the upper left comer of the component, respectively. The applet’s width and height are 200 pixels each, in which the upper left comer is denoted by (0,0) and lower right comer is (200, 200).
Event Handlers An event is generated when an action occurs, such as a mouse click on a button or a carriage return (enter) in a text field. Events are handled by creating listener classes which implement listener interfaces. The standard listener interfaces are found in java.awt.event.
Layout Manager A layout manager is automatically associated with each container when it is created. Examples of this are BorderLayout and GridLayout. | https://ecomputernotes.com/java/awt-and-applets/abstract-window-toolkit | CC-MAIN-2022-05 | en | refinedweb |
How to circumvent "apsw.BusyError: BusyError: database is locked"?
(1) By 6kEs4Majrd on 2020-06-04 00:13:46 [source]
I see this error.
apsw.BusyError: BusyError: database is locked
I've already used. So busy_timeout does not solve this problem.
pragma busy_timeout=2147483647;
What else can be done to circumvent this problem? Thanks.
(2) By Stephan Beal (stephan) on 2020-06-04 00:25:33 in reply to 1 [link] [source]
There are cases which a busy timeout cannot trigger and you might be hitting one of them. See, fourth paragraph.
(3) By 6kEs4Majrd on 2020-06-04 02:11:55 in reply to 2 [link] [source]
In my application, I can be sure that there will be a deadlock between two processes. In such a case, what can be done to prevent BusyError from occurring. Thanks.
(4) By Gunter Hick (gunter_hick) on 2020-06-04 06:08:55 in reply to 3 [link] [source]
SQLITE_BUSY is SQLite's way of telling you that you are in a deadlock. You need to change your application to avoid the deadlock. Since you don't divulge how you faithfully reproduce the deadlock, remedies cannot be suggested. Other than maybe using BEGIN IMMEDIATE so that upgrading transactions from READ to WRITE is avoided. Look up the Dining Philosophers problem. Nobody gets to eat until one of them lets go of the one fork they already have. No amount of waiting will resolve the issue, which incidentally is the definition of deadlock.
(5) By 6kEs4Majrd on 2020-06-04 12:01:32 in reply to 4 [link] [source]
I use the following code (n2d contains the data to be written, n2d of different processes are not guaranteed to be different, they may be partially the same of completely the same). I don't understand how deadlock is caused and how to solved it? I basically just write to the db (except checking if the table is avaialble), so by rewriting the code the deadlock could be removed? Thanks.
import apsw conn = apsw.Connection(sys.argv[1]) c = conn.cursor() c.execute('pragma busy_timeout=2147483647;') c.execute('BEGIN TRANSACTION;')
(6) By Keith Medcalf (kmedcalf) on 2020-06-04 14:09:21 in reply to 5 [link] [source]
When you commence a transaction that you know will write to the database use BEGIN IMMEDIATE rather than BEGIN DEFERRED.
This is preschool-level deadlock avoidance procedures. Always obtain all your required locks all at once and always in the same order, and release them all on failure to acquire a necessary lock.
(7) By 6kEs4Majrd on 2020-06-04 18:25:18 in reply to 6 [link] [source]
Now, I have multiple write processes using
BEGIN IMMEDIATE. Then, I access the db for reading only using the following code.
import apsw conn = apsw.Connection(f, flags = apsw.SQLITE_OPEN_READONLY) c = conn.cursor() c.execute('pragma busy_timeout=5000;') try: for x in c.execute('SELECT name FROM sqlar'): print(x[0]) except: print(sys.argv[1] % ("Failed to process '%s'." % f), file=sys.stderr) raise
I still get the same error.
apsw.BusyError: BusyError: database is locked
Do you know how to fix the problem?
(8) By Keith Medcalf (kmedcalf) on 2020-06-04 23:32:45 in reply to 7 [link] [source]
Set your busy timeout longer.
Make sure you do not hold write transactions longer than you need to. (Only write in write transactions -- do not open them then go for a coffee break).
Consider using WAL to permit simultaneous reading and writing (though you are still limited to one writer at a time).
(9) By 6kEs4Majrd on 2020-06-05 02:27:02 in reply to 8 [link] [source]
So I need to add the following line to both the writing python apsw program and the reading python apsw program showed in the two previous messages in this thread? Or I just need to add this line to one of the two programs? Thanks.
PRAGMA journal_mode=WAL;
(10) By Keith Medcalf (kmedcalf) on 2020-06-05 03:38:42 in reply to 9 [link] [source]
The WAL setting is persistent (stored in the database), so you really only need to set it once when you create the database. However, changing the journal_mode to WAL when it is already WAL is not harmful.
(11) By 6kEs4Majrd on 2020-06-05 05:15:58 in reply to 10 [link] [source]
What about changing journal_mode from WAL to default? Is it harmful?
For the script, I don't know what I should test to conditionally use
PRAGMA journal_mode=WAL;. Do you know how the code should be changed?
import apsw conn = apsw.Connection(sys.argv[1]) c = conn.cursor() c.execute('pragma busy_timeout=5;') c.execute('PRAGMA journal_mode=WAL;') c.execute('BEGIN IMMEDIATE;')
(12) By Keith Medcalf (kmedcalf) on 2020-06-05 06:26:23 in reply to 11 [link] [source]
If you execute
pragma journal_mode; you will get back the journal_mode in effect. Actually, when you execute
pragma journal_mode=WAL; you will get back the journal mode in effect after the command is executed.
if c.execute('pragma journal_mode;').fetchone()[0] <> 'wal': if c.execute('pragma journal_mode=wal;').fetchone()[0] <> 'wal': raise apsw.Error('Cannot change database to WAL')
You can of course skip the testing and just set the journal_mode and see if it worked.
if c.execute('pragma journal_mode=wal;').fetchone()[0] <> 'wal': raise apsw.Error('Cannot change database to WAL')
Changing the database journal_mode is never harmful. If you change it to something you do not want to change it to, you may be unhappy with the result, but it will not harm anything. That is, it will cause the expected result.
(15) By 6kEs4Majrd on 2020-06-05 14:00:28 in reply to 12 [link] [source]
I got this error.
File "/xxx.py", line 23, in <module> c.execute('PRAGMA journal_mode=WAL;') File "src/cursor.c", line 1019, in APSWCursor_execute.sqlite3_prepare File "src/statementcache.c", line 386, in sqlite3_prepare apsw.BusyError: BusyError: database is locked
So the following code would also cause the same error?
if c.execute('pragma journal_mode=wal;').fetchone()[0] <> 'wal': raise apsw.Error('Cannot change database to WAL')
So this is better as the first if just read the journal_mode and would not cause apsw.BusyError? Since WAL mode is persistent, as it as long as it is set once, the first
if will always be false then the rest
pragma journal_mode=wal; statement will not be called. Hence, there will be much less chance to see apsw.BusyError?
if c.execute('pragma journal_mode;').fetchone()[0] <> 'wal': if c.execute('pragma journal_mode=wal;').fetchone()[0] <> 'wal': raise apsw.Error('Cannot change database to WAL')
(13) By TripeHound on 2020-06-05 06:48:39 in reply to 11 [link] [source]
I notice you've got a
busy_timeout of 5... if you look at the documentation, you will see this is in milliseconds. A value of
5000 (=5 seconds) or more is probably what you want.
(14) By 6kEs4Majrd on 2020-06-05 13:56:19 in reply to 13 [link] [source]
I notice you've got a busy_timeout of 5... Thanks. I knew it. It was a typo. | https://sqlite.org/forum/info/db4c917a7bb8913d | CC-MAIN-2022-05 | en | refinedweb |
Nowadays, Redux saga became the most popular library to handle asynchronous requests and control the application flow in redux, so In this article, we will discuss what is redux-saga, what is the benefits of using it, and also discuss how to use redux-saga.
What is a redux-saga?
Redux-saga is middleware which is handle side effects and asynchronous request in redux.
Redux without redux-saga
Action(s) -> Reducer(s)
Redux with redux-saga
Actions(s) -> Redux saga -> Reducer(s)
Generators
Generators are the core concept of the redux-saga so before discussing how redux-saga works, we need to understand what is generators and how it works?, [More].
Let’s see a basic example of the generators
function* generators() { yield 1; yield 2; } // calling const gen = generator(); // use console.log(gen.next()); // {value: 1, done: false} console.log(gen.next()); // {value: 2, done: false} console.log(gen.next()); // {value: undefined, done: true}
See the above code, we observe that calling the generator function doesn’t execute the whole function definition, but instead of that it’s a return iterator object. When iterator’s next() method is called, the function body is executed until the first yield.
next() method returns the object with a value and done property, value contains the yielded value and done contain the generator has yielded its last value or not as a boolean.
Ok, So we have enough discussed generators, now we are going to create our first saga.
Create Saga
Before creating a saga we will add redux-saga middleware in our redux store.
import { createStore, applyMiddleware } from 'redux'; import createSagaMiddleware from 'redux-saga'; import reducers from './reducers'; import rootSaga from './sagas'; // saga middleware const sagaMiddleware = createSagaMiddleware() const store = createStore( reducers, applyMiddleware(sagaMiddleware) ) // run saga sagaMiddleware.run(rootSaga)
Above is the basic code of the how-to setup redux store with redux-saga middleware.
Now, we create our Saga files.
Saga files are mainly split into two parts
1. Watcher
2. Workers
- Watcher Saga watches every dispatch action and if it matches the action then handle that action and assign it to the saga worker.
- Worker saga handles all the side effects.
- In root-saga, we import watcher saga and mount on the redux store,
Let’s understand with an example:
// Watcher export function* watchBulkConnect() { yield takeEvery('BULK_CONNECT_FETCH_DATA_EFFECT', getBulkConnectList); } // Worker function* getBulkConnectList() { const data = yield call(apifetchProfiles); yield put({ type: 'BULK_CONNECT_SUCCESS_DATA_STATE', payload: data }); }
See above example,
Watcher Saga listing to BULK_CONNECT_FETCH_DATA_EFFECT and when this action type dispatched watcher saga called getBulkConnectList saga which is a worker and worker saga on first yield call some API and get the results and next yield, dispatch another action type which is BULK_CONNECT_SUCCESS_DATA_STATE with payload which contains previous yield results.
Here, takeEvery, call and put are provided by the redux-saga library itself to handle/dispatch redux effects.
You can check more creator functions here.
Reference: | https://tech.shaadi.com/2021/08/05/how-to-write-your-first-redux-saga/ | CC-MAIN-2022-05 | en | refinedweb |
As we know, a pointer to type T is analogous to an array of type T.A pointer can be used to represent a vector, as illustrated in Fig. When a pointer is declared, the memory is allocated only for the pointer variable. The memory for the array elements is usually allocated separately using dynamic memory allocation functions, namely, malloc or calloc.
The function ivec_alloc, that dynamically allocates an integer vector containing n elements and returns a pointer to the allocated memory block, is given below. Note that the function return type is int*.
int *ivec_alloc(int n)
{
int *tmp = (int*) malloc(n * sizeof(int));
if (tmp == NULL) {
printf(“Error: Out of memory …\n”);
exit(l);
}
return tmp;
}
This function accepts an array size (n) and allocates memory for the array, i. e., n * sizeof (int)bytes, to a temporary integer pointer tmp. This pointer is returned to the calling function. However, if the memory allocation is unsuccessful, it displays an error message and exits with error code 1. Thus, we require only a single line call to allocate a dynamic array as shown below.
int *a;
a= ivec_alloc(100); /* allocate 100 element int array */
Note that the pointer variable tmp is local to the function and will be destroyed when the function returns. However, the address of the allocated memory block is returned to the calling function, and we can continue to use the block as a vector (through pointer a in above example) until we explicitly free its memory using free function.
Finally note that the above function is written specifically for the allocation of an integer vector and we need to write a separate function for the vector of each type required in the program. For this, we should first change the function name, say fvec_alloc for float type, cvec_alloc for char type, sivec_alloc for short int type, etc. Also, we should replace each int keyword (other than that in the function parameter declaration, int n) with the desired type. For example, function fvec_alloc for allocation of a float vector is given below.
float *fvec_alloc(int n)
{
float *tmp = (float*) malloc(n * sizeof(float));
if (tmp == NULL) {
printf(“Error: Out of memory …\n”);
exit(1);
}
return tmp;
}
C Program for read a dynamic vector and print it in reverse order
A program to read a dynamic vector of type float and print it in reverse order is given below. It first reads the array size (n) from the keyboard and allocates a dynamic vector of that size using the fvec_alloc function. Then a for loop is used to read array elements from the keyboard and another for loop is used to print the array in reverse order. Observe that the elements of the dynamic array are accessed using the usual subscript notation, a [i ]. Finally, the memory allocated to the array is freed and the program ends. Note that the program includes the stdlib.h header file.
#include <stdio.h>
#include <stdlib.h>
float * fvec_alloc(int n);
void main ()
{
float *a; /* pointer for dynamic array */
int i, n;
printf(“Enter vector size: “);
scanf(“%d”, &n);
a= fvec_alloc(n); /* allocate vector */
/* read a vector */
printf(“Enter vector elements: “);
for (i = 0; i < n; i++)
scanf(“%f”, &a[i]);
/* print a vector */
printf(“Given vector in reverse order: “);
for (i = n – 1; i >= 0; i–)
printf(“%5.2f “, a[i]);
printf(“\n”);
free(a); /* free vector */
getch();
}
/* include definition of fvec alloc function here */
The program output is given below.
Enter vector size: 2
Enter vector elements: 1.2 2.3 3.4 4.5 5.6
Given vector in reverse order: 5.60 4.50 3.40 2.30 1.20 | https://ecomputernotes.com/what-is-c/array/c-dynamic-vectors | CC-MAIN-2022-05 | en | refinedweb |
If you already learned one language or framework, it's easier to learn similar ones. Instead of reading docs from top to bottom, you just think, "how to do X with Y?".
In this article, I introduce React way of implementing Vue.js features for Vue.js devs who want to learn React as well.
(I don't encourage anyone to switch from Vue.js to React! It's better -- and also fun -- to getting to know both, right?)
Components
How to create a component?
Vue.js way
Vue component is consists of 3 blocks --
<template>,
<script>,
<style>. And the file should have
.vue extension.
<template> <div> <h1>Sample</h1> <h2>This is a component.</h2> </div> </template> <script> export default { // data and behaviors. } </script> <style> /* how this component looks */ </style>
React way
In React, you have two ways to create components -- function and class.
Below is an exmaple of functional way of creating a component.
import React from 'react'; function Sample() { return ( <div> <h1>Sample</h1> <h2>This is a component.</h2> </div> ); } export default Sample;
A functional component is a function that returns React element. It should looks like JavaScript returning HTML, but it's not. It's JSX.
In order to use JSX, you have to import React though it doesn't seem to be referenced directly. (But in React v17.0, you can choose not to import React just for JSX. Read this official post for details.)
Below is another way of creating react components with class syntax.
import React from 'react'; class Sample extends React.Component { render() { return ( <div> <h1>Sample</h1> <h2>This is a component.</h2> </div> ); } } export default Sample;
Class component's
render method returns React element.
So, what is the difference between the two and which way should you choose to write your own React components?
In v16.7 and below, class components have state management (
data in Vue.js) and lifecycle methods -- both are crucial for useful components -- and functional ones didn't.
But, from v16.8, React introduced Hooks into functional components. Hooks take care of state management and "side effects" (operations that should happen after rendering).
Although a few lifecycle methods are not "translated" in hooks, functional components can do pretty much the same jobs as class components. And React team recommends functional way for your first choice.
When you’re ready, we’d encourage you to start trying Hooks in new components you write.
In the longer term, we expect Hooks to be the primary way people write React components.
Should I use Hooks, classes, or a mix of both?
So if you start brand new React project, or you are a React beginner, I think you should consider writing in functional way first. And if you want to use class-only features, then introduce class components. It's totally OK that functional components and class components live together.
In this article, I explain about functional way.
Templating
Vue.js way
Vue component's
<template> has its own syntax such as
v-bind,
v-for,
v-if.
<template> <div> <h1>Hello, {{ name }} !</h1> <a :Click me</a> <ul> <li v- {{ item.title }} </li> </ul> <p v-Paragraph</p> <p v-Second paragraph</p> </div> </template>
React way
In React, you use JSX.
return ( <div> <h1>Hello, {name} !</h1> <a href={link}>Click me</a> <ul> {items.map(item => ( <li key={item.key}>{item.title}</li> ))} </ul> {isActive && <p>Paragraph</p>} <p style={{ display: isShow ? 'initial' : 'none' }}>Second paragraph</p> </div> );
- JSX is not a template engine. It has only one special syntax --
{}-- and the rest are just JavaScript.
- statement inside of
{}is evaluated as JavaScript.
- There is no equivalent for
v-show. So basically you should manually manipulate
displayof style attribute.
- I'll talk about CSS classes later.
Just like Vue's
<template>, functional component must return only one root element. But React has convenient helper component
<React.Fragment>. It lets you return multiple elements in order for you not to wrap elements with useless
<div> only for the sake of a framework's requirement.
return ( <React.Fragment> <h1>...</h1> <h2>...</h2> <h3>...</h3> </React.Fragment> );
<React.Fragment> is not rendered as DOM. You just get
<h1>,
<h2> and
<h3> in the exmaple above.
And,
<React.Fragment> has its syntax sugar. Its name can be omit. That is, the snippet above can be written as below.
return ( <> <h1>...</h1> <h2>...</h2> <h3>...</h3> </> );
Odd but handy, huh?
CSS classes
Vue.js way
Vue.js offers
v-bind:class as a way to manipulate HTML
class attribute.
<button class="btn" :...</button> <button class="btn" :...</button>
React way
There is no special way in React.
className is just an equivalent for
class attribute.
class is one of reserved keywords in JavaScript so JSX calls this
className.
return <button className="btn btn-primary">...</button>;
Although, classnames library will help you dealing with HTML classes.
import classNames from 'classnames';
It's just like
v-bind:class.
const buttonClass = classNames({ btn: true, 'btn-primary': isPrimary }); return <button className={buttonClass}>...</button>;
HTML
Vue.js way
For injecting HTML string, you use
v-html in Vue.js.
<div v-</div>
React way
In React, there is a prop named
dangerouslySetInnerHTML. It literally warns you that inserting HTML string carelessly is a dangerous move.
dangerouslySetInnerHTML accepts an object that has
__html property with HTML strings as its value.
return <div dangerouslySetInnerHTML={{ __html: htmlString }} />;
Events
Vue.js way
In Vue.js, events are represented by
@ syntax (sugar for
v-on).
<button @Click me</button> <form @submit....</form>
React way
React takes more HTML-like approach. Event handler is passed to prop named onEventName -- e.g.
onChange,
onSubmit.
const handleClick = e => {/* blah blah... */}; return <button onClick={handleClick}>Click me</button>;
There is no event modifiers like
.prevent.
States (data)
Vue.js way
In Vue.js, component's internal state is defined by a return value of the
data method.
<script> export default { data() { return { count: 0 } } } </script>
Inside other parts of the component, you can reference its state value through
this.
methods: { increment() { this.count += 1; } }
React way
In React, you use
useState hook. Hey, here comes the hook!
import React, { useState } from 'react' function Counter() { const [count, setCount] = useState(0); const handleClick = () => setCount(count + 1); return <button onClick="handleClick">{count}</button>; }
Hooks are functions for accessing React's magic.
useState is the one for managing component's state.
useState takes state's default value as an argument, and returns array that contains 0. "state variable" and 1. "function that update state". State's value can only be updated through that function.
Call
useState by individual states.
const [name, setName] = useState("John Doe"); const [age, setAge] = useState(20);
You can set object as state's value.
const [user, setUser] = useState({ name: "John Doe", age: 20 });
Forms
Vue.js way
In Vue.js,
v-model handles form inputs.
<input type="text" v-
v-model lets you implement bi-directional data flow.
React way
React doesn't introduce sytax sugar for bi-directional data update. You have to implement it on your own by combining state and event.
const [name, setName] = useState(''); const handleInput = e => setName(e.target.value); return <input type="text" onChange="handleInput" value="name" />;
It's a bit annoying writing this boilerplate almost everytime dealing with forms. But I think this kind of simplicity, or "give you no sugar", "write what you need on your own as possible" style is very React-ish.
methods
Vue.js way
Inside of methods defined in
methods, you can reference states (
data). And the methods can be referenced inside your template.
<script> export default { methods: { sayHello() { console.log(`Hello, ${this.name}!`) } } } </script>
React way
There's nothing like Vue's
methods in React. React component is essentially just a JavaScript function, so you treat it as it is.
function MyComponent() { const [name, setName] = useState('John'); function sayHello() { console.log(`Hello, ${name}!`); } return <button onClick={sayHello}>...</button>; }
ref
Vue.js way
In Vue.js,
ref gives you direct access to the DOM.
<template> <div> <div ref="foo">...</div> <button @Click me</button> </div> </template> <script> export default { methods: { handleClick() { console.log(this.$refs.foo); } } } </script>
React way
React has similar functionality as Vue's
ref.
With
useRef hook, you can create a "ref object" for accessing DOM. The object's
current property contains reference for the DOM.
import React, { useRef } from 'react'; function MyComponent() { const target = useRef(null); const handleClick = () => { console.log(target.current); }; return ( <> <div ref={target}>...</div> <button onClick={handleClick}>Click me</button> </> ); } export default MyComponent;
computed properties
Vue.js way
Vue.js has "computed properties".
<p>Hello, {{ fullName }} !</p>
export default { data() { return { firstName: 'John', lastName: 'Doe' }; }, computed: { fullName() { return `${this.firstName} ${this.lastName}`; } } }
Computed properties are functions that capture the results of computation, and behave like properties in the template block.
React way
I think
useMemo hook is React version of "computed property".
import React, { useMemo } from 'react'; function MyComponent() { const [firstName, setFirstName] = useState("John"); const [lastName, setlastName] = useState("Doe"); const fullName = useMemo(() => { return `${firstName} ${lastName}`; }, [firstName, lastName]); return <p>Hello, {fullName} !</p>; }
useMemo takes function as 1st argument and array as 2nd argument, and returns memoized value.
- React's functional component is re-rendered everytime props or states are updated.
- But a function of
useMemo's 1st argument only be re-calculated when values in an array passed as 2nd argument are updated.
- If the values in 2nd argument array are not updated, cached value will be returned.
This behavior is similar to Vue's computed property, but it's not so much common pattern as computed property. You should use
useMemo only when there's a real need for optimization (I learned this from this post).
watch
Vue.js way
Vue.js offers you watchers -- "more generic way to react to data changes".
export default { watch: { name(valueAfterUpdate, valueBeforeUpdate) { // ... } } }
React way
React has no equivalent for watchers.
You can implement something like that using
useEffect hook. I will show you that hook in next section.
But I oftern think that there're not so many use-cases for the
watch option, because most of the time, it can be replaced with on-change event.
Lifecycles
Vue.js way
Vue.js has many lifecycle hooks.
export default { created() {/* ... */}, mounted() {/* ... */}, updated() {/* ... */}, destroyed() {/* ... */} }
React way
In React functional component, there is no concept of lifecycle. It's much simpler here.
- functional component is rendered and re-rendered when its props or states are updated.
- if you want to do something just after rendering, put that operation in the
useEffecthook.
import React, { useState, useEffect } from 'react'; function MyComponent() { const [items, setItems] = useState([]); useEffect(() => { someApi.getItems().then(response => { setItems(response.data); }); }, []);
useEffect behaves differently depending on what is passed as a 2nd argument.
// if there is no 2nd argument, // 1st argument is called on every renders. useEffect(() => {}); // if 2nd argument is an empty array, // 1st argument is called only on first render. useEffect(() => {}, []); // this is like "mounted" in Vue.js // if 2nd argument contains one or more items, // 1st argument is called on first render and when the items are updated. useEffect(() => {}, [aaa, bbb]); // this is like "mounted" plus "updated" & "watch", I guess.
useEffect's 1st argument can return "clean up" function, that is called just before its component is removed from the DOM.
import React, { useEffect } from 'react'; function MyComponent() { useEffect(() => { // ... return () => { // clean up function. // this is like "destroyed" in Vue. }; }, []); return <div>...</div>; }
On the other hand, class components have
constructor and lifecycle methods that work just like Vue.js. I don't show you around in this article, but you can learn about these from this post.
Interaction between components
props
Vue.js way
props option is used for passing data from parent component to its child.
<Child :
<script> function Item(one, two) { this.one = one this.two = two } export default { // validate its value with "type" and "required". props: { name: { type: String, required: false, default: 'John Doe' }, item: { type: Item, required: true } } } </script>
React way
In React, properties / attributes passed from parent to children are also called
props.
<Child name={test} item={sampleData} />
1st argument of a functional component is the props.
import React from 'react'; function Child(props) { // props.name // props.item }
You can use prop-types library for validation.
import React from 'react'; import PropTypes from 'prop-types'; function Child(props) { // props.name // props.item } Child.propTypes = { name: PropTypes.string, item: PropTypes.shape({ one: PropTypes.string.isRequired, two: PropTypes.number.isRequired }).isRequired }; Child.defaultProps = { name: 'John Doe' }; export default Child
emitting events
Vue.js way
In Vue.js, child component notifies event with
$emit method to its parent.
onSomethingHappened() { this.$emit('hello'); }
Then, register a handler for a notified event with
@ syntax.
<Child @
React way
React has no syntax for event emitting. You just pass a handler function as a prop -- i.e. parent component determine what to do and children execute that.
function Child({ onHello }) { const handleClick = () => { console.log('hello there'); onHello(); }; return <button onClick={handleClick}>click me</button>; }
function Parent() { const parentMethod = () => {/* blah blah... */}; return <Child onHello={parentMethod} />; }
slot
Vue.js way
Vue.js has
slot for inserting child elements.
<Content> <p>Hello world</p> </Content>
Content component be like:
<template> <article> <h1>This is a title.</h1> <slot></slot> </article> </template>
When you have more that one blocks to insert, you can name each of those.
<MyComponent> <template #header> <MyHeader /> </template> <template #content> <MyContent /> </template> <template #footer> <MyFooter /> </template> </MyComponent>
React way
In React,
children prop has inserted elements.
<Content> <p>Hello world</p> </Content>
function Content({ children }) { // children -> <p>Hello world</p> return ( <article> <h1>This is a title.</h1> {children} </article> ); }
You can neither have multiple
children nor name it.
But
children is just a prop. The example above is essentially same as below:
<Content children={<p>Hello world</p>} />
So you can just do this for inserting multiple elements.
return ( <MyComponent header={<MyHeader />} content={<MyContent />} footer={<MyFooter />} /> );
function MyComponent({ header, content, footer }) { return ( <div> <header>{header}</header> <main>{content}</main> <footer>{footer}</footer> </div> ) }
Wrapping up
Here is my impression:
- React is much simpler than Vue.js, and, more rooms for you to improvise.
- Vue.js has more APIs but is more easy to learn.
In that sense, I think Vue.js is well designed. I recommend Vue.js especially for new JS framework learners. It's also my first JS framework that I succeeded to learn (I failed with angular.js before that).
But, now I like React more. It's simple and enough.
Which one do you prefer?
So, that's all folks! Thanks for reading. Hope you enjoyed and this helps your learning!
Discussion (5)
For me, Vue covers most of the common application functions with a clean and simple API. V-for, v-on, v-if, v-model all make complete sense and the resulting html code is easy to read. It insulated new developments from some of the complexity of JavaScript: map and filter, object destructuring, asynchronous code execution. The one I love and hate at the same time is the hijack of this. Hoisting it so that it infers the data and methods object is mad-genious but doesn't help new devs to grasp the context sensitive nature of this and also prevents fat-arrow functions as they can't support the this override.
You should try a new version of this article with the Vue.js 3 changes, you might be positively surprised about Vue again.
Good article, but this needs to include Vue 3's newest features. And, I highly disagree that React is simpler than Vue. I'd also not call React's being more flexible, i.e. "room to improvise" a good thing. Stricter API's means "best practices" aren't needed as much, which means learning curves aren't as steep or rather cognitive load is less.
Scott
Brilliant article! Thanks so much!
This article help me so much to discover ReactJs through VueJs, really simple to understand. Very good comparison between Vue to React, easily to understand 👍 | https://practicaldev-herokuapp-com.global.ssl.fastly.net/_masahiro_h_/vue-js-developers-guide-to-react-lg0 | CC-MAIN-2022-05 | en | refinedweb |
sieve_compare_operands
Name
sieve_compare_operands — execute a sieve comparator match
Synopsis
#include "sieve/ecsieve.h"
|
int **sieve_compare_operands** ( | seng, | |
| | comp, | |
| | left, | |
| | right
); | |
SENG * <var class="pdparam">seng</var>;
struct sieve_compare_info * <var class="pdparam">comp</var>;
SIEVEARGS * <var class="pdparam">left</var>;
SIEVEARGS * <var class="pdparam".
execute a sieve comparator match.
Performs a standard sieve matching operation, based on the comparison information provided.
If the right operand was previously compiled, that compiled state will be re-used.
Returns a boolean to indicate a successful match according to the criteria provided. | https://support.sparkpost.com/momentum/3/3-api/apis-sieve-compare-operands | CC-MAIN-2022-05 | en | refinedweb |
Made peephole a configurable option call compilation in cross works now Not done yet: - peephole itself - Create as alit, - DOES> compilation
1: /* 2: This is a generic file for 32-bit machines with IEEE FP arithmetic (no VMS). 3: It only supports indirect threading. 4: 5: Copyright (C) 1995,1998,1999: 24: #ifndef THREADING_SCHEME 25: #define THREADING_SCHEME 6 26: #endif 27: 28: #ifdef GFORTH_DEBUGGING 29: /* schedule the ip update after the rest of the primitive; 30: never mind speed */ 31: #undef THREADING_SCHEME 32: #ifdef DIRECT_THREADED 33: #define THREADING_SCHEME 10 34: #else 35: #define THREADING_SCHEME 8 36: #endif /* DIRECT_THREADED */ 37: #endif /* GFORTH_DEBUGGING */ 38: 39: 40: /* define SYSCALL */ 41: 42: #ifndef SYSCALL 43: #define SYSCALL 44: #endif 45: 46: #ifndef SYSSIGNALS 47: #define SYSSIGNALS 48: #endif 49: 50: #ifndef USE_FTOS 51: #ifndef USE_NO_FTOS 52: /* keep top of FP stack in register. Since most processors have FP 53: registers and they are hardly used in gforth, this is usually a 54: good idea. The 88100 has no separate FP regs, but many general 55: purpose regs, so it should be ok */ 56: #define USE_FTOS 57: #endif 58: #endif 59: /* I don't do the same for the data stack (i.e. USE_TOS), since this 60: loses on processors with few registers. USE_TOS might be defined in 61: the processor-specific files */ 62: 63: #ifdef DIRECT_THREADED 64: /* If you want direct threading, write a .h file for your processor! */ 65: /* We could put some stuff here that causes a compile error, but then 66: we could not use this file in the other machine.h files */ 67: #endif 68: 69: /* Types: these types are used as Forth's internal types */ 70: 71: /* define this if IEEE singles and doubles are available as C data types */ 72: #define IEEE_FP 73: 74: /* the IEEE types are used only for loading and storing */ 75: /* the IEEE double precision type */ 76: typedef double DFloat; 77: /* the IEEE single precision type */ 78: typedef float SFloat; 79: 80: typedef CELL_TYPE Cell; 81: typedef unsigned CELL_TYPE UCell; 82: typedef Cell Bool; 83: typedef unsigned char Char; 84: typedef double Float; 85: typedef Char *Address; 86: 87: #if defined(DOUBLY_INDIRECT) 88: typedef void **Label; 89: #else /* !defined(DOUBLY_INDIRECT) */ 90: typedef void *Label; 91: #endif /* !defined(DOUBLY_INDIRECT) */ 92: 93: /* feature defines */ 94: 95: #define HAS_DCOMPS 96: #define HAS_FILE 97: #define HAS_FLOATING 98: #define HAS_GLOCALS 99: #define HAS_HASH 100: #define HAS_OS 101: #define HAS_XCONDS 102: #define HAS_STANDARDTHREADING 103: #define HAS_DEBUG 104: #define HAS_PEEPHOLE 105: 106: #define RELINFOBITS 8 | https://www.complang.tuwien.ac.at/cvsweb/cgi-bin/cvsweb/gforth/arch/generic/machine.h?f=h;only_with_tag=MAIN;content-type=text%2Fx-cvsweb-markup;ln=1;rev=1.13 | CC-MAIN-2022-05 | en | refinedweb |
Bob, They are actually the same thing. Lift's processing directives are simply built-in snippets. You can, if you dare, override their functionality. :-)
Thanks, David On Fri, Apr 10, 2009 at 11:23 AM, bob <rbpas...@gmail.com> wrote: > > if I see <lift:XXXX/>, it could mean one of two things: a directive, > e.g., <lift:bind/> or <lift:surround/> or shorthand for a snippet, eg > <lift:myClass> represents <lift:snippet > > i guess I would like to see these disambiguated a shorthand for > snippets that doesn't overlap with the directive namespace. > > some possible solutions: > > 1. <lift:bind/> would be the directive and <lift:.bind/> would be the > snippet. please don't get hung up on my use of dot. it is only an > example, and not an actual suggestion. > > 2. <lift:bind/> maps to a real class, not some internal code, much the > way <lift:msgs/> maps to net.liftweb.builtin.snippets.Msgs (thanks > Jorge) > > 3. <lift:bind> is the directive, and <liftsnippet:bind> is the snippet > > comments? > > thanks, bob > > > > > -- Lift, the simply functional web framework Beginning Scala Follow me: Git some: --~--~---------~--~----~------------~-------~--~----~ -~----------~----~----~----~------~----~------~--~--- | https://www.mail-archive.com/liftweb@googlegroups.com/msg04707.html | CC-MAIN-2022-05 | en | refinedweb |
My packages : import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
from plotly.offline import iplot
import plotly.offline as pyo
import matplotlib.pyplot as plt
pyo.init_notebook_mode()
Im trying to save my graph : fig.write_html(“C:/Users/vladi/Documents/Seven Hightest Purchases.html”) And i get this error: AttributeError: ‘dict’ object has no attribute ‘write_html’
Ocra and caleido installed
Can anyone tell me how to save my graph in html format ?
Thanks | https://community.plotly.com/t/write-html-raise-error-attributeerror-dict-object-has-no-attribute-write-html/58861 | CC-MAIN-2022-05 | en | refinedweb |
In this article, we will learn what a heap is in python and its implementation. We will understand max heap and min heap concepts with their python program implementation and the difference between max-heap and min-heap. Lastly, we will learn the time complexity and applications of heap data structure. So, let's get started!
What is Heap?
Heap is a data structure that follows a complete binary tree's property and satisfies the heap property. Therefore, it is also known as a binary heap. As we all know, the complete binary tree is a tree with every level filled and all the nodes are as far left as possible. In the binary tree, it is possible that the last level is empty and not filled. Now, you must be wondering what is the heap property? In the heap data structure, we assign key-value or weight to every node of the tree. Now, the root node key value is compared with the children’s nodes and then the tree is arranged accordingly into two categories i.e., max-heap and min-heap. Heap data structure is basically used as a heapsort algorithm to sort the elements in an array or a list. Heapsort algorithms can be used in priority queues, order statistics, Prim's algorithm or Dijkstra's algorithm, etc. In short, the heap data structure is used when it is important to repeatedly remove the objects with the highest or the lowest priority.
As learned earlier, there are two categories of heap data structure i.e. max-heap and min-heap. Let us understand them below but before that, we will study the heapify property to understand max-heap and min-heap.
What is Heapify?
Before moving forward with any concept, we need to learn what is heapify. So, the process of creating a heap data structure using the binary tree is called Heapify. The heapify process is used to create the Max-Heap or the Min-Heap. Let us study the Heapify using an example below:
Consider the input array as shown in the figure below:
Using this array, we will create the complete binary tree
We will start the process of heapify from the first index of the non-leaf node as shown below:
Now we will set the current element “k” as “largest” and as we know the index of a left child is given by “2k + 1” and the right child is given by “2k + 2”.
Therefore, if the left child is larger than the current element i.e. kth index we will set the “largest” with the left child’s index and if the right child is larger than the current element i.e., kth index then we will set the “largest” with right child’s index.
Lastly, we will swap the “largest” element with the current element(kth element).
We’ll repeat the above steps 3-6 until the tree is heaped.
Algorithm for Max-Heapify
maxHeapify(array, size, k) set k as largest leftChild = 2k + 1 rightChild = 2k + 2 if leftChild > array[largest] set leftChildIndex as largest if rightChild > array[largest] set rightChildIndex as largest swap array[k] and array[largest]
Algorithm for Min-Heapify
minHeapify(array, size, k) set k as smallest leftChild = 2k + 1 rightChild = 2k + 2 if leftChild < array[smallest] set leftChildIndex as smallest if rightChild < array[smallest] set rightChildIndex as smallest swap array[k] and array[smallest]
What is Max Heap?
When the value of each internal node is larger than or equal to the value of its children node then it is called the Max-Heap Property. Also, in a max-heap, the value of the root node is largest among all the other nodes of the tree. Therefore, if “a” has a child node “b” then
Key(a) >= key(b)
represents the Max Max Heap
MaxHeap(array, size) loop from the first index down to zero call maxHeapify
Algorithm for Insertion in Max Heap
If there is no node, create a new Node. else (a node is already present) insert the new Node at the end maxHeapify the array
Algorithm for Deletion in Max Heap
If nodeDeleted is the leaf Node remove the node Else swap nodeDeleted with the lastNode remove nodeDeleted maxHeapify the array
Python Code for Max Heap Data Structure
def max_heapify(A,k): l = left(k) r = right(k) if l < len(A) and A[l] > A[k]: largest = l else: largest = k if r < len(A) and A[r] > A[largest]: largest = r if largest != k: A[k], A[largest] = A[largest], A[k] max_heapify(A, largest) def left(k): return 2 * k + 1 def right(i): return 2 * k + 2 def build_max_heap(A): n = int((len(A)//2)-1) for k in range(n, -1, -1): max_heapify(A,k) A = [3,9,2,1,4,5] build_max_heap(A) print(A)
Output
[9, 4, 5, 1, 3, 2]
What is Min Heap?
When the value of each internal node is smaller than the value of its children node then it is called the Min-Heap Property. Also, in the min-heap, the value of the root node is the smallest among all the other nodes of the tree. Therefore, if “a” has a child node “b” then
Key(a) < key(b)
represents the Min Min Heap
MinHeap(array, size) loop from the first index down to zero call minHeapify
Algorithm for Insertion in Min Heap
If there is no node, create a new Node. else (a node is already present) insert the new Node at the end minHeapify the array
Algorithm for Deletion in Min Heap
If nodeDeleted is the leaf Node remove the node Else swap nodeDeleted with the lastNode remove nodeDeleted minHeapify the array
Python Code for Min Heap Data Structure
def min_heapify(A,k): l = left(k) r = right(k) if l < len(A) and A[l] < A[k]: smallest = l else: smallest = k if r < len(A) and A[r] < A[smallest]: smallest = r if smallest != k: A[k], A[smallest] = A[smallest], A[k] min_heapify(A, smallest) def left(k): return 2 * k + 1 def right(k): return 2 * k + 2 def build_min_heap(A): n = int((len(A)//2)-1) for k in range(n, -1, -1): min_heapify(A,k) A = [3,9,2,1,4,5] build_min_heap(A) print(A)
Output
[1, 3, 2, 9, 4, 5]
Min Heap vs Max Heap
Time complexity
The running time complexity of the building heap is O(n log(n)) where each call for heapify costs O(log(n)) and the cost of building heap is O(n). Therefore, the overall time complexity will be O(n log(n)).
Applications of Heap
- Heap is used while implementing priority queue
- Heap is used in Heap sort
- Heap data structure is used while working with Dijkstra's algorithm
- We can use max-heap and min-heap in the operating system for the job scheduling algorithm
- It is used in the selection algorithm
- Heap data structure is used in graph algorithms like prim’s algorithm
- It is used in order statistics
- Heap data structure is used in k-way merge
Conclusion
Heap data structure is a very useful data structure when it comes to working with graphs or trees. Heap data structure helps us improve the efficiency of various programs and problem statements. We can use min-heap and max-heap as they are efficient when processing data sets. As you get a good command of heap data structure, you are great to work with graphs and trees at the advanced level. | https://favtutor.com/blogs/heap-in-python | CC-MAIN-2022-05 | en | refinedweb |
Many of you must be familiar with the application of a linked list in the real world and its importance. We use linked lists to maintain a directory of names, dynamic allocation of memory, and create an implementation of essentials data structures like stacks and queues, and what not?
Knowing all this in this tutorial we are going to discuss the basic understanding of a linked list, and implement and analyze how to reverse a linked list in C++. Let’s get Kraken!
What is Linked List?
The general definition is that a linked list is a sequence of data structures, the nodes are connected with pointers, and the last node points to NULL.
A linked list is a sequence of links that contain elements connected using pointers. Each link which is a pointer contains a connection to another node. The linked list is the second most utilized data structure after arrays.
There are three components of a linked list:
Node − Each node stores data which is called an element.
Next − Every node of a linked list contains a link to the next link that is Next.
Head − A Linked List contains the pointer to the first link called a head pointer.
How to Reverse a Linked List?
Reversing the list implies reversing all the elements and we can do it by reversing all the links and make the next pointer point to the previous node.
Problem Description
In this problem statement we are provided with the pointer or reference to the head of a singly linked list, invert the list, and return the pointer or reference to the head of the new reversed linked list.
For example, consider the following linked list:
After reversing the complete linked list we return the pointer to the new linked list as demonstrated in the figure:
There can be two approaches to solve this problem, the following are the hints, try solving the problem by yourself and then head over to the next section to find the solution and C++ code.
Hints
- Think of an iterative approach to find the reversed list in a single pass.
- Or, think of a recursive approach to find the reversed list in a single pass.
Now that you have tried solving the problem yourself given the two types of approaches to solving this problem, let’s discuss both the approaches one by one:
Iterative Solution for Reversing a Linked List
If the linked list has only one or no element, then we return the current list as it is. And if there are two or more elements, then we can implement an iterative solution using three-pointers
We will create a function to reverse the linked list taking reference to the head node and as the only argument and return the head of the new linked list:
Step 1: Define three nodes one with the reference to the head node and name it current, and name the other two nodes temp and prev pointers as NULL.
Step 2: Using a while loop we will traverse the linked list once until the next pointer does not become NULL.
Step 3: While iterating, we perform the following operations:
temp = current->next;
current->next = prev;
prev = current;
current = temp;
We assign the temp node to the next of the current node and then reverse the link by assign the current->next to the previous node. And then increment the previous node to the current node and then the current node to the temp node.
And then we finally return the head node.
Iterative Implementation
The iterative implementation of reversing a linked list in c++ follows:-
#include<bits/stdc++.h> using namespace std; struct node { int data; struct node *next; }; // To create a demo we have to construct a linked list and this // function is to push the elements to the list. void push(struct node **head_ref, int data) { struct node *node; node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->next = (*head_ref); (*head_ref) = node; } // Function to reverse the list void reverse(struct node **head_ref) { struct node *temp = NULL; struct node *prev = NULL; struct node *current = (*head_ref); while(current != NULL) { temp = current->next; current->next = prev; prev = current; current = temp; } (*head_ref) = prev; } // To check our program void printnodes(struct node *head) { while(head != NULL) { cout<<head->data<<" "; head = head->next; } } // Driver function int main() { struct node *head = NULL; push(&head, 0); push(&head, 1); push(&head, 8); push(&head, 0); push(&head, 4); push(&head, 10); cout << "Linked List Before Reversing" << endl; printnodes(head); reverse(&head); cout << endl; cout << "Linked List After Reversing"<<endl; printnodes(head); return 0; }
Output:
Linked List Before Reversing
10 4 0 8 1 0
Linked List After Reversing
0 1 8 0 4 10
Time complexity:
O(N) because we iterate through each element at least once.
Space complexity:
O(1) because no extra space was used here.
Recursive solution for Reversing a Linked List
The most important thing to remember in this approach is that the recursive approach uses a stack. The compiler allocates stack memory after each recursive call, and this solution can run out of memory in case of very huge linked lists (think billions of elements).
We recursively iterate to each node in the list until we reach the last node and return the new head. We have to note that the last node in this approach will become the new head of the list. On the return path, each node is going to append itself to the end of the partially reversed linked list.
Recursive Implementation
The recursive implementation of reversing a linked list in c++ follows:-
#include using namespace std; struct Node { int data; struct Node* next; Node(int data) { this->data = data; next = NULL; } }; struct LinkedList { Node* head; LinkedList() { head = NULL; } Node* reverse(Node* head) { if (head == NULL || head->next == NULL) return head; // Recursive call Node* rest = reverse(head->next); head->next->next = head; head->next = NULL; return rest; } void print() { struct Node* temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } void push(int data) { Node* temp = new Node(data); temp->next = head; head = temp; } }; int main() { LinkedList ll; ll.push(320); ll.push(34); ll.push(315); ll.push(385); cout << "Linked List Before Reversing\n"; ll.print(); ll.head = ll.reverse(ll.head); cout << "\nLinked List After Reversing \n"; ll.print(); return 0; }
Output:
Linked List Before Reversing
385 315 34 320
Linked List After Reversing
320 34 315 385
Time Complexity:
O(N) because we iterate through each element at least once.
Space complexity:
O(N) because we create a recursive stack each time we call the reverse function recursively.
Conclusion
In this tutorial, we learned how to reverse a link using two approaches, and discussed the code in C++. This question is frequently asked in technical interviews by huge companies like Amazon and Google. | https://favtutor.com/blogs/reverse-a-linked-list-cpp | CC-MAIN-2022-05 | en | refinedweb |
Using the Intel Galileo for Internet-of-Things projects is a natural fit. With Arduino pin compatibility, networking, and Linux, it’s a powerful yet flexible board that can control hardware, handle computing jobs ordinary microcontrollers can’t, and send and receive information from the internet. And what information is more important than knowing when to expect the next volume of MAKE?
I’ve created a website called How Many Days Until MAKE Comes Out? that serves one simple purpose: It tells you how many days until the next issue of MAKE magazine is scheduled to hit newsstands. The source code is available at github.com/mrichardson23/nextmakemagazine if you want to see how I made it.
Go to nextmakemagazine.appspot.com in your web browser, and you’ll see the information is formatted to be viewed and understood by a human. Next, visit nextmakemagazine.appspot.com/simple and you’ll see the server is also configured to speak directly to microcontrollers, by stripping away all the extra style and language and only returning the number of hours until the next issue is released.
Your Galileo can use its internet connection via Ethernet to connect to this URL, receive the data, and evaluate how to display it in your home. We’ll pass this data from the Linux side to the Arduino side — a powerful feature of this board — and then display it on a standard LCD.
What is Galileo?
The Intel Galileo is an innovative new microcontroller that runs Linux out of the box and supports Arduino programming and most Arduino shields. It’s based on the Intel Quark SoC X1000, a 32-bit Intel Pentium-class system on a chip, so it’s more capable than many other controller boards.
In addition to the familiar Arduino hardware, the Galileo board has a full-sized Mini-PCI Express slot, 100Mb Ethernet port, MicroSD slot, RS-232 serial port, USB Host port, USB Client port, and 8MByte NOR flash memory.
The Galileo also has the ability (unlike others) to multitask while operating an Arduino sketch — which opens up a world of new opportunities for your projects.
This project is adapted from the new book Getting Started with Intel Galileo, available from the Maker Shed (makershed.com).
Testing the Connections
First, make sure your Galileo can connect to the server.
- Connect the Galileo via an Ethernet cable to your network, plugging it into your router or an active Ethernet jack.
- Connect the Galileo to power.
- Connect your computer to Galileo via the USB client port.
- Launch the Arduino IDE software and select File → Examples → Ethernet → WebClient.
- Click Upload.
- Open the Serial Monitor.
You’ll see text start to appear in the Serial Monitor. This example programs your Galileo to do a Google search for the term “Arduino.” As the HTML response from Google’s server is received, it sends those characters to the Serial Monitor.Figure A
void setup() { } void loop() { Serial.println(getHours()); delay(5000); } int getHours() { char output[5]; system("curl > response.txt”); FILE *fp; fp = fopen(“response.txt”, “r”); fgets(output, 5, fp); fclose(fp); return atoi(output); }
Now that you’re sure the network connection is working, tell your Galileo to connect to the How Many Days Until MAKE Comes Out? server:
- Create a new sketch and enter the code in Figure A.
- Upload the code and then open the Serial Monitor.
If it worked, you should see the number of hours out printed every 5 seconds in the Serial Monitor.
The loop function has only 2 lines of code. The delay(5000) is what ensures that each iteration of the loop only happens every 5 seconds. But what about Serial.println(getHours());? The innermost function, getHours(), is defined right below the loop function. It requests data from the server, stores that response in a file, and then reads the file and returns an integer value representing the number of hours you’ll need to wait for the new magazine. It’s the atoi() function that looks at the ASCII characters sent by the server, (say, 4 and 5) and outputs their value as an integer (45), which you can use for arithmetic.
Having the Linux command write the data to a file and then having the Arduino sketch read that file is just one way that you can get data into your sketch. This unique Galileo feature is a powerful way to connect different parts of a project together since there are so many ways to read and write files.
Parsing JSON with Python
The example in Figure A is easy because it handles only one simple piece of data. But lots of web services provide several pieces of data structured in a format called JSON, or JavaScript Object Notation.
JSON has become the standard format for transmitting structured data through the web. If you want to read data from a site that offers JSON, you’ll have to parse it. Since this would be difficult to do with Arduino code, you can use other languages on the Galileo to do this job and pass the appropriate information into the Arduino code.
To preview JSON data, visit nextmakemagazine.appspot.com/json in your web browser:
{"totalHours":1469.0,"volumeNumber":"40","daysAway":61}
There are 3 key/value pairs: the number of hours until the next issue, the next volume number, and the number of days until the next issue.Figure B
import json import urllib2 httpResponse = urllib2.urlopen(‘http://↵ nextmakemagazine.appspot.com/json’) jsonString = httpResponse.read() jsonData = json.loads(jsonString) print “Volume”, jsonData[‘volumeNumber’], “will be↵ released in”, jsonData[‘totalHours’], “hours.”
The code in Figure B uses the Python programming language to connect to the server’s JSON feed at nextmakemagazine.appspot.com/json and parses the volume number and number of hours.
- Connect to Galileo’s command line using SSH, Telnet, or serial.
- Change to root’s home directory.
# cd /home/root/
- Launch the text editor vi with the filename json-parse.py to create that file.
# vi json-parse.py
- Along the left side of the screen you’ll see a column of tildes (~). Type the letter i to enter insert mode. An I will appear in the lower left corner of your screen.
- Enter the code from Figure B into vi.
- Hit the Escape key to switch from insert mode to command mode. The I in the lower left corner will disappear and you’ll see a dash instead.
- Type :x and press Enter to save the file and exit vi.
- Test the script by executing the code from the command line.
# python json-parse.py
If you got everything right, you should see the following output on the command line:
Volume 40 will be released in 1473.0 hours.
import json import urllib2 httpResponse = urllib2.urlopen(‘http://↵ nextmakemagazine.appspot.com/json’) jsonString = httpResponse.read() jsonData = json.loads(jsonString) print jsonData[‘daysAway’]Figure D
void setup() { } void loop() { Serial.println(getDays()); delay(5000); } int getDays() { char output[5]; system(“python /home/root/json-parse.py > /response.txt”); FILE *fp; fp = fopen(“response.txt”, “r”); fgets(output, 5, fp); fclose(fp); return atoi(output); }
As you can see, parsing a JSON response from a website isn’t hard when you have Python available to you on Galileo. Now you’ll simply connect the response from Python to your Arduino code.
To try that now, first modify json-parse.py:
- On Galileo’s command line, be sure you’re still in root’s home directory:
# cd /home/root/
- Open the file for editing in vi:
# vi json-parse.py
- Type the letter i to enter insert mode. An I will appear in the lower left corner of your screen.
- Edit the file so that it reflects the code in Figure C.
- In the Arduino IDE, create a new sketch with the code in Figure D. You’ll see it’s very similar to the Arduino code Figure A. Instead of calling curl from the command line, it uses Python to run the script you wrote.
- Upload the code to the board and open the Serial Monitor.
Now you should see the response from the server as the number of days until the next issue of MAKE comes out.
Connecting an LCD Character Display
What good is this information if it can only be seen in your Serial Monitor? Let’s hook up an LCD display to read out the info where anyone can see it (Figure E).
To connect the LCD to Galileo:
- Disconnect your Galileo board from your computer’s USB port and from power.
- Insert the LCD into the breadboard (solder header pins onto it if necessary).
- Insert the potentiometer into the breadboard as well.
- Using your jumper wires, connect the potentiometer and LCD to Galileo as shown in Figure F.
- Connect power to Galileo.
- Connect Galileo to your computer via USB.
- From the Arduino IDE, upload the code in Figure G.
Figure GFigure G
#include LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { lcd.init(1,12,255,11,5,4,3,2,0,0,0,0); lcd.begin(16, 2); lcd.setCursor(3, 0); lcd.print(“days until”); lcd.setCursor(0, 1); lcd.print(“MAKE is here!”); } void loop() { lcd.setCursor(0, 0); lcd.print(“ “); lcd.setCursor(0, 0); lcd.print(getDays()); delay(30*60*1000); } int getDays() { char output[5]; system(“python /home/root/json-parse.py > /response.txt”); FILE *fp; fp = fopen(“response.txt”, “r”); fgets(output, 5, fp); fclose(fp); return atoi(output); }
Conclusion
Now you can easily keep tabs on when the next MAKE will hit newsstands! This is a simple example — you can just imagine the tricks Galileo can do with almost any data on the web. Pick up a copy of Getting Started with Intel Galileo for more network-connected Galileo projects. | https://makezine.com/projects/galileo-make-countdown/ | CC-MAIN-2022-05 | en | refinedweb |
table of contents
NAME¶
strrot13 - encrypt or decrypt string using rot13
SYNOPSIS¶
#include <publib.h> char *strrot13(char *str);
DESCRIPTION¶
str VALUE¶
strrot13 returns its argument.
SEE ALSO¶
AUTHOR¶
Lars Wirzenius (lars.wirzenius@helsinki.fi) | https://manpages.debian.org/testing/publib-dev/strrot13.3pub.en.html | CC-MAIN-2022-05 | en | refinedweb |
In order to be more “pythonic” while writing python code, many best practices are recommended. Python list comprehensions, like “dictionary comprehension” or “set comprehension” or using “warlus operator(introduced in python 3.8 )” is found in use in many python libraries.
Let’s see the basic construct for a python list comprehension.
How to write
new_list = [ expression(i) for i in old_list if condition(i) ]
The above expression shows the way a python list comprehension is written. Note that the the right hand side of the “=” starts with “[” and ends with “]” . This means that whatever we write inside the brackets, generates a list, which is the output for ny python list comprehension .
Let’s see an example for the same. Here we shall be creating a list of items ( squared by it’s original value -> i*i ) if the value of the item ( i ) is even (i %2 == 0 )
new_list = [ i*i for i in old_list if i%2 ==0 ]
Let’s take a look at the below function
def list_comp(): old_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] new_list = [i * i for i in old_list if i % 2 == 0] return new_list
Now if we execute the below function,
print(list_comp())We will have the below output
[0, 4, 16, 36, 64]
The above function uses an old list to generate a new list after applying a filter which checks if the current item is even .
In the above code our expression is i*i and condition is i%2 == 0. For more details let’s look at the github repository for the code.
When to use list comprehension ?
When we want to achieve the below points we should consider using a list comprehension in python
- create a new list from a computation
- create a list using a declarative approach
- we want to apply some filters while creating the list
Benefits of using list comprehension
- As it is a declarative way of creating a new list while using list comprehension, the code becomes more readable.
- By using list comprehension we can avoid using loops and map() , and therefore not care about initializing a new list before the start of the loop or not care about the order of augments passed inside the map() . And thus we are better off in writing code
- List comprehension also enables us to write code by applying filter-logic to wipe out data that are not important | https://www.codegigs.app/python-list-comprehension/ | CC-MAIN-2022-05 | en | refinedweb |
When people who speak different languages get together and talk, they try to use a language that everyone in the group understands.
To achieve this, everyone has to translate their thoughts, which are usually in their native language, into the language of the group. This “encoding and decoding” of language, however, leads to a loss of efficiency, speed, and precision.
The same concept is present in computer systems and their components. Why should we send data in XML, JSON, or any other human-readable format if there is no need for us to understand what they are talking about directly? As long as we can still translate it into a human-readable format if explicitly needed.
Protocol Buffers are a way to encode data before transportation, which efficiently shrinks data blocks and therefore increases speed when sending it. It abstracts data into a language- and platform-neutral format.
Table of Contents
- Why do we need Protocol Buffers?
- What are Protocol Buffers and how do they work?
- Protocol Buffers in Python
- Final notes
Why Protocol Buffers?
The initial purpose of Protocol Buffers was to simplify the work with request/response protocols. Before ProtoBuf, Google used a different format which required additional handling of marshaling for the messages sent.
In addition to that, new versions of the previous format required the developers to make sure that new versions are understood before replacing old ones, making it a hassle to work with.
This overhead motivated Google to design an interface that solves precisely those problems..
Another interesting use case is how Google uses it for short-lived Remote Procedure Calls (RPC) and to persistently store data in Bigtable. Due to their specific use case, they integrated RPC interfaces into ProtoBuf. This allows for quick and straightforward code stub generation that can be used as starting points for the actual implementation. (More on ProtoBuf RPC.)
Other examples of where ProtoBuf can be useful are for IoT devices that are connected through mobile networks in which the amount of sent data has to be kept small or for applications in countries where high bandwidths are still rare. Sending payloads in optimized, binary formats can lead to noticeable differences in operation cost and speed.
Using
gzip compression in your HTTPS communication can further improve those metrics.
What are Protocol buffers and how do they work?
Generally speaking, Protocol Buffers are a defined interface for the serialization of structured data. It defines a normalized way to communicate, utterly independent of languages and platforms.
Google advertises its ProtoBuf like this:
Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once …
The ProtoBuf interface describes the structure of the data to be sent. Payload structures are defined as “messages” in what is called Proto-Files. Those files always end with a
.proto extension.
For example, the basic structure of a todolist.proto file looks like this. We will also look at a complete example in the next section.
syntax = "proto3"; // Not necessary for Python, should still be declared to avoid name collisions // in the Protocol Buffers namespace and non-Python languages package protoblog; message TodoList { // Elements of the todo list will be defined here ... }
Those files are then used to generate integration classes or stubs for the language of your choice using code generators within the protoc compiler. The current version, Proto3, already supports all the major programming languages. The community supports many more in third-party open-source implementations.
Generated classes are the core elements of Protocol Buffers. They allow the creation of elements by instantiating new messages, based on the
.proto files, which are then used for serialization. We’ll look at how this is done with Python in detail in the next section.
Independent of the language for serialization, the messages are serialized into a non-self-describing, binary format that is pretty useless without the initial structure definition.
The binary data can then be stored, sent over the network, and used any other way human-readable data like JSON or XML is. After transmission or storage, the byte-stream can be deserialized and restored using any language-specific, compiled protobuf class we generate from the .proto file.
Using Python as an example, the process could look something like this:
First, we create a new todo list and fill it with some tasks. This todo list is then serialized and sent over the network, saved in a file, or persistently stored in a database.
The sent byte stream is deserialized using the parse method of our language-specific, compiled class.
Most current architectures and infrastructures, especially microservices, are based on REST, WebSockets, or GraphQL communication. However, when speed and efficiency are essential, low-level RPCs can make a huge difference.
Instead of high overhead protocols, we can use a fast and compact way to move data between the different entities into our service without wasting many resources.
But why isn’t it used everywhere yet?
Protocol Buffers are a bit more complicated than other, human-readable formats. This makes them comparably harder to debug and integrate into your applications.
Iteration times in engineering also tend to increase since updates in the data require updating the proto files before usage.
Careful considerations have to be made since ProtoBuf might be an over-engineered solution in many cases.
What alternatives do I have?
Several projects take a similar approach to Google’s Protocol Buffers.
Google’s Flatbuffers and a third party implementation, called Cap’n Proto, are more focused on removing the parsing and unpacking step, which is necessary to access the actual data when using ProtoBufs. They have been designed explicitly for performance-critical applications, making them even faster and more memory efficient than ProtoBuf.
When focusing on the RPC capabilities of ProtoBuf (used with gRPC), there are projects from other large companies like Facebook (Apache Thrift) or Microsoft (Bond protocols) that can offer alternatives.
Python and Protocol Buffers
Python already provides some ways of data persistence using pickling. Pickling is useful in Python-only applications. It's not well suited for more complex scenarios where data sharing with other languages or changing schemas is involved.
Protocol Buffers, in contrast, are developed for exactly those scenarios.
The
.proto files, we’ve quickly covered before, allow the user to generate code for many supported languages.
To compile the
.proto file to the language class of our choice, we use protoc, the proto compiler.
If you don’t have the protoc compiler installed, there are excellent guides on how to do that:
Once we’ve installed protoc on our system, we can use an extended example of our todo list structure from before and generate the Python integration class from it.
syntax = "proto3"; // Not necessary for Python but should still be declared to avoid name collisions // in the Protocol Buffers namespace and non-Python languages package protoblog; // Style guide prefers prefixing enum values instead of surrounding // with an enclosing message enum TaskState { TASK_OPEN = 0; TASK_IN_PROGRESS = 1; TASK_POST_PONED = 2; TASK_CLOSED = 3; TASK_DONE = 4; } message TodoList { int32 owner_id = 1; string owner_name = 2; message ListItems { TaskState state = 1; string task = 2; string due_date = 3; } repeated ListItems todos = 3; }
Let’s take a more detailed look at the structure of the
.proto file to understand it.
In the first line of the proto file, we define whether we’re using Proto2 or 3. In this case, we’re using Proto3.
The most uncommon elements of proto files are the numbers assigned to each entity of a message. Those dedicated numbers make each attribute unique and are used to identify the assigned fields in the binary encoded output.
One important concept to grasp is that only values 1-15 are encoded with one less byte (Hex), which is useful to understand so we can assign higher numbers to the less frequently used entities. The numbers define neither the order of encoding nor the position of the given attribute in the encoded message.
The package definition helps prevent name clashes. In Python, packages are defined by their directory. Therefore providing a package attribute doesn’t have any effect on the generated Python code.
Please note that this should still be declared to avoid protocol buffer related name collisions and for other languages like Java.
Enumerations are simple listings of possible values for a given variable.
In this case, we define an Enum for the possible states of each task on the todo list.
We’ll see how to use them in a bit when we look at the usage in Python.
As we can see in the example, we can also nest messages inside messages.
If we, for example, want to have a list of todos associated with a given todo list, we can use the repeated keyword, which is comparable to dynamically sized arrays.
To generate usable integration code, we use the proto compiler which compiles a given .proto file into language-specific integration classes. In our case we use the --python-out argument to generate Python-specific code.
protoc -I=. --python_out=. ./todolist.proto
In the terminal, we invoke the protocol compiler with three parameters:
- -I: defines the directory where we search for any dependencies (we use . which is the current directory)
- --python_out: defines the location we want to generate a Python integration class in (again we use . which is the current directory)
- The last unnamed parameter defines the .proto file that will be compiled (we use the todolist.proto file in the current directory)
This creates a new Python file called <name_of_proto_file>_pb2.py. In our case, it is todolist_pb2.py. When taking a closer look at this file, we won’t be able to understand much about its structure immediately.
This is because the generator doesn’t produce direct data access elements, but further abstracts away the complexity using metaclasses and descriptors for each attribute. They describe how a class behaves instead of each instance of that class.
The more exciting part is how to use this generated code to create, build, and serialize data. A straightforward integration done with our recently generated class is seen in the following:
import todolist_pb2 as TodoList my_list = TodoList.TodoList() my_list.owner_id = 1234 my_list.owner_name = "Tim" first_item = my_list.todos.add() first_item.state = TodoList.TaskState.Value("TASK_DONE") first_item.task = "Test ProtoBuf for Python" first_item.due_date = "31.10.2019" print(my_list)
It merely creates a new todo list and adds one item to it. We then print the todo list element itself and can see the non-binary, non-serialized version of the data we just defined in our script.
owner_id: 1234 owner_name: "Tim" todos { state: TASK_DONE task: "Test ProtoBuf for Python" due_date: "31.10.2019" }
Each Protocol Buffer class has methods for reading and writing messages using a Protocol Buffer-specific encoding, that encodes messages into binary format.
Those two methods are
SerializeToString() and
ParseFromString().
import todolist_pb2 as TodoList my_list = TodoList.TodoList() my_list.owner_id = 1234 # ... with open("./serializedFile", "wb") as fd: fd.write(my_list.SerializeToString()) my_list = TodoList.TodoList() with open("./serializedFile", "rb") as fd: my_list.ParseFromString(fd.read()) print(my_list)
In the code example above, we write the Serialized string of bytes into a file using the wb flags.
Since we have already written the file, we can read back the content and Parse it using ParseFromString. ParseFromString calls on a new instance of our Serialized class using the rb flags and parses it.
If we serialize this message and print it in the console, we get the byte representation which looks like this.
b'\x08\xd2\t\x12\x03Tim\x1a(\x08\x04\x12\x18Test ProtoBuf for Python\x1a\n31.10.2019'
Note the b in front of the quotes. This indicates that the following string is composed of byte octets in Python.
If we directly compare this to, e.g., XML, we can see the impact ProtoBuf serialization has on the size.
<todolist> <owner_id>1234</owner_id> <owner_name>Tim</owner_name> <todos> <todo> <state>TASK_DONE</state> <task>Test ProtoBuf for Python</task> <due_date>31.10.2019</due_date> </todo> </todos> </todolist>
The JSON representation, non-uglified, would look like this.
{ "todoList": { "ownerId": "1234", "ownerName": "Tim", "todos": [ { "state": "TASK_DONE", "task": "Test ProtoBuf for Python", "dueDate": "31.10.2019" } ] } }
Judging the different formats only by the total number of bytes used, ignoring the memory needed for the overhead of formatting it, we can of course see the difference.
But in addition to the memory used for the data, we also have 12 extra bytes in ProtoBuf for formatting serialized data. Comparing that to XML, we have 171 extra bytes in XML for formatting serialized data.
Without Schema, we need 136 extra bytes in JSON for formatting serialized data.
If we’re talking about several thousands of messages sent over the network or stored on disk, ProtoBuf can make a difference.
However, there is a catch. The platform Auth0.com created an extensive comparison between ProtoBuf and JSON. It shows that, when compressed, the size difference between the two can be marginal (only around 9%).
If you’re interested in the exact numbers, please refer to the full article, which gives a detailed analysis of several factors like size and speed.
An interesting side note is that each data type has a default value. If attributes are not assigned or changed, they will maintain the default values. In our case, if we don’t change the TaskState of a ListItem, it has the state of “TASK_OPEN” by default. The significant advantage of this is that non-set values are not serialized, saving additional space.
If we, for example, change the state of our task from TASK_DONE to TASK_OPEN, it will not be serialized.
owner_id: 1234 owner_name: "Tim" todos { task: "Test ProtoBuf for Python" due_date: "31.10.2019" }
b'\x08\xd2\t\x12\x03Tim\x1a&\x12\x18Test ProtoBuf for Python\x1a\n31.10.2019'
Final Notes
As we have seen, Protocol Buffers are quite handy when it comes to speed and efficiency when working with data. Due to its powerful nature, it can take some time to get used to the ProtoBuf system, even though the syntax for defining new messages is straightforward.
As a last note, I want to point out that there were/are discussions going on about whether Protocol Buffers are “useful” for regular applications. They were developed explicitly for problems Google had in mind.
If you have any questions or feedback, feel free to reach out to me on any social media like twitter or email :) | https://www.freecodecamp.org/news/googles-protocol-buffers-in-python/ | CC-MAIN-2022-05 | en | refinedweb |
This chapter describes some general tips related to cross-platform development.
The main include file is
"wx/wx.h"; this includes the most commonly used modules of wxWidgets.
To save on compilation time, include only those header files relevant to the source file. If you are using precompiled headers, you should include the following section before any other includes:
// For compilers that support precompilation, includes "wx.h". #include <wx/wxprec.h> #ifndef WX_PRECOMP // Include your minimal set of headers here, or wx.h # include <wx/wx.h> #endif ... now your other include files ...
The file
"wx/wxprec.h" includes
"wx/wx.h". Although this incantation may seem quirky, it is in fact the end result of a lot of experimentation, and several Windows compilers to use precompilation which is largely automatic for compilers with necessary support. Currently it is used for Visual C++ (including embedded Visual C++) and newer versions of GCC. Some compilers might need extra work from the application developer to set the build environment up as necessary for the support.
All ports of wxWidgets can create either a static library or a shared library.
".so" (Shared Object) under Linux and
".dll" (Dynamic Link Library) under Windows.).
wxWidgets can also be built in multilib and monolithic variants. See the Library List for more information on these.
When (or DEB or other forms of binaries) for installing wxWidgets on Linux, a correct
"setup.h" is shipped in the package and this must not be changed.
On Microsoft Windows, wxWidgets has a different set of makefiles for each compiler, because each compiler's
'make' tool is slightly different. Popular Windows compilers that we cater for, and the corresponding makefile extensions, include: Microsoft Visual C++ (.vc) and MinGW/Cygwin (.gcc). Makefiles are provided for the wxWidgets library itself, samples, demos, and utilities.
On Linux and macOS, you use the
'configure' command to generate the necessary makefiles. You should also use this method when building with MinGW/Cygwin on Windows.
We also provide project files for some compilers, such as Microsoft VC++. However, we recommend using makefiles to build the wxWidgets library itself, because makefiles can be more powerful and less manual intervention is required.
On Windows using a compiler other than MinGW/Cygwin, you would build the wxWidgets library from the
"build/msw" directory which contains the relevant makefiles.
On Windows using MinGW/Cygwin, and on Unix and macOS, you invoke 'configure' (found in the top-level of the wxWidgets source hierarchy), from within a suitable empty directory for containing makefiles, object files and libraries.
For details on using makefiles, configure, and project files, please see
"docs/xxx/install.txt" in your distribution, where
"xxx" is the platform of interest, such as
msw,
gtk,
x11,
mac.
All wxWidgets makefiles are generated using Bakefile. wxWidgets also provides (in the
"build/bakefiles/wxpresets" folder) the wxWidgets bakefile presets. These files allow you to create bakefiles for your own wxWidgets-based applications very easily.
wxWidgets application compilation under MS Windows requires at least one extra file: a.ico
The icon can then be referenced by name when creating a frame icon. See the Microsoft Windows SDK documentation..
In general wxWindow-derived objects should always be allocated on the heap as wxWidgets will destroy them itself. The only, but important, exception to this rule are the modal dialogs, i.e. wxDialog objects which are shown using wxDialog::ShowModal() method. They may be allocated on the stack and, indeed, usually are local variables to ensure that they are destroyed on scope exit as wxWidgets does not destroy them unlike with all the other windows. So while it is still possible to allocate modal dialogs on the heap, you should still destroy or delete them explicitly in this case instead of relying on wxWidgets doing it..
A problem which sometimes arises from writing multi-platform programs is that the basic C types are not defined the same on all platforms. This holds true for both the length in bits of the standard types (such as int and long) as well as their byte order, which might be little endian (typically on Intel computers) or big endian (typically on some Unix workstations). wxWidgets defines types and macros that make it easy to write architecture independent code. The types are:
wxInt32, wxInt16, wxInt8, wxUint32, wxUint16 = wxWord, wxUint8 = wxByte
where wxInt32 stands for a 32-bit signed integer type etc. You can also check which architecture the program is compiled on using the wxBYTE_ORDER define which is either wxBIG_ENDIAN or wxLITTLE_ENDIAN (in the future maybe wxPDP_ENDIAN as well).
The macros handling bit-swapping with respect to the applications endianness are described in the Byte Order section.
One of the purposes of wxWidgets is to reduce the need for conditional compilation in source code, which can be messy and confusing to follow. However, sometimes it is necessary to incorporate platform-specific features (such as metafile use under MS Windows). The wxUSE Preprocessor Symbols symbols listed in the file
setup.h may be used for this purpose, along with any user-supplied ones.
The following documents some miscellaneous C++ issues.
wxWidgets does not use templates (except for some advanced features that are switched off by default) since it is a notoriously unportable feature.
wxWidgets does not use C++ run-time type information since wxWidgets provides its own run-time type information system, implemented using macros.
Some compilers, such as Microsoft C++, support precompiled headers. This can save a great deal of compiling time. The recommended approach is to precompile
"wx.h", using this precompiled header for compiling both wxWidgets itself and any wxWidgets applications. For Windows compilers, two dummy source files are provided (one for normal applications and one for creating DLLs) to allow initial creation of the precompiled header.
However, there are several downsides to using precompiled headers. One is that to take advantage of the facility, you often need to include more header files than would normally be the case. This means that changing a header file will cause more recompilations (in the case of wxWidgets, everything needs to be recompiled since everything includes
"wx.h").
A related problem is that for compilers that don't have precompiled headers, including a lot of header files slows down compilation considerably. For this reason, you will find (in the common X and Windows parts of the library) conditional compilation that under Unix, includes a minimal set of headers; and when using Visual C++, includes
"wx.h". This should help provide the optimal compilation for each compiler, although it is biased towards the precompiled headers facility available in Microsoft C++.
When building an application which may be used under different environments, one difficulty is coping with documents which may be moved to different directories on other machines. Saving a file which has pointers to full pathnames is going to be inherently unportable.
One approach is to store filenames on their own, with no directory information. The application then searches into a list of standard paths (platform-specific) through the use of wxStandardPaths.
Eventually you may want to use also the wxPathList class.
Nowadays the limitations of DOS 8+3 filenames doesn't apply anymore. Most modern operating systems allow at least 255 characters in the filename; the exact maximum length, as well as the characters allowed in the filenames, are OS-specific so you should try to avoid extremely long (> 255 chars) filenames and/or filenames with non-ANSI characters.
Another thing you need to keep in mind is that all Windows operating systems are case-insensitive, while Unix operating systems (Linux, Mac, etc) are case-sensitive.
Also, for text files, different OSes use different End Of Lines (EOL). Windows uses CR+LF convention, Linux uses LF only, Mac CR only.
The wxTextFile, wxTextInputStream, wxTextOutputStream classes help to abstract from these differences. Of course, there are also 3rd party utilities such as
dos2unix and
unix2dos which do the EOL conversions.
See also the Files and Directories section of the reference manual for the description of miscellaneous file handling functions.
It is good practice to use ASSERT statements liberally, that check for conditions that should or should not hold, and print out appropriate error messages.
These can be compiled out of a non-debugging version of wxWidgets and your application. Using ASSERT is an example of `defensive programming': it can alert you to problems later on.
See wxASSERT() for more info.
Using wxString can be much safer and more convenient than using
wxChar*.
You can reduce the possibility of memory leaks substantially, and it is much more convenient to use the overloaded operators than functions such as
strcmp. wxString won't add a significant overhead to your program; the overhead is compensated for by easier manipulation (which means less code).
The same goes for other data types: use classes wherever possible.
XRC(wxWidgets resource files) where possible, because they can be easily changed independently of source code. See the XML Based Resource System (XRC) for more info.
It is common to blow up the problem in one's imagination, so that it seems to threaten weeks, months or even years of work. The problem you face may seem insurmountable: but almost never is. Once you have been programming for some time, you will be able to remember similar incidents that threw you into the depths of despair. But remember, you always solved the problem, somehow!
Perseverance is often the key, even though a seemingly trivial problem can take an apparently inordinate amount of time to solve. In the end, you will probably wonder why you worried so much. That's not to say it isn't painful at the time. Try not to worry – there are many more important things in life.
Reduce the code exhibiting the problem to the smallest program possible that exhibits the problem. If it is not possible to reduce a large and complex program to a very small program, then try to ensure your code doesn't hide the problem (you may have attempted to minimize the problem in some way: but now you want to expose it).
With luck, you can add a small amount of code that causes the program to go from functioning to non-functioning state. This should give a clue to the problem. In some cases though, such as memory leaks or wrong deallocation, this can still give totally spurious results!
This sounds like facetious advice, but it is surprising how often people don't use a debugger. Often it is an overhead to install or learn how to use a debugger, but it really is essential for anything but the most trivial programs.
There is a variety of logging functions that you can use in your program: see Logging.
Using tracing statements may be more convenient than using the debugger in some circumstances (such as when your debugger doesn't support a lot of debugging code, or you wish to print a bunch of variables).
You can use wxDebugContext to check for memory leaks and corrupt memory: in fact in debugging mode, wxWidgets will automatically check for memory leaks at the end of the program if wxWidgets is suitably configured. Depending on the operating system and compiler, more or less specific information about the problem will be logged.
You should also use Debugging macros as part of a "defensive programming" strategy, scattering wxASSERT()s liberally to test for problems in your code as early as possible. Forward thinking will save a surprising amount of time in the long run.
See the Debugging for further information. | https://docs.wxwidgets.org/trunk/page_multiplatform.html | CC-MAIN-2022-05 | en | refinedweb |
formsy-react alternatives and similar libraries
Based on the "Form Logic" category.
Alternatively, view formsy-react alternatives based on common mentions on social networks and blogs.
formik9.9 6.9 formsy-react VS formikBuild forms in React, without the tears 😭 [Moved to:]
react-hook-form9.8 9.7 formsy-react VS react-hook-form📋 React Hooks for form state management and validation (Web + React Native)
redux-form9.5 2.0 formsy-react VS redux-formA Higher Order Component using react-redux to keep form state in a Redux store
react-jsonschema-formA React component for building Web forms from JSON Schema.
Formily9.0 9.8 formsy-react VS FormilyAlibaba Group Unified Form Solution -- Support React/ReactNative/Vue2/Vue3
react-final-form8.9 6.7 formsy-react VS react-final-form🏁 High performance subscription-based form state management for React
surveyjs8.4 9.7 formsy-react VS surveyjsJavaScript Survey and Form Library
react-redux-form7.6 0.0 formsy-react VS react-redux-formCreate forms easily in React with Redux.
tcomb-form6.6 0.0 formsy-react VS tcomb-formForms library for react
JSONForms6.1 8.0 formsy-react VS JSONFormsCustomizable JSON Schema-based forms with React, Angular and Vue support out of the box.
winterfell5.8 0.0 formsy-react VS winterfellGenerate complex, validated and extendable JSON-based forms in React.
newforms5.1 0.0 formsy-react VS newformsIsomorphic form-handling for React
MSON4.2 8.9 formsy-react VS MSON🏗️MSON Lang: Generate an app from JSON
react-validation-mixinSimple validation mixin (HoC) for React.
data-driven-formsReact library for rendering forms.
plexus-form2.8 0.0 formsy-react VS plexus-formA dynamic form component for react using JSON-Schema.
formcat2.1 0.0 formsy-react VS formcatA simple and easy way to control forms in React using the React Context API
MSON-React1.9 7.7 formsy-react VS MSON-ReactReact and Material-UI Rendering Layer for MSON
formhero1.1 0.0 formsy-react VS formheroFully customisable React form utility
cerebral-module-formsForm handling for Cerebral
react-formawesomeReact UI lib for validation forms
Table of Contentsforml - extensible react json schema form generator
@mozartspa/mobx-reactHigh performance, hook-based forms library for React, powered by MobX.
Deliver Cleaner and Safer Code - Right in Your IDE of Choice!
Do you think we are missing an alternative of formsy-react or a related project?
README
Moved!
This project has moved. Starting from 1.0.0 onward, develeopment will continue at
formsy-react
A form input builder and validator for React JS
Background.
What you can do
Build any kind of form element components. Not just traditional inputs, but anything you want and get that validation for free
Add validation rules and use them with simple syntax
Use handlers for different states of your form. Ex. "onSubmit", "onError", "onValid" etc.
Pass external errors to the form to invalidate elements
You can dynamically add form elements to your form and they will register/unregister to the form
Default elements
You can look at examples in this repo or use the formsy-react-components project to use bootstrap with formsy-react, or use formsy-material-ui to use Material-UI with formsy-react.
Install
- Download from this REPO and use globally (Formsy) or with requirejs
- Install with
npm install formsy-reactand use with browserify etc.
- Install with
bower install formsy-react
Changes
[Older changes](CHANGES.md)
How to use
See
examples folder for examples. Codepen demo.
Complete API reference is available here.
Formsy gives you a form straight out of the box
import Formsy from 'formsy-react'; const MyAppForm = React.createClass({ getInitialState() { return { canSubmit: false } }, enableButton() { this.setState({ canSubmit: true }); }, disableButton() { this.setState({ canSubmit: false }); }, submit(model) { someDep.saveEmail(model.email); }, render() { return ( <Formsy.Form onValidSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}> <MyOwnInput name="email" validations="isEmail" validationError="This is not a valid email" required/> <button type="submit" disabled={!this.state.canSubmit}>Submit</button> </Formsy.Form> ); } });
This code results in a form with a submit button that will run the
submit method when the submit button is clicked with a valid email. The submit button is disabled as long as the input is empty (required) or the value is not an email (isEmail). On validation error it will show the message: "This is not a valid email".
Building a form element (required)
import Formsy from 'formsy-react'; const MyOwnInput = React.createClass({ // Add the Formsy Mixin mixins: [Formsy.Mixin], // setValue() will set the value of the component, which in // turn will validate it and the rest of the form changeValue(event) { this.setValue(event.currentTarget.value); }, render() { // Set a specific className based on the validation // state of this component. showRequired() is true // when the value is empty and the required prop is // passed to the input. showError() is true when the // value typed is invalid const className = this.showRequired() ? 'required' : this.showError() ? 'error' : null; // An error message is returned ONLY if the component is invalid // or the server has returned an error message const errorMessage = this.getErrorMessage(); return ( <div className={className}> <input type="text" onChange={this.changeValue} value={this.getValue()}/> <span>{errorMessage}</span> </div> ); } });
The form element component is what gives the form validation functionality to whatever you want to put inside this wrapper. You do not have to use traditional inputs, it can be anything you want and the value of the form element can also be anything you want. As you can see it is very flexible, you just have a small API to help you identify the state of the component and set its value.
Related projects
- formsy-material-ui - A formsy-react compatibility wrapper for Material-UI form components.
- formsy-react-components - A set of React JS components for use in a formsy-react form.
- ...
- Send PR for adding your project to this list!
Contribute
- Fork repo
npm install
npm run examplesruns the development server on
localhost:8080
npm testruns the tests
License
*Note that all licence references and agreements mentioned in the formsy-react README section above are relevant to that project's source code only. | https://react.libhunt.com/formsy-react-alternatives | CC-MAIN-2022-05 | en | refinedweb |
Working with file upload using Java Selenium WebDriver
We have seen how to download file in selenium in this article. Like file download scenario, file upload is also frequently used use case in automation testing.
In this article, lets learn how to upload a file using Java Selenium Webdriver. For python example, visit our article.
Sample HTML:
<!DOCTYPE html> <html> <body> <form action="**"> <input type="file" name="uploadfile" id="uploadfile"/> <input type="button" name="submit" id="submit"/> </form> </body> </html>
As far as Selenium 1 is considered, the way to address this is to place the files in an accessible server and use the attachFile command that points to the correct URL to file location in server.
Things changed in Selenium Webdriver and it comes with native file upload feature. Uploading files in WebDriver is done by simply using the sendKeys() method on the ‘file select’ input field i.e. just enter the path to the file to be uploaded.
There is no setup required for running tests with file upload scenarios locally, all we need to do is use the sendKeys command to type the local path of the file in the file field. This is sufficient and works very well in all drivers.
WebDriver driver = new FirefoxDriver(); driver.get(“”); WebElement upload = driver.findElement(By.id(“myfile”)); upload.sendKeys(“/path-to-file/users.csv”); driver.findElement(By.id(“submit”)).click();
The problem occurs when moving the same test to run in a remote server (for example, Selenium Grid running in some other server). Selenium webdriver has a built-in feature for this scenario as well, all we have to do is use the setFileDetector method to let WebDriver know that you’re uploading files from your local computer to a remote server instead of just typing a path.
Two things happens,
1. The file is base64 encoded
2. java example code:
import java.net.URL; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Platform; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; public class UploadFileTest { private RemoteWebDriver driver; public void setUp() throws Exception { DesiredCapabilities capabilities = DesiredCapabilities.firefox(); capabilities.setCapability("platform", Platform.LINUX); driver = new RemoteWebDriver(new URL(""), capabilities); driver.setFileDetector(new LocalFileDetector()); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } public void testSauce() throws Exception { driver.get(""); WebElement upload = driver.findElement(By.id("uploadfile")); upload.sendKeys("/path-to-file/users.csv"); driver.findElement(By.id("submit")).click(); } public void tearDown() throws Exception { driver.quit(); } }
Note the game changing line ‘driver.setFileDetector(new LocalFileDetector());’ in above sample script. Also please note that this does not affect local test execution and comes into play only when tests are running in remote server.
This sample is to run tests in remote machine and refer files from local i.e. from where execution is controlled. If you want to send files to one machine/local to remote, you must use other file transfer options available outside of selenium.
There are other options like AutoIt and java in built Robot class available to handle this kind of scenario. However it is good to use built-in feature because, there are no dependency on external executables(AutoIt) and tests are not flaky(in case of Robot class).
Hope this helps you efficiently in your Selenium projects. If there are any different approach to work with the file uploads that you know, please use the comment box to share it which will help all. | http://allselenium.info/working-with-file-upload-using-java-selenium-webdriver/ | CC-MAIN-2022-05 | en | refinedweb |
The Gmail API uses
Thread resources
to group email replies with their original message into a single conversation or
thread. This allows you to retrieve all messages in a conversation, in order,
making it easier to have context for a message or to refine search results.
Like messages, threads may also have labels applied to them. However, unlike messages, threads cannot be created, only deleted. Messages can, however, be inserted into a thread.
Contents
Retrieving threads
Threads provide a simple way of retrieving messages in a conversation in order.
By listing a set of threads you can choose to group messages by conversation
and provide additional context. You can retrieve a list of threads using the
threads.list method, or retrieve
a specific thread with
threads.get. You can also
filter threads using the same query parameters as
for the
Message resource. If any
message in a thread matches the query, that thread is returned in the result.
The code sample below demonstrates how to use both methods in a sample that
displays the most chatty threads in your inbox. The
threads.list method
fetches all thread IDs, then
threads.get grabs all messages in each thread.
For those with 3 or more replies, we extract the
Subject line and display the
non-empty ones plus the number of messages in the thread. You'll also find this
code sample featured in the corresponding DevByte video.
Python
def show_chatty_threads(service, user_id='me'): threads = service.users().threads().list(userId=user_id).execute().get('threads', []) for thread in threads: tdata = service.users().threads().get(userId=user_id, id=thread['id']).execute() nmsgs = len(tdata['messages']) if nmsgs > 2: # skip if <3 msgs in thread msg = tdata['messages'][0]['payload'] subject = '' for header in msg['headers']: if header['name'] == 'Subject': subject = header['value'] break if subject: # skip if no Subject line print('- %s (%d msgs)' % (subject, nmsgs))
Adding drafts and messages to threads
If you are sending or migrating messages that are a response to another email or part of a conversation, your application should add that message to the related thread. This makes it easier for Gmail users who are participating in the conversation to keep the message in context.
A draft can be added to a thread as part of creating, updating, or sending a draft message. You can also add a message to a thread as part of inserting or sending a message.
In order to be part of a thread, a message or draft must meet the following criteria:
- The requested
threadIdmust be specified on the
Messageor
Draft.Messageyou supply with your request.
- The
Referencesand
In-Reply-Toheaders must be set in compliance with the RFC 2822 standard.
- The
Subjectheaders must match.
Take a look at the creating a draft or sending a
message examples. In both cases, you would simply
add a
threadId key paired with a thread ID to a message's metadata, the
message object. | https://developers.google.com/gmail/api/guides/threads | CC-MAIN-2022-05 | en | refinedweb |
October 14, 2015
Bi.
To update to or install Bioconductor 3.2:
Install R 3.2. Bioconductor 3.2 has been designed expressly for this version of R.
Follow the instructions at .
There are 80 new packages in this release of Bioconductor.
ABAEnrichment - The package ABAEnrichment is designed to test for enrichment of user defined candidate genes in the set of expressed genes in different human brain regions. The core function ‘aba_enrich’ integrates the expression of the candidate gene set (averaged across donors) and the structural information of the brain using an ontology, both provided by the Allen Brain Atlas project. ‘aba_enrich’ interfaces the ontology enrichment software FUNC to perform the statistical analyses. Additional functions provided in this package like ‘get_expression’ and ‘plot_expression’ facilitate exploring the expression data.
acde - ‘Multivariate Method for Inferential Identification of Differentially Expressed Genes in Gene Expression Experiments’ by J. P. Acosta, L. Lopez-Kleine and S. Restrepo (2015, pending publication).
AnnotationHubData - These recipes convert a wide variety and a growing number of public bioinformatic data sets into easily-used standard Bioconductor data structures.
BBCAnalyzer -.
biobroom -.
caOmicsV - caOmicsV package provides methods to visualize multi-dimentional cancer genomics data including of patient information, gene expressions, DNA methylations, DNA copy number variations, and SNP/mutations in matrix layout or network layout.
CausalR - Causal Reasoning algorithms for biological networks, including predictions, scoring, p-value calculation and ranking
ChIPComp - ChIPComp detects differentially bound sharp binding sites across multiple conditions considering matching control.
CNPBayes - Bayesian hierarchical mixture models for batch effects and copy number.
CNVPanelizer -.
DAPAR - This package contains a collection of functions for the visualisation and the statistical analysis of proteomic data.
DChIPRep - The DChIPRep package implements a methodology to assess differences between chromatin modification profiles in replicated ChIP-Seq studies as described in Chabbert et. al -.
DeMAND - DEMAND predicts Drug MoA by interrogating a cell context specific regulatory network with a small number (N >= 6) of compound-induced gene expression signatures, to elucidate specific proteins whose interactions in the network is dysregulated by the compound.
destiny - Create and plot diffusion maps
DiffLogo - DiffLogo is an easy-to-use tool to visualize motif differences.
DNABarcodes -.
dupRadar - Duplication rate quality control for RNA-Seq datasets.
ELMER - ELMER is designed to use DNA methylation and gene expression from a large number of samples to infere regulatory element landscape and transcription factor network in primary tissue.
EnrichedHeatmap -.
erma - Software and data to support epigenomic road map adventures.
eudysbiome - eudysbiome a package that permits to annotate the differential genera as harmful/harmless based on their ability to contribute to host diseases (as indicated in literature) or.
fCI - (f.
FindMyFriends -.
gcatest - GCAT is an association test for genome wide association studies that controls for population structure under a general class of trait. models.
GeneBreak - Recurrent breakpoint gene detection on copy number aberration profiles.
genotypeeval - Takes in a gVCF or VCF and reports metrics to assess quality of calls.
GEOsearch -.
GUIDEseq - The package implements GUIDE-seq analysis workflow including functions for obtaining unique cleavage events, estimating the locations of the cleavage sites, aka, peaks, merging estimated cleavage sites from plus and minus strand, and performing off target search of the extended regions around cleavage sites.
Guitar - The package is designed for visualization of RNA-related genomic features with respect to the landmarks of RNA transcripts, i.e., transcription starting site, start codon, stop codon and transcription ending site.
hierGWAS - Testing individual SNPs, as well as arbitrarily large groups of SNPs in GWA studies, using a joint model of all SNPs. The method controls the FWER, and provides an automatic, data-driven refinement of the SNP clusters to smaller groups or single markers.
HilbertCurve - Hilbert curve is a type of space-filling curves that fold one dimensional axis into a two dimensional space, but with still keep the locality. This package aims to provide a easy and flexible way to visualize data through Hilbert curve.
iCheck - QC pipeline and data analysis tools for high-dimensional Illumina mRNA expression data.
iGC - This package is intended to identify differentially expressed genes driven by Copy Number Alterations from samples with both gene expression and CNA data.
Imetagene - This package provide a graphical user interface to the metagene package. This will allow people with minimal R experience to easily complete metagene analysis.
INSPEcT - INSPEcT (INference of Synthesis, Processing and dEgradation rates in Time-Course experiments) analyses 4sU-seq and RNA-seq time-course data in order to evaluate synthesis, processing and degradation rates and asses via modeling the rates that determines changes in mature mRNA levels.
IONiseR -.
ldblock - Define data structures for linkage disequilibrium measures in populations.
LedPred -.
lfa - LFA is a method for a PCA analogue on Binomial data via estimation of latent structure in the natural parameter.
LOLA - Provides functions for testing overlap of sets of genomic regions with public and custom region set (genomic ranges) databases. This make is possible to do automated enrichment analysis for genomic region sets, thus facilitating interpretation of functional genomics and epigenomics data.
MEAL - Package to integrate methylation and expression data. It can also perform methylation or expression analysis alone. Several plotting functionalities are included as well as a new region analysis based on redundancy analysis. Effect of SNPs on a region can also be estimated.
metagenomeFeatures -.
metaX - The package provides a integrated pipeline for mass spectrometry-based metabolomic data analysis. It includes the stages peak detection, data preprocessing, normalization, missing value imputation, univariate statistical analysis, multivariate statistical analysis such as PCA and PLS-DA, metabolite identification, pathway analysis, power analysis, feature selection and modeling, data quality assessment.
miRcomp - Based on a large miRNA dilution study, this package provides tools to read in the raw amplification data and use these data to assess the performance of methods that estimate expression from the amplification curves.
mirIntegrator - Tools for augmenting signaling pathways to perform pathway analysis of microRNA and mRNA expression levels.
miRLAB - Provide tools exploring miRNA-mRNA relationships, including popular miRNA target prediction methods, ensemble methods that integrate individual methods, functions to get data from online resources, functions to validate the results, and functions to conduct enrichment analyses.
motifbreakR -).
myvariant - MyVariant.info is a comprehensive aggregation of variant annotation resources. myvariant is a wrapper for querying MyVariant.info services
NanoStringDiff -.
OGSA - OGSA provides a global estimate of pathway deregulation in cancer subtypes by integrating the estimates of significance for individual pathway members that have been identified by outlier analysis.
OperaMate - OperaMate is a flexible R package dealing with the data generated by PerkinElmer’s Opera High Content Screening System. The functions include the data importing, normalization and quality control, hit detection and function analysis.
Oscope -.
Path2PPI - Package to predict pathway specific protein-protein interaction (PPI) networks in target organisms for which only a view information about PPIs is available. Path2PPI uses PPIs of the pathway of interest from other well established model organisms to predict a certain pathway in the target organism. Path2PPI only depends on the sequence similarity of the involved proteins.
pathVar - This package contains the functions to find the pathways that have significantly different variability than a reference gene set. It also finds the categories from this pathway that are significant where each category is a cluster of genes. The genes are separated into clusters by their level of variability.
PGA - This package provides functions for construction of customized protein databases based on RNA-Seq data, database searching, post-processing and report generation. This kind of customized protein database includes both the reference database (such as Refseq or ENSEMBL) and the novel peptide sequences form RNA-Seq data.
Prize -.
Prostar - This package provides a GUI interface for DAPAR.
ProteomicsAnnotationHubData - These recipes convert a variety and a growing number of public proteomics data sets into easily-used standard Bioconductor data structures.
RareVariantVis - Genomic variants can be analyzed and visualized using many tools. Unfortunately, number of tools for global interrogation of variants is limited. Package RareVariantVis aims to present genomic variants (especially rare ones) in a global, per chromosome way. Visualization is performed in two ways - standard that outputs png figures and interactive that uses JavaScript d3 package. Interactive visualization allows to analyze trio/family data, for example in search for causative variants in rare Mendelian diseases.
rCGH - A comprehensive pipeline for analyzing and interactively visualizing genomic profiles generated through Agilent and Affymetrix microarrays. As inputs, rCGH supports Agilent dual-color Feature Extraction files (.txt), from 44 to 400K, and Affymetrix SNP6.0 and cytoScan probeset.txt, cychp.txt, and cnchp.txt files, exported from ChAS or Affymetrix Power Tools. This package takes over all the steps required for a genomic profile analysis, from reading the files to the segmentation and genes annotations, and provides several visualization functions (static or interactive) which facilitate profiles interpretation. Input files can be in compressed format, e.g. .bz2 or .gz.
RCy3 - Vizualize, analyze and explore graphs, connecting R to Cytoscape >= 3.2.1.
RiboProfiling -.
rnaseqcomp - Several quantitative and visualized benchmarks for RNA-seq quantification pipelines. Two-replicate quantifications for genes, transcripts, junctions or exons by each pipeline with nessasery meta information should be organizd into numeric matrix in order to proceed the evaluation.
ropls -).
RTCGA -.
RTCGAToolbox -.
sbgr - R client for Seven Bridges Genomics API.
SEPA -.
SICtools -.
SISPA - Sample Integrated Gene Set Analysis (SISPA) is a method designed to define sample groups with similar gene set enrichment profiles.
SNPhood -.
subSeq - Subsampling of high throughput sequencing count data for use in experiment design and analysis.
SummarizedExperiment - The SummarizedExperiment container contains one or more assays, each represented by a matrix-like object of numeric or other mode. The rows typically represent genomic ranges of interest and the columns represent samples.
SWATH2stats - This package is intended to transform SWATH data from the OpenSWATH software into a format readable by other statistics packages while performing filtering, annotation and FDR estimation.
synlet -.
TarSeqQC - The package allows the representation of targeted experiment in R. This is based on current packages and incorporates functions to do a quality control over this kind of experiments and a fast exploration of the sequenced regions. An xlsx file is generated as output.
TCGAbiolinks - The aim of TCGAbiolinks is : i) facilitate the TCGA open-access data retrieval, ii) prepare the data using the appropriate pre-processing strategies, iii) provide the means to carry out different standard analyses and iv) allow the user to download a specific version of the data and thus to easily reproduce earlier research results. In more detail, the package provides multiple methods for analysis (e.g., differential expression analysis, identifying differentially methylated regions) and methods for visualization (e.g., survival plots, volcano plots, starburst plots) in order to easily develop complete analysis pipelines.
traseR - traseR performs GWAS trait-associated SNP enrichment analyses in genomic intervals using different hypothesis testing approaches, also provides various functionalities to explore and visualize the results.
variancePartition - Quantify and interpret multiple sources and biological and technical variation in gene expression experiments. Uses linear mixed model to quantify variation in gene expression attributable to individual, tissue, time point, or technical variables.
XBSeq -.
Package maintainers can add NEWS files describing changes to their packages since the last release. The following package NEWS is available:
Changes in version 0.99.0:
NEW FEATURES
Changes in version 2.9.3 (2015-05-30):
Fixed Note about require(Cairo).
Fixed failure with changes in ffbase and not exporting min.ff and max.ff
Changes in version 2.9.2 (2015-05-07):
Changes in version 2.9.1 (2015-04-30):
Added the CITATION file (which was never uploaded to the svn repos)
Added in one reference in pSegement.Rd
Changes in version 1.41.7 (2015-09-14):
Changes in version 1.41.6 (2015-07-29):
Changes in version 1.41.5 (2015-06-17):
Changes in version 1.41.4 (2015-05-26):
Changes in version 1.41.3 (2015-05-13):
Changes in version 1.41.2 (2015-05-05):
BUG FIX/ROBUSTNESS: readCelHeader() and readCel() would core dump R/affxparser if trying to read multi-channel CEL files (Issue #16). Now an error is generated instead. Multi-channel CEL files (e.g. Axiom) are not supported by affxparser. Thanks to Kevin McLoughlin (Lawrence Livermore National Laboratory, USA) for reporting on this.
BUG FIX/ROBUSTNESS: readCelHeader() and readCel() on corrupt CEL files could core dump R/affparser (Issues #13 & #15). Now an error is generated instead. Thanks to Benilton Carvalho (Universidade Estadual de Campinas, Sao Paulo, Brazil) and Malte Bismarck (Martin Luther University of Halle-Wittenberg) for reports.
Changes in version 1.41.1 (2015-04-25):
Changes in version 1.41.0 (2015-04-16):
Changes in version 1.8.0:
NEW FEATURES
genotype accessor requires reference and alternative allele information
genotype setter requires reference allele information
reference fraction is now accessed through fraction(ASEset, top.allele.criteria=”ref”)
for a more robust performance unit tests are now covering the most crucial calculations, such as e.g. fraction, frequency, summary, mapbias and phase specific calculations.
Changes in version 1.47:
DEFUNCT
probesByLL is now defunct; use AnnotationDbi::select() instead.
blastSequences supports multiple sequence queries; use as=”data.frame” for output.
Improve blastSequences strategy for result retrieval, querying the appropriate API for status every 10 seconds after initial estimated processing time.
Changes in version 1.31:
NEW FEATURES and API changes
columns() and keytypes() sort their return values.
ls() on a Bimap option returns keys in sort()ed order, by default * *
Changes in version 2.1.26:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.0.0:
BUG FIXES
Changes in version 0.0.214:
NEW FEATURES
Have added vcf files from the following genome builds for humans “human_9606/VCF/clinical_vcf_set/”, “human_9606_b141_GRCh37p13/VCF/”, “human_9606_b142_GRCh37p13/VCF/”, “human_9606_b142_GRCh37p13/VCF/clinical_vcf_set/”
For each genome build, where available, the following VCF file formats are available a) all.vcf.gz b) all_papu.vcf.gz c) common_all.vcf.gz d) clinvar.vcf.gz e) clinvar_papu f) common_and_clinical g) common_no_known_medical_impact
The user can refer to for VCF file type formats
Changes in version 1.9.1:
Add NEWS file
Add code to compute expression variability measure from Alemu, et al. NAR 2014.
Changes in version 2.99.0 (2015-10-06):
Changes in version 2.1.1:
bug fix in texpr, eexpr, iexpr, and gexpr methods; they no longer crash with single-replicate objects
Small documentation clarifications
Changes in version 1.0.0:
Changes in version 1.20.0:
BUG FIXES
Changes in version 1.8.0:
R Markdown templates for Bioconductor HTML and PDF documents
Suggest ‘rmarkdown’ as the default engine for .Rmd documents
Simplified use with ‘rmarkdown’ - no need to include a separate code chunk calling ‘BiocStyle::markdown’ anymore
Functions facilitating the inclusion of document compilation date and package version in the .Rmd document header
Changes in version 1.37.2:
NEW FEATURES
Changes in version 1.9.8:
BUG FIXES
Changes in version 1.5:
new function strandCollapse for collapsing forward and reverse strand data to be unstranded.
Updated read.bismark() to support the cytosine report files; both formats are supported. Other minor updates (mostly internal) to read.bismark(). Greatly improved documentation of this function, paying particular attention to differences in file formats between versions of Bismark.
Changes in version 1.25.3:
BUG FIXES
Changes in version 1.25.2:
USER VISIBLE CHANGES
Changes in version 1.25.1:
BUG FIXES
Changes in version 1.1.0:
BUG FIXES
Fixed bug in formatting m/z labels affecting R 3.2.2
Removed dependency on ‘fields’ because ‘maps’ is broken on Windows
Changes in version 3.3.8:
Changes in version 3.3.7:
FIX BUGS
Changes in version 3.3.6:
NEW FEATURE
add new function featureAlignedSignal, featureAlignedDistribution, featureAlignedHeatmap, pie1
add new dataset HOT.spots, wgEncodeTfbsV3
update annoGR class
update vignettes
Changes in version 3.3.5:
NEW FEATURE
remove all the RangedData
add annoGR class
update vignettes
Changes in version 3.3.4:
NEW FEATURE
toGRanges from MACS2, narrowPeak.
calculate the p value of overlapping peaks by reagioneR
update documentation
Changes in version 3.3.3:
NEW FEATURE
Changes in version 3.3.2:
NEW FEATURE
Changes in version 3.3.1:
NEW FEATURE
Changes in version 1.5.11:
remove ellipsis parameter in enrichPeakOverlap function and extend it to support GRanges objects <2015-10-08, Thu> + see
fixed the issue, <2015-10-05, Mon>
update GEO info, now contains >18,000 bed file information <2015-09-24, Thu>
Changes in version 1.5.10:
dropAnno function, eg. drop nearest gene annotation that far from TSS (>10k). <2015-09-17, Thu> + see + add parameter distanceToTSS_cutoff to enrichAnnoOverlap
use base::subset in plotDistToTSS instead of subsetting data within geom_bar <2015-09-17, Thu> + see + subset parameter in layer will be removed in next release of ggplot2.
Changes in version 1.5.9:
bug fixed of enrichAnnoOverlap <2015-08-26, Wed>
change parameter order.matrix to order.by in upsetplot to meet the change of UpSetR pkg <2015-08-26, Wed>
Changes in version 1.5.8:
Changes in version 1.5.7:
add vennpie parameter in upsetplot <2015-07-20, Mon>
upsetplot function for csAnno object <2015-07-20, Mon>
Changes in version 1.5.6:
update citation info <2015-07-09, Thu>
BED file +1 shift for BED coordinate system start at 0 <2015-07-07, Tue>
Changes in version 1.5.5:
Changes in version 1.5.4:
Changes in version 1.5.3:
Changes in version 1.5.1:
Changes in version 1.4.0:
Weighted voting mode that uses the distance from an observation to the nearest crossover point of the class densities added.
Bartlett Test selection function included.
New class SelectResult. rankPlot and selectionPlot can additionally work with lists of SelectResult objects. All feature selection functions now return a SelectResult object or a list of them.
priorSelection is a new selection function for using features selected in a prior cross validation for a new dataset classification.
New weighted voting mode, where the weight is the distance of the x value from the nearest crossover point of the two densities. Useful for predictions with skewed features.
Changes in version 1.7.2:
Changes in version 1.7.1:
BUG FIXES
Changes in version 1.8.0:
NEW FEATURES
Changes in version 2.3.8:
dropGO function <2015-09-24, Thu> + see
use_internal_data = TRUE in enrichKEGG example to speedup compilation of vignette and prevent error when online is not available <2015-09-23, Wed>
Changes in version 2.3.7:
bug fixed in sorting pvalue of compareClusterResult. <2015-09-16, Wed> For compareCluster(fun=groupGO), there is no pvalue, use Count for sorting
use_internal_data= TRUE in enrichKEGG and gseKEGG demonstrated in vignette due to the issue <2015-08-26, Wed>
Changes in version 2.3.6:
merge_result function <2015-07-15, Wed>
add citation of ChIPseeker <2015-07-09, Thu>
add ‘Functional analysis of NGS data’ section in vignette <2015-06-29, Mon>
update vignette <2015-06-24, Wed>
Changes in version 2.3.5:
Changes in version 2.3.4:
Changes in version 2.3.3:
Changes in version 2.3.2:
bug fixed of build_Anno <2015-05-07, Thu>
add plotGOgraph function <2015-05-05, Tue>
Changes in version 2.3.1:
remove import RDAVIDWebService <2015-04-29, Wed>
update buildGOmap <2015-04-29, Wed>
remove import KEGG.db <2015-04-29, Wed>
Changes in version 0.99.12:
Changes in version 0.99.11:
Changes in version 0.99.10:
Changes in version 0.99.9:
Add fix for inconsistencies
Remove CheckSignificance documentation for function not available
Fix for vignette plot inconsistency bootstrap count
Increment version number
Changes in version 0.99.8:
Changes in version 0.99.7:
Specificity improvements BUG FIXES
Improve code Styling
Add documentation
Changes in version 0.99.6:
Initial Bioconductor release BUG FIXES
Add required imports at NAMESPACE
Improve code Styling
Add documentation
Remove unnecessary files
Changes in version 1.38.0:
Fixed error reading Codelink files with option type=”Raw” or type=”Norm”.
Now readCodelinkSet() accepts “path=” as argument to enable reading files from a target directory.
Changes in version 1.2.0 (2015-09-01):
update exmaple dataset.
add drug repositioning gene sets and anlaysis.
Changes in version 1.3.4:
Changes in version 1.3.3:
Changes in version 1.3.2:
Changes in version 1.5.1:
oncoPrint: there are default graphics if type of alterations is
less than two.
anno_*: get rid of lazy loading
Changes in version 2.0.6 (2015-06-15):
Changes in version 2.0.5 (2015-06-10):
Changes in version 2.0.4 (2015-06-05):
Changes in version 2.0.3 (2015-05-06):
Changes in version 2.0.2 (2015-04-24):
Changes in version 2.0.1 (2015-04-18):
Implemented resetting the original work directory upon exit of CopywriteR functions
Corrected R dependency to version 3.2
Updated DESCRIPTION file
Fixed bug resulting in failure to calculate loesses RELEASE (version 2.0)
Changes in version 1.3.2:
Modified the fields title and description of the file DESCRIPTION to cerrect the title in the citation of the package.
Modified the field title of the file COSNet-package.Rd USER VISIBLE CHANGES BUG FIXES PLANS
Changes in version 1.3.14:
Added clusterFDR() function to compute the FDR for clusters of DB windows.
Added checkBimodality() function to compute bimodality scores for regions.
Modified normalize(), asDGEList() to allow manual specification of library sizes.
Switched from normalizeCounts(), normalize() to S4 method normOffsets().
Modified default parameter specification in strandedCounts(), to avoid errors.
Switched to warning from error when a restricted chromosome is specified in extractReads().
Modified extractReads() interface with improved support for extended read and paired read extraction.
Added normalization options to filterWindows() when using control samples.
Fixed bug for proportional filtering in filterWindows().
Allowed correlateReads() to accept paired-end specification when extracting data.
Added maximizeCcf() function to estimate the average fragment length.
Added support for strand-specific overlapping in detailRanges().
Increased the fidelity of retained information in dumped BAM file from dumpPE().
Modified strand specification arguments for profileSites(), allowed reporting of individual profiles.
Removed param= specification from wwhm().
Switched to RangedSummarizedExperiment conventions for all relevant functions.
Switched to mapqFilter for scanBam() when filtering on mapping quality.
Added tests for previously untested functions.
Slight updates to documentation, user’s guide.
Changes in version 1.8.2:
UPDATED FUNCTIONS
Changes in version 1.7.2:
NEW FEATURES
add html documentation
customize the x axis as the amino acid physical position
update the documentation
BUG FIXES
Changes in version 1.7.1:
NEW FEATURES
BUG FIXES
Changes in version 1.17.1:
Changes in version 0.99.5:
Changes in version 0.99.4:
Changes in version 0.99.3:
updated the python script to be executable
python script help in the vignette is now “live”
added negative tests for empty and flawed input in test_dataInput.R
small fixes in the tests and the source code
Changes in version 0.99.2:
updated general package help
small fixes in the vignette
updated newsfile
Changes in version 0.99.1:
fixed typos in the documentation
clarified dimensions of the count tables in the vignette
added additional checks to the data import functions
Changes in version 0.99.0:
Changes in version 1.24.0:
QuantStudio (LifeTechnologies) output files are now supported
All packages that were ‘depended on’ are not explicitly ‘imported from’. This has the effect that scripts depending on ddCt may explicitly load libraries (such as RColorBrewer and Biobase) to use functions therein.
ColMap is now simplied to contain only three slots: Sample, Detector, and Ct.
Class ‘CSVReader’ is now renamed into ‘TSVReader’ since it supports rather tab-delimited file, instead of comma-separated file
A direct way to convert a data.frame to a InputFrame object is documented. See ‘example(InputFrame)’.”)
1.4.0: 07-03-2015 Lorena Pantano lorena.pantano@gmail.com FIX SOME TEXT IN VIGNETTE, AND CLEAN DEPENDS FLAG
Changes in version 1.9.0:
Changes in version 1.3.3:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3.2:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3.1:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3.1:
NEW FEATURES
Changes in version 1.3.4:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3.3:
NEW FEATURES
Changes in version 1.3.2:
NEW FEATURES
Changes in version 1.3.1:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.10.0:
Added MLE argument to plotMA().
Added normTransform() for simple log2(K/s + 1) transformation, where K is a count and s is a size factor.
When the design contains an interaction, DESeq() will use betaPrior=FALSE. This makes coefficients easier to interpret.
Independent filtering will be less greedy, using as a threshold the lowest quantile of the filter such that the number of rejections is within 1 SD from the maximum. See ?results.
summary() and plotMA() will use ‘alpha’ from results().
Changes in version 1.16.0:
Roll up bugfixes
dba.plotHeatmap returns binding sites in row order
Changes in version 1.1.17:
Renamed normalize() to normOffsets().
Added library size specification to DIList methods normOffsets(), asDGEList().
Fixed bugs under pathological settings in plotPlaid(), plotDI(), rotPlaid(), rotDI().
Optimized C++ code for connectCounts(), squareCounts().
Streamlined various R utilities used throughout all functions.
Added iter_map.py to inst/python, for iterative mapping of DNase Hi-C data.
Added the neighborCounts() function, for simultaneous read counting and enrichment calculation.
Added exclude for enrichedPairs(), to provide an exclusion zone in the local neighborhood.
Switched default colour in rotPlaid(), plotPlaid() to black.
Added compartmentalize() function to identify genomic compartments.
Added domainDirections() function to help identify domains.
Modified correctedContact() to allow distance correction and report factorized probabilities directly.
Modified marginCounts() function for proper single-end-like treatment of Hi-C data.
Extended clusterPairs() to merge bin pairs from multiple DILists.
Switched to reporting ranges directly from boxPairs(), added support for minimum bounding box output.
Modified consolidatePairs() to accept index vectors for greater modularity.
Added reference argument for large bin pairs, in filterDirect() and filterTrended().
Added filterDiag() convenience function for filtering of (near-)diagonal bin pairs.
Slight change to preparePairs() diagnostic reports when dedup=FALSE, and for unpaired reads.
Added option for a distance-based threshold to define invalid chimeras in preparePairs().
Updated documentation, tests and user’s guide.
Added diffHic paper entry to CITATION.
Changes in version 2.7.12:
Changes in version 2.7.11:
check whether input geneList is sorted <2015-09-22, Tue>
order first followed by showCategory subsetting in barplot <2015-09-08, Tue> +
bug fixed in EXTID2NAME, keytype is TAIR for arabidopsis and ORF for malaria <2015-08-26, Wed>
Changes in version 2.7.10:
add Giovanni Dall’Olio as contributor in author list. <2015-07-21, Tue>
update NCG data to version cancergenes_4.9.0_20150720 contributed by Giovanni Dall’Olio. <2015-07-21, Tue>
geneInCategory may simplify to vector by R in very rare case, which violate the assumption of list in S4 validation checking. This issue was fixed. <2015-07-19, Sun>
Changes in version 2.7.9:
add citation of ChIPseeker <2015-07-09, Thu>
add ‘Disease analysis of NGS data’ section in vignette <2015-06-29, Mon>
convert vignette from Rnw to Rmd <2015-06-24, Wed>
Changes in version 2.7.8:
Changes in version 2.7.7:
speed up by using sample.int instead of sample <2015-06-04, Thu>
add seed = FALSE to control reproduciblility of gsea function. to make result reproducible, explicitly set seed=TRUE <2015-06-04, Thu>
Changes in version 2.7.6:
Changes in version 2.7.5:
Changes in version 2.7.4:
Changes in version 2.7.3:
add setType slot in gseaResult <2015-05-15, Tue>
add universe and geneSets slots in enrichResult <2015-05-05, Tue>
Changes in version 2.7.2:
Changes in version 2.7.1:
Changes in version 2.8.0:
Changes in version 0.99.3:
DOCUMENTATION
First release to Bioconductor
NEWS file was added.
Changes in version 2.5.6:
Ported changes from version 2.4.5 - 2.4.7
Added a function to create the synthetic transcripts
Deprecated functions fetchAnnotation and knowOrganisms are now defunct
Export ‘basename’, ‘seqlevels’, ‘seqlevels<-‘ and ‘seqnames<-‘
Changes in version 2.5.5:
Changes in version 2.5.4:
Changes in version 2.5.3:
Ported changed from release version 2.4.1
Adapted to the genomeIntervals API changes (change from seq_name to seqnames and addition of the coercion methods to GRanges and consort).
Changes in version 2.5.2:
Changes in version 2.5.1:
Changes in version 2.5.0:
Changes in version 4.12.0:
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
deprecated ‘…GreyScale’
‘resize’ doesn’t perform bilinear filtering at image borders anymore in order to prevent the blending of image edges with the background when the image is upscaled; to switch on bilinear sampling at image borders use the function argument ‘antialias = TRUE’
‘floodFill’ and ‘fillHull’ preserve storage mode
PERFORMANCE IMPROVEMENTS
all morphological operations use the efficient Urbach-Wilkinson algorithm (up to 3x faster compared to the previous implementation)
‘rotate’: perform lossless 90/180/270 degree rotations by disabling bilinear filtering
BUG FIXES
reimplemented the Urbach-Wilkinson algorithm used to perform grayscale morphological transformations
improved pixel-level accuracy of spatial linear transformations: ‘affine’, ‘resize’, ‘rotate’ and ‘translate’
‘display(…, method = “raster”)’: displaying of single-channel color images
‘drawCircle’: corrected x-y offset
‘equalize’: in case of a single-valued histogram issue a warning and return its argument
‘hist’: accept images with ‘colorMode = Color’ containing less than three color channels
‘image’: corrected handling of image frames
‘medianFilter’: filter size check
‘normalize’: normalization of a flat image when the argument ‘separate’ is set to ‘FALSE’
‘reenumerate’: corrected handling of images without background
‘stackObjects’: corrected handling of blank images without any objects
‘tile’: reset dimnames
Changes in version 1.9.3:
Correct typos in GetDEResults help file.
Include an additional method for normalization.
Changes in version 1.9.2:
Changes in version 1.9.1:
Changes in version 2.3:
Added function getGeneLengthAndGCContent to compute gene length and GC-content.
Updated vignette.
Changes in version 2.1.1:
Moderated F-test has been added for likelihood ratio test
Weights can be inputted into odp/lrt which allows it to work for RNA-Seq experiments with low samples
added function apply_jackstraw
fixed bug in build_study
Changes in version 3.12.0:
New argument tagwise for estimateDisp(), allowing users not to estimate tagwise dispersions.
estimateTrendedDisp() has more stable performance and does not return negative trended dispersion estimates.
New plotMD methods for DGEList, DGEGLM, DGEExact and DGELRT objects to make a mean-difference plot (aka MA plot).
readDGE() now recognizes HTSeq style meta genes.
Remove the F-test in glmLRT().
New argument contrast for diffSpliceDGE(), allowing users to specify the testing contrast.
glmTreat() returns both logFC and unshrunk.logFC in the output table.
New method implemented in glmTreat() to increase the power of the test.
New kegga methods for DGEExact and DGELRT objects to perform KEGG pathway analysis of differentially expressed genes using Entrez Gene IDs.
New dimnames<- methods for DGEExact and DGELRT objects.
Bug fix to dimnames<- method for DGEGLM objects.
User’s Guide updated. Three old case studies are replaced by two new comprehensive case studies.
Changes in version 1.2.0:
Removed function QCfilter
Heavily modified function QCinfo
Add an argument exSample to preprocessENmix
Changes in version 0.99.3:
anno_enrich: get rid of lazy loading
smoothing by locfit
Changes in version 0.99.2:
Changes in version 0.99.1:
system.file()now
Changes in version 0.99.0:
Changes in version 1.1.9:
BUG FIXES
Changes in version 1.1.6:
BUG FIXES
Changes in version 1.1.5:
NEW FEATURES
Changes in version 1.1.4:
NEW FEATURES
Changes in version 1.1.3:
SIGNIFICANT USER-VISIBLE CHANGES
Added method ensemblVersion that returns the Ensembl version the package bases on.
Added method getGenomeFaFile that queries AnnotationHub to retrieve the Genome FaFile matching the Ensembl version of the EnsDb object.
Changes in version 1.1.2:
SIGNIFICANT USER-VISIBLE CHANGES
Added examples to the vignette for building an EnsDb using AnnotationHub along with the matching genomic sequence.
Added an example for fetching the sequences of genes, transcripts and exons to the vignette.
BUG FIXES
Changes in version 1.1.1:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.10.0:
NEW FEATURES
Changes in version 1.6.1:
Changes in version 1.3.5:
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES AND MINOR IMPROVEMENTS
Changes in version 1.3.4:
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES AND MINOR IMPROVEMENTS
Fixed allReps and labelReps value assignment
Fixed bug for duplicate row names in array data
Fixed warning for incorrect sample names
Changes in version 1.3.3:
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES AND MINOR IMPROVEMENTS
Added warnings to initDat function for incorrect sample names and missing 1:1 controls from userMixFileß
Set minimum version requirements for ggplot2 and gridExtra
Changes in version 1.3.2:
SIGNIFICANT USER-VISIBLE CHANGES
Vignette is updated to include use of grid.arrange for viewing figures
multiplot function is deprecated and removed from the package, function is replaced with grid.arrange
BUG FIXES AND MINOR IMPROVEMENTS
Changes in version 1.3.1:
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES AND MINOR IMPROVEMENTS
Changes in version 1.9.2:
Changes in version 1.9.1:
integrated the RMT tool for extracting the combinatorial RNA methylome from multiple MeRIP-Seq datasets, see ?RMT
3 authors: Jia Meng, Lin Zhang and Lian Liu
added another citation (Liu 2015)
Changes in version 3.4:
Added argument ‘downloadFile’ to fea_david() to choose whether to save the analysis results to the current directory
DAVID now requires https. This causes errors in some systems. A (hopefully) temporary solution is to install some certificates locally. See RDAVIDWebService help:
Changes in version 0.99.0:
Changes in version 1.7.3:
add the header ie the sample names to the output tables (created when using output.type=’table’)
correct little bug concerning the SAM file when header is present (see samio.cpp first test over linecount replace by totalnumread)
Changes in version 1.4.0:
NEW FEATURES
BUG FIXES
OTHER NOTES
added LazyData: true in the DESCRIPTION
updated travis.yml to use native R integration
vignette: improved structure, to enhance readability and usability; removed rgl hook which was not used anyway
documentation: slight updates and enhancements
Changes in version 1.1.1:
NEW FEATURES
Changes in version 2.7.0:
Changes in version 1.6.0:
Changes in version 1.11.1:
Changes in version 2.0.0:
Added functions for PC-Relate. PC-Relate provides model-free estimation of recent genetic relatedness in general samples. It can.
GENESIS now imports the package gdsfmt.
Changes in version 1.9.3:
Changes in version 1.9:
Added CITATION
GenesRanking help: How to create a GenesRanking object based on scores provided by another algorithm
Several message and warning improvements
Bugfix: 0 IQR filter now returns the original matrix
Changes in version 1.1.27:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.26:
NEW FUNCTIONS AND FEATURES
Changes in version 1.1.25:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.24:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.23:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.22:
NEW FUNCTIONS AND FEATURES
Changes in version 1.1.21:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.20:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.19:
NEW FUNCTIONS AND FEATURES
Arithmetic, indicator and logic operations as well as subsetting work on ScoreMatrix, ScoreMatrixBin and ScoreMatrixList objects. New functionality at “ScoreMatrix-class” and “ScoreMatrixList-class” are documented in help pages.
Commented examples of functions are uncommented or \donttest{} is used.
Changes in version 1.1.18:
NEW FUNCTIONS AND FEATURES
Changes in version 1.1.17:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.16:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.15:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.14:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.13:
IMPROVEMENTS AND BUG FIXES
add new argument cex.legend to plotTargetAnnotation() to specify the size of the legend.
changed ScoreMatrixBin() to run faster when noCovNA=TRUE
check not only for .bw but also .bigWig and .bigwig extensions of BigWig file in ScoreMatrix() and ScoreMatrixBin()
Changes in version 1.1.12:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.11:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.10:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.9:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.8:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.7:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.6:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.5:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.4:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.3:
IMPROVEMENTS AND BUG FIXES
Functions that read data from text files re-written from data.table::fread() to readr::read_delim() and now they can read compressed files from a URL
Changes in readBed(), readNarrowPeak(), readBroadPeak() and gffToGRanges() arguments; All of them have now track.line argument that can be FALSE, “auto” or an integer indicating number of first lines to skip. The zero.based argument was added to readBed() that tells whether ranges in the bed file are in 0 or 1-based coordinate system. Implemented by Katarzyna Wręczycka.
Changes in version 1.1.2:
IMPROVEMENTS AND BUG FIXES
Changes in version 1.1.1:
NEW FUNCTIONS AND FEATURES
IMPROVEMENTS AND BUG FIXES
Changes in version 1.25.3:
Changes in version 1.25.2:
Changes in version 1.25.1:
Changed readGff3 to use closed intervals by default. Implemented two sub-functions that implement reading a gff3 as base-pair features only (no zero length intervals, i.e. right-closed intervals) or which allows for zero length intervals, i.e. right-open intervals, when start equals end)
Deprecated the seq_name accessors in favour of the BiocGenerics seqnames
Added a width accessor - similar to the IRanges functionality
Added coercion to GRangesList and RangedData
Edited some of the documentation (man page) and NAMESPACE generation to use roxygen2
Changes in version 1.25.0:
Changes in version 1.6.0:
NEW FEATURES
Add strandMode() getter and setter for GAlignmentPairs objects in response to the following post: See ?strandMode for more information.
The readGAlignment*() functions now allow repeated seqnames in the BAM header.
Add “coverage” method for GAlignmentsList objects.
The strand setter now works on a GAlignmentsList object in a restricted way (only strand(x) <- “+” or “-“ or “*” is supported).
SIGNIFICANT USER-LEVEL CHANGES
summarizeOverlaps() now returns a RangedSummarizedExperiment object (defined in the new SummarizedExperiment package) instead of an “old” SummarizedExperiment object (defined in the GenomicRanges package).
Slightly modify the behavior of junctions() on a GAlignmentPairs object so that the returned ranges now have the “real strand” set on them. See ?junctions and the documentation of the ‘real.strand’ argument in the man page of GAlignmentPairs objects for more information.
Add ‘real.strand’ argument to first() and last() getters for GAlignmentPairs objects.
DEPRECATED AND DEFUNCT
Deprecate left() and right() getters and strand() setter for GAlignmentPairs objects.
Deprecate ‘invert.strand’ argument of first() and last() getters for GAlignmentPairs objects.
Deprecate ‘order.as.in.query’ argument of “grglist” method for GAlignmentPairs objects.
Deprecate ‘order.as.in.query’ argument in “rglist” method for GAlignmentsList objects (this concept is not defined for these objects in general and the argument was ignored anyway).
After being deprecated in BioC 3.1, the “mapCoords” and “pmapCoords” methods are now defunct. mapToAlignments() should be used instead.
After being deprecated in BioC 3.1, the readGAlignmentFromBam() functions are now defunct. Everybody says “Let’s all use the readGAlignment() functions instead! (no FromBam suffix). Yeah!”
BUG FIXES
Changes in version 1.22:
NEW FEATURES
Add coverageByTranscript() and pcoverageByTranscript(). See ?coverageByTranscript for more information.
Various improvements to makeTxDbFromGFF(): - Now supports ‘format=”auto”’ for auto-detection of the file format. - Now supports naming features by dbxref tag (like GeneID). This has proven useful when importing GFFs from NCBI.
Improvements to the coordinate mapping methods: - Support recycling when length(transcripts) == 1 for parallel mapping functions. - Add pmapToTranscripts,Ranges,GRangesList and pmapFromTranscripts,Ranges,GRangesList methods.
Adds ‘taxonomyId’ argument to the makeTxDbFrom*() functions.
Improvements to makeTxDbPackage(): - Add ‘pkgname’ argument to makeTxDbPackage() to let the user override the automatic naming of the package to be generated. - Support person objects for ‘maintainer’ and ‘author’ arguments to makeTxDbPackage().
The ‘chrominfo’ vector passed to makeTxDb() can now mix NAs and non-NAs.
SIGNIFICANT USER-VISIBLE CHANGES
Improve handling of ‘circ_seqs’ argument by makeTxDbFromUCSC(), makeTxDbFromGFF(), and makeTxDbFromBiomart(): no more annoying warning when none of the strings in DEFAULT_CIRC_SEQS matches the seqlevels of the TxDb object to be made.
2 minor changes to makeTxDbFromBiomart(): - Now drops unneeded chromosome info when importing an incomplete transcript dataset. - Now returns a TxDb object with ‘Full dataset’ field set to ‘no’ when makeTxDbFromBiomart() is called with user-supplied ‘filters’.
makeTxDbPackage() now includes data source in the package name by default (for non UCSC and BioMart databases).
The following changes were made to the coordinate mapping methods: - mapToTranscripts() now reports mapped position with respect to the transcription start site regardless of strand. - Change ‘ignore.strand’ default from TRUE to FALSE in all coordinate mapping methods for consistency with other functions that already have the ‘ignore.strand’ argument. - Name matching in mapFromTranscripts() is now done with seqnames(x) and names(transcripts). - The pmapFromTranscripts,*,GRangesList methods now return a GRangesList object. Also they no longer use ‘UNMAPPED’ seqname for unmapped ranges. - Remove uneeded ellipisis from the argument list of various coordinate mapping methods.
Change behavior of seqlevels0() getter so it does what it was always intended to do.
The order of the transcripts returned by transcripts() has changed: now they are guaranteed to be in the same order as in the GRangesList object returned by exonsBy().
Code improvements and speedup to the transcripts(), exons(), cds(), exonsBy(), and cdsBy() extractors.
DEPRECATED AND DEFUNCT
After being deprecated in BioC 3.1, the makeTranscriptDb*() functions are now defunct.
After being deprecated in BioC 3.1, the ‘exonRankAttributeName’, ‘gffGeneIdAttributeName’, ‘useGenesAsTranscripts’, ‘gffTxName’, and ‘species’ arguments of makeTxDbFromGFF() are now defunct.
Remove sortExonsByRank() (was defunct in BioC 3.1).
BUG FIXES
Fix bug in fiveUTRsByTranscript() and threeUTRsByTranscript() extractors when the TxDb object had “user defined” seqlevels and/or a set of “active/inactive” seqlevels defined on it.
Fix bug in isActiveSeq() setter when the TxDb object had “user defined” seqlevels on it.
Fix many issues with seqlevels() setter for TxDb objects. In particular make the ‘seqlevels(x) <- seqlevels0(x)’ idiom work on TxDb objects.
Fix bug in makeTxDbFromBiomart() when using it to retrieve a dataset that doesn’t provide the cds_length attribute (e.g. sitalica_eg_gene dataset in plants_mart_26).
Changes in version 1.6.0:
BUG FIXES
Changes in version 1.3.9:
NEW FEATURES
InteractionTrack class for plotting interactions with Gviz
plotAvgViewpoint for plotting summarised interactions around a set of features
summariseByFeaturePairs: to summarise interactions between all pairs of two feature sets
SIGNIFICANT USER-LEVEL CHANGES
annotateInteractions is significantly faster
Data import has been made stricter and more consistent across different file formats. Homer interaction files now have data imported that was previously discarded.
BUG FIXES
single viewpoint plotting (plotViewpoint)
is.dt, is.pt
calculateDistances
some import/export issues
Changes in version 1.22.0:
NEW FEATURES
Support coercions back and forth between a GRanges object and a character vector (or factor) with elements in the format ‘chr1:2501-2800’ or ‘chr1:2501-2800:+’.
Add facilities for manipulating “genomic variables”: bindAsGRanges(), mcolAsRleList(), and binnedAverage(). See ?genomicvars for more information.
Add “narrow” method for GRangesList objects.
Enhancement to the GRanges() constructor. If the ‘ranges’ argument is not supplied then the constructor proceeds in 2 steps: 1. An initial GRanges object is created with ‘as(seqnames, “GRanges”)’. 2. Then this GRanges object is updated according to whatever other arguments were supplied to the call to GRanges(). Because of this enhancement, GRanges(x) is now equivalent to ‘as(x, “GRanges”)’ e.g. GRanges() can be called directly on a character vector representing ranges, or on a data.frame, or on any object for which coercion to GRanges is supported.
Add ‘ignore.strand’ argument to “range” and “reduce” methods for GRangesList objects.
Add coercion from SummarizedExperiment to RangedSummarizedExperiment (also available via updateObject()). See 1st item in DEPRECATED AND DEFUNCT section below for more information about this.
GNCList objects are now subsettable.
“coverage” methods now accept ‘shift’ and ‘weight’ supplied as an Rle.
SIGNIFICANT USER-LEVEL CHANGES
Modify behavior of “*” strand in precede() / follow() to mimic ‘ignore.strand=TRUE’.
Revisit “pintersect” methods for GRanges#GRanges, GRangesList#GRanges, and GRanges#GRangesList: - Sanitize their semantic. - Add ‘drop.nohit.ranges’ argument (FALSE by default). - If ‘drop.nohit.ranges’ is FALSE, the returned object now has a “hit” metadata column added to it to indicate the elements in ‘x’ that intersect with the corresponding element in ‘y’.
binnedAverage() now treats ‘numvar’ as if it was set to zero on genomic positions where it’s not set (typically happens when ‘numvar’ doesn’t span the entire chromosomes because it’s missing the trailing zeros).
GRanges() constructor no more mangles the names of the supplied metadata columns (e.g. if the column is “_tx_id”).
makeGRangesFromDataFrame() now accepts “.” in strand column (treated as
GNCList() constructor now propagates the metadata columns.
Remove “seqnames” method for RangesList objects.
DEPRECATED AND DEFUNCT
The SummarizedExperiment class defined in GenomicRanges is deprecated and replaced by 2 new classes defined in the new SummarizedExperiment package: SummarizedExperiment0 and RangedSummarizedExperiment. In BioC 2.3, the SummarizedExperiment class will be removed from the GenomicRanges package and the SummarizedExperiment0 class will be renamed SummarizedExperiment. To facilitate this transition, a coercion method was added to coerce from old SummarizedExperiment to new RangedSummarizedExperiment (this coercion is performed when calling updateObject() on an old SummarizedExperiment object).
makeSummarizedExperimentFromExpressionSet() and related stuff was moved to the new SummarizedExperiment package.
After being deprecated in BioC 3.1, the rowData accessor is now defunct (replaced with the rowRanges accessor).
After being deprecated in BioC 3.1, GIntervalTree objects and the “intervaltree” algorithm in findOverlaps() are now defunct.
After being deprecated in BioC 3.1, mapCoords() and pmapCoords() are now defunct.
BUG FIXES
Changes in version 0.99.0:
genotypeeval in use at Genentech and HLI.
genotypeeval submitted to Bioconductor.
2.36: New Features * New, faster SOFT format parsing (Leonardo Gama) * Turned on unit tests in Travis CI * Test coverage metrics added Bug fixes * default download method no longer assumes that curl is installed on linux * GSEMatrix parsing from file now finds cached GPLs
Changes in version 1.1.20:
fixed bug in geom_tiplab when x contains NA (eg, removing by collapse function) <2015-10-01, Thu>
bug fixed in %add2%, if node available use node, otherwise use label <2015-09-04, Fri>
bug fixed of subview for considering aes mapping of x and y <2015-09-03, Thu>
update vignette by adding r8s example <2015-09-02, Wed>
bug fixed in fortify.multiPhylo, convert df$.id to factor of levels=names(multiPhylo_object) <2015-09-02, Wed>
update scale_x_ggtree to support Date as x-axis <2015-09-01, Tue>
add mrsd parameter for user to specify ‘most recent sampling date’ for time tree <2015-09-01, Tue> - remove ‘time_scale’ parameter.
defined ‘raxml’ class for RAxML bootstrapping analysis result <2015-09-01, Tue> + see + read.raxml, parser function + plot, get.tree, get.fields, groupOTU, groupClade, scale_color, gzoom and show methods + fortify.raxml method
Changes in version 1.1.19:
use fortify instead of fortify.phylo in fortify.multiPhylo, so that multiPhylo can be a list of beast/codeml or other supported objects. <2015-08-31, Mon>
support multiPhylo object, should use + facet_wrap or + facet_grid <2015-08-31, Mon>
remove dependency of EBImage and phytools to speedup the installation process of ggtree <2015-08-31, Mon> + these two packages is not commonly used, and will be loaded automatically when needed.
Changes in version 1.1.18:
layout name change to ‘rectangular’, ‘slanted’, ‘circular’/’fan’ for phylogram and cladogram (if branch.length = ‘none’) ‘unroot’ is not changed. <2015-08-28. Fri>
implement geom_point2, geom_text2, geom_segment2 to support subsetting <2015-08-28, Fri> see
update geom_tiplab according to geom_text2 and geom_segment2 <2015-08-28, Fri>
add geom_tippoint, geom_nodepoint and geom_rootpoint <2015-08-28, Fri>
Changes in version 1.1.17:
bug fixed in rm.singleton.newick by adding support of scientific notation in branch length <2015-08-27, Thu>
bug fixed in gheatmap, remove inherit aes from ggtree <2015-08-27, Thu>
add ‘width’ parameter to add_legend, now user can specify the width of legend bar <2015-08-27, Thu>
add ‘colnames_position’ parameter to gheatmap, now colnames can be display on the top of heatmap <2015-08-27, Thu>
theme_transparent to make background transparent <2015-08-27, Thu>
subview for adding ggplot object (subview) to another ggplot object (mainview) <2015-08-27, Thu>
Changes in version 1.1.16:
Changes in version 1.1.15:
open text angle parameter for annotation_clade/annotation_clade2 <2015-08-13, Thu>
support changing size of add_legend <2015-08-13, Thu>
reroot methods for phylo and beast <2015-08-07, Fri>
Changes in version 1.1.14:
Changes in version 1.1.13:
implement annotation_image <2015-08-01, Sat>
better implementation of geom_tiplab for accepting aes mapping and auto add align dotted line <2015-08-01, Sat>
open group_name parameter of groupOTU/groupClade to user <2015-08-01, Sat>
Changes in version 1.1.12:
update vignette according to the changes <2015-07-31, Fri>
add mapping parameter in ggtree function <2015-07-31, Fri>
extend groupClade to support operating on tree view <2015-07-31, Fri>
extend groupOTU to support operating on tree view <2015-07-31, Fri>
new implementation of groupClade & groupOTU <2015-07-31, Fri>
Changes in version 1.1.11:
annotation_clade and annotation_clade2 functions. <2015-07-30, Thu>
better add_legend implementation. <2015-07-30, Thu>
add … in theme_tree & theme_tree2 for accepting additional parameter. <2015-07-30, Thu>
better geom_tree implementation. Now we can scale the tree with aes(color=numVar). <2015-07-30, Thu>
Changes in version 1.1.10:
Changes in version 1.1.9:
update add_legend to align legend text <2015-07-06, Mon>
bug fixed in internal function, getChild.df, which should not include root node if selected node is root <2015-07-01, Wed>
rotate function for ratating a clade by 180 degree and update vignette <2015-07-01, Wed>
get_taxa_name function will return taxa name vector of a selected clade <2015-06-30, Tue>
add example of flip function in vignette <2015-06-30, Tue>
flip function for exchanging positions of two selected branches <2015-06-30, Tue>
Changes in version 1.1.8:
update get.placement <2015-06-05, Fri>
edgeNum2nodeNum for converting edge number to node number for EPA/pplacer output <2015-06-04, Thu>
mv scale_x_gheatmap to scale_x_ggtree, which also support msaplot <2015-06-02, Tue>
add mask function <2015-06-02, Tue>
Changes in version 1.1.7:
add example of msaplot in vignette <2015-05-22, Fri>
msaplot for adding multiple sequence alignment <2015-05-22, Fri>
Changes in version 1.1.6:
add vertical_only parameter to scaleClade and set to TRUE by default. only vertical will be scaled by default. <2015-05-22, Fri>
update add_colorbar & add_legend <2015-05-21, Thu>
add example of add_legend and gheatmap in vignette <2015-05-18, Mon>
gheatmap implementation of gplot <2015-05-18, Mon>
add_legend for adding evolution distance legend <2015-05-18, Mon>
Changes in version 1.1.5:
Changes in version 1.1.4:
better performance of parsing beast tree <2015-05-11, Mon> + support beast tree begin with ‘tree tree_1 = ‘ and other forms. + support file that only contains one evidence for some of the nodes/tips
update add_colorbar to auto determine the position <2015-05-04, Mon>
add_colorbar function <2015-04-30, Thu>
Changes in version 1.1.3:
add space between residue substitution (e.g. K123R / E155D) <2015-04-30, Thu>
remove slash line in heatmap legend <2015-04-30, Thu>
update vignette to add example of merge_tree <2015-04-29, Wed>
Changes in version 1.1.2:
in addition to parsing beast time scale tree in XXX_year[\.\d], now supports XXX/year[\.\d] <2015-04-29, Wed>
add examples folder in inst that contains sample data <2015-04-29, Wed>
update gplot, now rowname of heatmap will not be displayed <2015-04-28, Tue>
add line break if substitution longer than 50 character <2015-04-28, Tue>
support calculating branch for time scale tree <2015-04-28, Tue>
remove parsing tip sequence from mlb and mlc file <2015-04-28, Tue>
remove tip.fasfile in read.paml_rst for rstfile already contains tip sequence <2015-04-28, Tue>
scale_color accepts user specific interval and output contains ‘scale’ attribute that can be used for adding legend <2015-04-28, Tue>
extend fortify methods to support additional fields <2015-04-28, Tue>
extend get.fields methods to support additional fields <2015-04-28, Tue>
extend tree class to support additional info by merging two tree <2015-04-28, Tue>
implement merge_tree function to merge two tree objects into one <2015-04-28, Tue>
Changes in version 1.1.1:
minor bug fixed in extracting node ID of rst file <2015-04-27, Mon>
update parsing beast time scale tree to support _year (originally supports _year.\d+) <2015-04-27, Mon>
add Tommy in author <2015-04-27, Mon>
Changes in version 1.21.1:
Changes in version 1.3.2:
BUG FIX
Changes in version 1.3.1:
BUG FIX
Changes in version 1.27.4:
Changes in version 1.27.3:
Changes in version 1.27.2:
Changes in version 1.27.1:
Changes in version 1.15.3 (2015-10-07):
Updated all pathway data.
More descriptive edge types.
Use the package “rappdirs” to select a directory for cached files.
Changes in version 1.1.1:
Changes in version 1.4.0:
Changes in version 1.31:
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
Changes in version 1.1.1:
print message if input chromosome names are without ‘chr’
call
start() and
end() explictely with
GenomicRanges::
unit of x-axis is correct now
Changes in version 0.99.9:
Changes in version 2.1.0:
USER VISIBLE CHANGES
GWAS catalog data curated at EMBL/EBI will now be used with makeCurrentGwascat: Updated 3 August 2015, as comma-space delim. for genes and EFO tags has been introduced
Interfaces to the Experimental Factor Ontology () are provided: efo.obo.g is an annotated graphNEL with the ontology
Vignette gwascatOnt.Rmd introduced
Changes in version 1.15.16:
Changes in version 1.15.15:
Changes in version 1.15.13:
Changes in version 1.15.12:
Changes in version 1.15.11:
Changes in version 1.15.10:
Changes in version 1.15.8:
Changes in version 1.15.7:
Changes in version 1.15.5:
Changes in version 1.15.3:
Changes in version 1.15.2:
Changes in version 1.15.1:
Changes in version 1.3.4 (2015-09-08):
Changes in version 1.3.3 (2015-07-20):
Updated output format of core functions.
Fixed minor bugs.
Changes in version 1.3.2 (2015-05-26):
Updated DESCRIPTION FILE.
Updated the CITATION file.
Changes in version 1.3.1 (2015-05-12):
Updated DESCRIPTION FILE.
Updated the CITATION file.
Updated documentation.
Changes in version 2.15.2:
Changes in version 1.3.2:
Changes in version 1.3.1:
Changes in version 1.6.0:
Changes in version 0.99.3:
Removed hlr dependency and added the MEL function
Fixed computation of r2 when the SNP_index = NULL
Changes in version 0.99.3:
Changes in version 0.99.2:
Changes in version 0.99.1:
Changes in version 0.99.0:
Changes in version 1.4.0:
Changes in version 1.13.2:
SIGNIFICANT USER-VISIBLE CHANGES
Change in the way the interaction matrix is loaded. During the import, the lazyload option will force the data to be stored as triangular matrix. Note that a symmetric matrix is not triangular by construction. Then, to avoid any error in the data processing, the triangular matrix is always converted into symmetrical matrix before being returned by the intdata method.
Update of track display in mapC function. Off-set plot of adjacent features
BUG FIXES
Bug fixed in quality control function when empty maps are used
Bug fixed when plotting empty matrix
Changes in version 1.13.1:
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
getCombinedContact is now able to merge HTCexp objects for non complete HiTClist objects. Missing maps are replaced by NA matrices
Update of isComplete, isPairwise, getCombinedIntervals methods for Hi-C data with no intrachromosomal maps
When the maxrange argument is set in the mapC function, all maps are displayed on the same scale so that they can be compared to each other
BUG FIXES
Bug fixed in mapC with the contact map is empty
Bug fixed in seqlevels(HTClist) method
Changes in version 1.11.1:
Changes in version 1.11.0:
Changes in version 1.0.0:
Changes in version 0.11.2 (2015-09-11):
BUG FIX: readIDAT() can now read non-encrypted IDAT files with strings longer than 127 characters.
BUG FIX: readIDAT() incorrectly assumed that there were exactly two blocks in RunInfo fields of non-encrypted (v3) IDAT files. Thanks to Gordon Bean (GitHub @brazilbean) for reporting on and contributing with code for the above two bugs.
Changes in version 0.11.1 (2015-07-29):
Changes in version 0.11.0 (2015-04-16):
1.1.1: NEW FEATRUES: * A normalization step which the sample cell-clusters to the common meta-cluster model is included an optionally activated during the major meta-clustering process. CHANGES: * The meta.ME C-binding and return value was modified in a way that the A-Posterior probability matrix Z for a cell-cluster belonging to a meta-cluster is also calculated and returned. BUFIXES: * Ellipse position were not correct when ploting a parameter subset
Changes in version 1.1.9:
Changes in version 1.1.8:
BUG FIXES
Changes in version 1.1.7:
BUG FIXES
Changes in version 1.1.6:
BUG FIXES
Changes in version 1.1.5:
BUG FIXES
Changes in version 1.1.4:
BUG FIXES
Changes in version 1.1.3:
BUG FIXES
Changes in version 1.1.2:
BUG FIXES
Changes in version 1.1.1:
BUG FIXES
Changes in version 1.7:
NEW FEATURES
BUG FIXES
Changes in version 2.4.0:
NEW FEATURES
Add “cbind” methods for binding Rle or RleList objects together.
Add coercion from Ranges to RangesList.
Add “paste” method for CompressedAtomicList objects.
Add “expand” method for Vector objects for expanding a Vector object ‘x’ based on a column in mcols(x).
Add overlapsAny,integer,Ranges method.
coverage” methods now accept ‘shift’ and ‘weight’ supplied as an Rle.
SIGNIFICANT USER-VISIBLE CHANGES
The following was moved to S4Vectors: - The FilterRules stuff. - The “aggregate” methods. - The “split” methods.
The “sum”, “min”, “max”, “mean”, “any”, and “all” methods on CompressedAtomicList objects are 100X faster on lists with 500k elements, 80X faster for 50k elements.
Tweak “c” method for CompressedList objects to make sure it always returns an object of the same class as its 1st argument.
NCList() constructor now propagates the metadata columns.
DEPRECATED AND DEFUNCT
RangedData/RangedDataList are not formally deprecated yet but the documentation now officially declares them as superseded by GRanges/GRangesList and discourage their use.
After being deprecated in BioC 3.1, IntervalTree and IntervalForest objects and the “intervaltree” algorithm in findOverlaps() are now defunct.
After being deprecated in BioC 3.1, mapCoords() and pmapCoords() are now defunct.
Remove seqapply(), mseqapply(), tseqapply(), seqsplit(), and seqby() (were defunct in BioC 3.1).
BUG FIXES
Fix FactorList() constructor when ‘compress=TRUE’ (note that the levels are combined during compression).
Fix c() on CompressedFactorList objects (was returning a CompressedIntegerList object).
Changes in version 1.3.4:
correction of Ubuntu problem with realloc for 0 elements in linearKernel generating a sparse empty kernel matrix
correction of problem with feature weights and prediction profiles for position specific gappy pair kernel
correction of problem with feature weights and prediction profiles for position specific motif kernel
corrections for feature weights, prediction via feature weights and prediction profile for distance weighted kernels
update of KeBABS citation
Changes in
Changes in version 1.3.2:
correction of error in kernel lists
user defined sequence kernel example SpectrumKernlabKernel moved to separate directory
Changes in version 1.3.1:
correction of error in model selection for processing via dense LIBSVM
remove problem in check for loading of SparseM
Changes in version 1.3.0:
Changes in version 1.27.2 (2015-05-25):
Changes in version 1.27.1 (2015-05-04):
Changes in version 1.1.1:
A new function, the “probes2pathways” has been added.
I have added to more network reconstruction approaches. The “aracne.a” and the “aracne.m” as included in the “parmigene” r-package.
I have replaced in the “preprocess” function the type of the produced image from jpeg to tiff format, with resolution=300dpi.
Changes in version 1.3.6:
Changes in version 1.3.1:
Changes in version 2.2.0:
Added checks to avoid producing identical matrices or data frame when the parameters are still the same after first function call.
Splitted the analysis in multiple (optionnal) intermediate steps (add_design, produce_matrices and produce_data_frame).
narrowPeak and broadPeak format is now supported.
Added multiple getter to access metagene members that are all now private (get_params, get_design, get_regions, get_matrices, get_data_frame, get_plot, get_raw_coverages and get_normalized_coverages.
Added the NCIS algorithm for noise removal.
Replaced the old datasets with promoters_hg19, promoters_hg18, promoters_mm10 and promoters_mm9 that can be accessed with data(promoters_????).
Added flip_regions and unflip_regions to switch regions orientation based on the strand.
Changes in version 0.0.0.9 (2015-09-14):
Changes in version 1.11:
Adding fitFeatureModel - a feature based zero-inflated log-normal model.
Added MRcoefs,MRtable,MRfulltable support for fitFeatureModel output.
Added mention in vignette.
Added support for normalizing matrices instead of just MRexperiment objects.
Fixed cumNormStat’s non-default qFlag option
Changes in version 1.9.21 (2015-10-08):
NEW FEATURES
BUG FIXES
Fixed broken dependency with removed CRAN package MADAM which was used for the Fisher p-value combination. The fix was done by copying the two required functions from the last MADAM archived version (1.2).
Fixed a bug in make.sample.list which rendered the function unusable (credits to Marina Adamou-Tzani).
Fixed a very special-case small bug in the report generation only a single gene passes the multiple testing correction cutoff (thans to Martic Reszcko, BSRC ‘Alexander Fleming’).
Fixed problem with Fisher p-value combination method (returning all NA due to the inexistence of names in the p-value vecror).
Fixed bug with flags of biotype filtered genes.
Changes in version 1.9.0 (2015-05-27):
NEW FEATURES
BUG FIXES
Changes in version 0.1.0:
Changes in version 1.3.3:
Changes in version 1.3.2:
Changes in version 1.15:
Adding testing for preprocessNoob, preprocessFunnorm.
Fxing some verbose output of preprocessNoob.
Adding non-exported function .digestVector for testing.
Changes in version 1.49.8:
Changes in version 1.49.7:
Changes in version 1.49.1:
Changes in version 1.1.1:
NEW FEATURES
Changes in version 1.13.8:
NEW FEATURES
Changes in version 1.13.7:
Changes in version 1.13.6:
BUG FIXES
Changes in version 1.13.5:
NEW FEATURES
Changes in version 1.13.4:
NEW FEATURES
BUG FIXES
Changes in version 1.13.3:
NEW FEATURES
BUG FIXES
Changes in version 1.13.2:
NEW FEATURES
BUG FIXES
Changes in version 1.13.1:
NEW FEATURES
BUG FIXES
Changes in version 1.2.0:
Changes in version 1.17.16:
Changes in version 1.17.15:
Changes in version 1.17.14:
Changes in version 1.17.13:
partly rewrite writeMgfData <2015-05-16 Thu>
initial hmap function <2015-07-16 Thu>
fix bug in plotting MS1 spectra (closes issue #59) <2015-07-16 Thu>
new image implementation, based on @vladpetyuk’s vp.misc::image_msnset <2015-07-25 Sat>
Changed the deprecated warning to a message when reading MzTab data version 0.9, as using the old reader can not only be achived by accident and will be kept for backwards file format compatibility <2015-07-30 Thu>
Changes in version 1.17.12:
Changes in version 1.17.11:
adding unit tests <2015-07-01 Wed>
fix abundance column selection when creating MSnSet form MzTab <2015-07-01 Wed>
new mzTabMode and mzTabType shortcut accessors for mode and type of an mzTab data <2015-07-01 Wed>
Changes in version 1.17.10:
Changes in version 1.17.9:
calculateFragments’ “neutralLoss” argument is now a list (was a logical before), see #47. <2015-06-24 Wed>
add defaultNeutralLoss() function to fill calculateFragments’ modified “neutralLoss” argument, see #47. <2015-06-24 Wed>
Changes in version 1.17.8:
coercion from IBSpectra to MSnSet, as per user request <2015-06-23 Tue>
new iPQF combineFeature method <2015-06-24 Wed>
Changes in version 1.17.7:
Changes in version 1.17.6:
Export metadata,MzTab-method <2015-06-19 Fri>
Replace spectra,MzTab-method by psms,MzTab-method <2015-06-20 Sat>
Change the meaning of calculateFragments’ “modifications” argument. Now the modification is added to the mass of the amino acid/peptide. Before it was replaced. <2015-06-21 Sun>
calculateFragments gains the feature to handle N-/C-terminal modifications, see #47. <2015-06-21 Sun>
update readMzTabData example <2015-06-22 Mon>
Changes in version 1.17.5:
Changes in version 1.17.4:
New lengths method for FoICollection instances <2015-06-06 Sat>
New image2 function for matrix object, that behaves like the method for MSnSets <2015-06-10 Wed>
image,MSnSet labels x and y axis as Samples and Features <2015-06-10 Wed>
fixed bug in purityCorrect, reported by Dario Strbenac <2015-06-11 Thu>
Changes in version 1.17.3:
Changes in version 1.17.2:
Changes in version 1.17.1:
new MSnSetList class <2015-04-19 Sun>
new commonFeatureNames function <2015-04-14 Tue>
new compareMSnSets function <2015-04-19 Sun>
splitting and unsplitting MSnSets/MSnSetLists <2015-04-19 Sun>
Changes in version 1.17.0:
Changes in version 1.3.1:
Changes in version 3.0.12:
Changes in version 3.0.9:
dataProcess
add options for ‘cutoffCensored=“minFeatureNRun”’.
summaryMethods=“TMP” : output will have ‘more50missing’column.
remove50missing=FALSE option : remove runs which has more than 50% of missing measurement. It will be affected for TMP, with censored option.
MBimpute : impute censored by survival model (AFT) with cutoff censored value
featureSubset option : “all”,”top3”, “highQuality”
change the default. -groupComparisonPlots
heatmap, for logBase=10, fix the bug for setting breaks.
Changes in version 3.0.8:
dataProcess : when censoredInt=“0”, intensity=0 works even though skylineReport=FALSE.
dataProcess, with censored=“0” or “NA” : fix the bug for certain run has completely missing.
cutoffCensored=“minRun” or “minFeature” : cutoff for each Run or each feature is little less (99%) than minimum abundance. -summaryMethod=“TMP”, censored works. censoredInt=NA or 0, and cutoffCensored=0, minFeature, minRun
Changes in version 3.0.3:
dataProcess : new option, skylineReport. for skyline MSstats report, there is ‘Truncated’ column. If Truncated==True, remove them. and keep zero value for summaryMethod=“skyline”.
groupComparison : for skyline option, t.test, val.equal=TRUE, which is no adjustment for degree of freedom, just pooled variance.
Changes in version 1.7.1:
Imports generics from ProtGenerics
Export base classes
Changes in version 2.3.3:
Changes in version 2.3.2:
Changes in version 2.3.1:
Changes in version 0.99.0:
NEW FEATURES
1.1.1: package. Added covariance matrix as output of screen_cvglasso.
Changes in version 1.99.0:
Added option for the output of model parameters.
Added option for multiple imputation.
Added option for the model function.
Changes in version 1.5.1:
Changes in version 1.9.1:
NEW FEATURES
Changes in version 1.1.0:
Changes:
the modelList has been added to provide the user a list of currently implemented methods.
The ‘verbose’ argument in fs.stability, fs.ensembl.stability, & fit.only.model has been changed to a character option indicating the extent of verbose output.
Canberra stability has been added as the previous implementation was not compatible with RPT. See ?canberra.stability for more details.
Many more tests have been implemented to make the package more stable.
Changes in version 1.99.9 (2015-10-08):
Fixed NEWS file.
Removed empty file.
Changes in version 1.99.8 (2015-10-01):
Changes in version 1.99.7 (2015-09-27):
Changes in version 1.99.6 (2015-09-26):
Improved test coverage and removed stringsAsfactors from tests.
Consistent handling of corner cases in Bozic.
Miscell minor documentation improvements.
Changes in version 1.99.5 (2015-06-25):
Changes in version 1.99.4 (2015-06-22):
Plotting true phylogenies.
Tried randutils, from O’Neill. Won’t work with gcc-4.6.
bool issue in Windows/gcc-4.6.
Most all to all.equal in tests.
Changes in version 1.99.3 (2015-06-19):
More examples to vignette
Using Makevars
More functionality to plot.fitnessEffects
Will Windoze work now?
Changes in version 1.99.2 (2015-06-19):
Changes in version 1.99.01 (2015-06-17):
Many MAJOR changes: we are done moving to v.2
New way of specifying restrictions (v.2) that allows arbitrary epistatic interactions and order effects, and very large (larger than 50000 genes) genomes.
When onlyCancer = TRUE, all iterations now in C++.
Many tests added.
Random DAG generation.
Some defaults for v.1 changed.
Changes in version 1.99.1 (2015-06-18):
Try to compile in Windoze with the SSTR again.
Reduce size of RData objects with resaveRdaFiles.
Try to compile in Mac: mt RNG must include random in all files.
Changes in version 1.99.00 (2015-04-23):
Accumulated changes of former 99.1.2 to 99.1.14:
changes in intermediate version 1.99.1.14 (2015-04-23):
Now are things OK (I messed up the repos)
changes in intermediate version 99.1.13 (2015-04-23)
Added a couple of drop = FALSE. Their absence lead to crashes in some strange, borderline cases.
Increased version to make unambiguous version used for anal. CBN.
changes in intermediate version 99.1.12 (2015-04-22)
Removed lots of unused conversion helpers and added more strict checks and tests of those checks.
changes in intermediate version 99.1.11 (2015-04-18)
Tests of conversion helpers now really working.
changes in intermediate version 99.1.10 (2015-04-16)
Added conversion helpers as separate file.
Added tests of conversion helpers.
Added generate-random-trees code (separate file).
More strict now on the poset format and conversions.
changes in intermediate version 99.1.9 (2015-04-09)
added null mutation for when we run out of mutable positions, and since not clear how to use BNB then.
changes in intermediate version 99.1.8 (2015-04-03)
added extraTime.
changes in intermediate version 99.1.7 (2015-04-03)
endTimeEvery removed. Now using minDDrPopSize if needed.
changes in intermediate version 99.1.6 (2015-03-20)
untilcancer and oncoSimulSample working together
changes in intermediate version 99.1.5 (2015-03-20)
Using the untilcancer branch
changes in intermediate version 99.1.4 (2014-12-24)
Added computation of min. of ratio birth/mutation and death/mutation.
changes in intermediate version 99.1.3 (2014-12-23)
Fixed segfault when hitting wall time and sampling only once.
changes in intermediate version 99.1.2 (2014-12-16)
Sampling only once
Changes in version 1.7.1:
Enhancements
Changes in version 1.3.3 (2015-07-14):
GENERAL
NEW FEATURES
IMPROVEMENTS
MODIFICATIONS
BUG FIXES
Changes in version 1.3.2 (2015-06-22):
GENERAL
Update to the latest R version which has been released a few days ago (2015-06-18).
Built with R-3.2.1
NEW FEATURES
IMPROVEMENTS
MODIFICATIONS
BUG FIXES
Changes in version 1.3.1 (2015-06-17):
GENERAL
The optional rlm normalization (for ProtoArrays) used by the functions normalizeArrays(), plotNormMethods() and plotMAPlots() has been completely reimplemented in order to fix some bugs and simplify the usage of these functions (details: see below).
Built with R-3.2.0
NEW FEATURES
IMPROVEMENTS
MODIFICATIONS 1.9.3:
pathview can accept a vector of multiple pathway ids, and map/render the user data onto all these pathways in one call.
one extra column “all.mapped” was added to pathview output data.frames as to show all the gene/compound IDs mapped to each node.
add geneannot.map as a generic function for gene ID or annotation mapping.
sim.mol.data now generate data with all major gene ID types for all 19 species in bods, not just human.
download.kegg now let the user to choose from xml, png or both file types to download for each input pathway. In the meantime, it uses the KEGG REST API instead of the classical KEGG download links. All potential pathways including the general pathways can be downloaded this way.
solve the redundant import from graph package.
import specific instead of all functions from XML package.
Changes in version 1.9.1:
Changes in version 0.9.1:
Changes in version 0.9.0:
Changes in version 1.5.2 (2015-08-07):
ADDED FUNCTIONS
Changes in version 0.1.0:
Changes in version 2.3.1:
NEW FUNCTIONALITY
COMPATIBILITY ISSUES
Changes in version 1.13.6:
BUG FIXES
droplevels suggestion for sample-data
DESeq2 migrated to suggests
extend_metagenomeSeq functionality
bugs related to previous version distance uptick, mostly in tests and vignette
Changes in version 1.13.5:
USER-VISIBLE CHANGES
Help avoid cryptic errors due to name collision of
distance with
external loaded packages by making
distance a formal S4 method in
phyloseq.
Improve documentation of
distance function and the downstream
procedures on which it depends
Migrate the list of supported methods to a documented, exported list
object, called
distanceMethodList.
Improved distance unit tests with detailed checks that dispatch works and gives exactly expected distance matrices for all methods defined in distanceMethodList.
Improved JSD doc, performance, code, deprecated unnecessary
parallel argument in JSD
Changes in version 1.13.4:
BUG FIXES
psmelt bug if user has also loaded the original “reshape” package,
due to name collision on the function called
melt.
psmelt now
explicitly calls
reshape2::melt to avoid confusion.
Fix following note… There are ::: calls to the package’s namespace in its code. A package almost never needs to use ::: for its own objects: ‘JSD.pair’
Changes in version 1.10:
Changes in version 1.1.3:
Changes in version 1.1.2:
Changes in version 1.1.1:
Changes in version 1.1.9.7:
New SpatProtVis visualisation class <2015-08-13 Thu>
add link to explanation of supportive/uncertain reliability scores in tl vignette <2015-09-02 Wed>
Changes in version 1.9.6:
Update REAMDE with TL ref
Update refs in lopims documentation <2015-07-30 Thu>
Changes in version 1.9.5:
Changes in version 1.9.4:
Add reference to TL paper and link to lpSVM code <2015-07-06 Mon>
highlightOnPlot throws a warning and invisibly returns NULL instead of an error when no features are in the object <2015-07-08 Wed>
highlightOnPlot has a new labels argument <2015-07-10 Fri>
Changes in version 1.9.3:
Clarify error when no annotation params are provided <2015-05-11 Mon>
support for matrix-encoded markers <2015-05-19 Tue>
New default in addLegend: bty = “n” <2015-05-20 Wed>
getMarkers now supports matrix markers <2015-05-20 Wed>
getMarkerClasses now supports matrix markers <2015-05-20 Wed>
markerMSnSet and unknownMSnSet now support matrix markers <2015-05-20 Wed>
sampleMSnSet now supports matrix markers <2015-05-23 Sat>
updated yeast markers and added uniprot ids <2015-05-27 Wed>
plot2D support a pre-calculated dim-reduced data matrix as method parameter to avoid recalculation <2015-05-27 Wed>
Changes in version 1.9.2:
Changes in version 1.9.1:
new plot2Ds function to overlay two data sets on the same PCA plot [2015-04-17 Fri]
regenerate biomart data used by setAnnotationParams [2015-04-24 Fri]
new setStockcolGui function to set the default colours manually via a simple interface [2015-04-29 Wed]
new move2Ds function to produce an transition movie between two MSnSets [2015-04-29 Wed]
functions to convert GO ids to/from terms. See ?goTermToId for details <2015-05-08 Fri>
Changes in version 1.9.0:
Changes in version 1.3.2:
Changes in version 1.3.1:
new plotMat2D function <2015-05-20 Wed>
Fix query search in pRolocVis, contributed by pierremj <2015-05-27 Wed>
pRolocVis has new method arg <2015-05-29 Fri>
Changes in version 1.3.0:
Changes in version 0.99.0:
Changes in version 0.99.3:
Changes in version 0.99.2:
Changes in version 0.99.1:
Changes in version 0.99.0:
Changes in version 1.1.1:
Changes in version 1.1.0:
Changes in version 4.5.1:
Convert log(P-values) back to P-values for human using a chi-sq distribution Version 4:
New algorithm for human backgrounds
New function: toPWM() that takes both PFMs and PPMs
Changes in version 1.1.10:
include threshold parameter into ‘readTFdata’ function
change STRINGdb to version 10
Changes in version 1.1.1:
rename consensus-based dynamic analysis
adjust vignette workflow figure
Changes in version 1.6.0:
RELEASE
IMPROVEMENTS
BUG FIXES
Changes in version 1.4.2 (2015-08-20):
BUG FIXES
Changes in version 1.4.1 (2015-06-30):
IMPROVEMENTS
Changes in version 2.40:
BUG FIXES
Changes in version 1.10.0:
NEW FEATURES
qExportWig gained createBigWig argument and can now create bigWig files directly
qQCReport now also produces base quality plots for bam-file projects by sampling reads from the bam files
qCount, qProfile and qExportWig have gained a includeSecondary argument to include/exclude secondary alignments while counting
Changes in version 2.1.1:
handles NA values
upgraded plotting functions
1.2.0: Updates: * Removed dependency from DAVIDQuery package as it will deprected. * Fixed some bugs in DAVIDQuery functions and integrated them into R3CPET. * Updated the Readme.Rd file. * Updated the HPRD.RData and Biogrid.RData to the new igraph class. * some small changes.
Changes in version 1.9.8:
BUG FIXES
Changes in version 1.13.5:
Changes in version 1.13.4:
Changes in version 1.13.3:
add citation of ChIPseeker <2015-07-09, Thu>
add ‘Pathway analysis of NGS data’ section in vignette <2015-06-29, Mon>
convert vignette from Rnw to Rmd <2015-06-29, Mon>
Changes in version 1.13.2:
Changes in version 1.13.1:
Changes in version 1.1.8:
NEW FEATURES
Added new functionality to permTest to use multiple evaluation functions with a single randomization procedure. This gives a significant speedup when comparing a single region set with multiple other features
Created a new function createFunctionsList() that given a function and a list of values, creates a list of curried functions (e.g with one parameter preassigned to each of the given values)
PERFORMANCE IMPROVEMENTS
BUG FIXES
Changes in version 1.3.8:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3.7:
NEW FEATURES
Changes in version 1.3.6:
NEW FEATURES
Changes in version 1.3.5:
SIGNIFICANT USER-VISIBLE CHANGES
Merged pull request
Added “template” argument to renderReport and derfinderReport to customize the knitr template used
Wrapped code that works in a temporary directory in with_wd function, which evaluates in the directory but returns to the original directory in the case of a user interrupt or error (with on.exit)
Changes in version 1.3.4:
NEW FEATURES
Changes in version 1.3.3:
NEW FEATURES
Now uses derfinderPlot::vennRegions() to show venn diagram of genomic states. Requires derfinderPlot version 1.3.2 or greater.
derfinderReport() now has a ‘significantVar’ argument that allows users to choose between determining significant regions by P-values, FDR adjusted P-values, or FWER adjusted P-values (if FWER adjusted P-values are absent, then FDR adjusted P-values are used instead, with a warning).
Changes in version 1.3.2:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3.1:
BUG FIXES
Changes in version 1.1.6:
Changes in version 1.1.5:
Changes in version 1.1.4:
Changes in version 1.1.3:
error message is extract from GREAT now.
default value of
bgChoice depeneds on
gr
Changes in version 1.1.2:
Changes in version 1.1.1:
GreatJobobject are initialized inside
submitGreatJob
Changes in version 2.14.0:
NEW FEATURES
improved handling of error messages: HDF5 error messages are simplified and forwarded to R.
When reading integer valued data, especially 64-integers and unsigned 32-bit integers, overflow values are now replaced by NA’s and a warning is thrown in this case.
When coercing HDF5-integers to R-double, a warning is displayed when integer precision is lost.
New low level general library function H5Dget_storage_size implemented.
BUG FIXES
Memory allocation on heap instead of stack for reading large datasets (Thanks to a patch from Jimmy Jia).
Some bugs have been fixed for reading large 64-bit integers and unsigned 32-bit integers.
A bug was fixed for reading HDF5 files containing soft links.
Changes in version 0.99.7:
Changes in version 0.99.6:
Changes in version 0.99.5:
Added @return for roxygen comment in printPCA.R
Updated packages IRanges and BSgenome.Mmusculus.UCSC.mm10 before check.
Changes in version 0.99.4:
Non-null coverage values define the percentage of best expressed CDSs.
New function: readsToReadStart - it builds the GRanges object of the read start genomic positions
Acronym BAM used instead of bam
Correction of read start coverage (readStartCov) for the reverse strand
Title in Description in Title Case
Typos corrections in vignette.
Style inconsistencies solved: = replaced by <- outside named arguments No space around “=” when using named arguments to functions. This: somefunc(a=1, b=2) spaces around binary operators a space after all commas use of camelCase for both variable and function names ORFrelativePos -> orfRelativePos
Replaced 1:length(x) by seq_len(length(x))
Replaced 1:nrow(x) by seq_len(NROW(x))
Replaced trailing white spaces with this command: ‘find . -type f -path ‘./*R’ -exec perl -i -pe ‘s/ +$//’ {} \;’
countsPlot, histMatchLength, plotSummarizedCov: no longer print directly the graphs. Instead they return a list of graphs.
Replaced ‘class()’ tests by ‘inherits’ or ‘is’.
The codonPCA function no longer prints the PCA graphs sequantially. The 5 PCA graphs are returned, together with the PCA scores.
New function printPCA prints the 5 PCA plots produced by codonPCA.
A BAM file is now available in the inst/extdata ctrl_sample.bam. It is used in the testriboSeqFromBAM testthat
Changes in version 0.99.3:
Changes in version 0.99.2:
Modified the vignette: small corrections of the explanatory text.
New R version: 3.2.2 and bioconductor packages update
Changes in version 0.99.1:
Added biocViews: Sequencing, Coverage, Alignment, QualityControl, Software, PrincipalComponent v.0.99.0 Initial release.
Changes in version 1.1.2:
BUG FIXES
MISC
Changes in version 1.1.9:
Filtering report fix when no normalization is conducted
Bugfixes for combine(RnBSet, RnBSet) and BigFf matrices
Changes in version 1.1.8:
Corrected coverage statistics in sample summary table: Sites with NA methylation values are no longer considered in the coverage statistics (makes a difference if some coverage threshold is applied)
Improved method for gender prediction. Predicted genders are also included in the exported annotation table
Changes in version 1.1.7:
Improvements to mergeSamples function for RnBiseqSets
Some more memory clean-up
Changes in version 1.1.6:
Differential methylation based on region level only is now supported
Minor updates to the differential methylation report generation
Performance improvements and minor bugfixes for using disk.dump.bigff
Performance improvements (more memory clean-up)
Changes in version 1.1.5:
Changes in version 1.1.4:
Changes in version 1.1.3:
Some fixes in data loading
Fixes in parallel environment setup
Changes in version 1.1.2:
New annotation package format
Support for filtering out cross-reactive probes in Infinium 450k dataset
Improved logging on a Mac
Changes in version 1.11.6:
Changes in version 1.11.5:
add test script <2015-06-30 Tue>
more unit tests <2015-06-30 Tue>
Changes in version 1.11.4:
Changes in version 1.11.3:
Changes in version 1.11.2:
Changes in version 1.11.1:
Changes in version 1.11.0:
Changes in version 1.1.11:
NEW FEATURES
Changes in version 1.1.10:
NEW FEATURES
Changes in version 1.1.9:
NEW FEATURES
opls: default number of permutations set to 10 (instead of 100) as a compromise to enable both quick computation and a first hint at model significance
opls: maximum number of components in automated mode (predI = NA or orthoI = NA) set to 10 (instead of 15)
plot.opls: bug corrected in case of single component model without permutation testing
Changes in version 1.1.8:
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.1.7:
NEW FEATURES
Changes in version 1.1.6:
NEW FEATURES
Changes in version 1.1.5:
NEW FEATURES
Changes in version 1.1.4:
NEW FEATURES
Changes in version 1.1.3:
NEW FEATURES
Changes in version 1.1.2:
BUG FIXES
Changes in version 1.1.1:
SIGNIFICANT USER-VISIBLE CHANGES
The packaging was modified (but not the algorithms) to be consistent with other machine learning packages: ‘opls’ is now a class and the ‘print’, ‘plot’, ‘predict’, ‘summary’, ‘fitted’, ‘coefficients’ and ‘residuals’ methods are available (see the vignette)
renamed method: roplsF -> opls
renamed arguments testVi -> now ‘subset’ which indicates the indices of the training (instead of the testing) observations
values: tMN -> scoreMN pMN -> loadingMN wMN -> weightMN bMN -> coefficients rMN -> rotationMN varVn -> pcaVarVn tOrthoMN -> orthoScoreMN pOrthoMN -> orthoLoadingMN wOrthoMN -> orthoWeightMN
new (S3) methods for objects of class ‘opls’ print summary plot predict fitted coefficients residuals
Changes in version 1.5.1:
unit tests <2015-06-30 Tue>
export and document pxnodes <2015-06-30 Tue>
Changes in version 1.5.0:
Changes in version 1.4:
NEW FEATURES
Custom template support added
Read frequency result and plot (rqcReadFrequencyPlot) added
Per file top represented reads added
Top representated reads added
Per file heatmap plot (rqcFileHeatmap) added
checkpoint function added (experimental)
USER VISIBLE CHANGES
BPPARAM argument replaced by workers argument
File information table added to default report template
Function rqcReadWidthPlot, y-axis changed to proportion (%)
Almost all plots use colorblid scheme
Changes in version 1.21:
SIGNIFICANT USER-VISIBLE CHANGES
pileup adds query_bins arg to give strand-sensitive cycle bin behavior; cycle_bins renamed left_bins; negative values allowed (including -Inf) to specify bins based on distance from end-of-read.
mapqFilter allows specification of a mapping quality filter threshold
PileupParam() now correctly follows samtools with min_base_quality=13, min_map_quality=0 (previously, values were assigned as 0 and 13, respectively)
Support parsing ‘B’ tags in bam file headers.
BUG FIXES
segfault on range iteration introduced 1.19.35, fixed in 1.21.1
BamViews parallel evaluation with BatchJobs back-end requires named arguments
Changes in version 1.20.0:
NEW FEATURES
Fast sorting of input bam files in featureCounts.
Fractional counting of multi-mapping reads in featureCounts.
Detection of complex indels in Subread and Subjunc aligners.
Including more candidate locations in read re-alignment step to improve mapping performance.
New formula for mapping paired-end reads that takes into account paired-end distance, number of subread votes and number of mismatched bases.
Changes in version 1.30:
NEW FEATURES
SIGNIFICANT USER-VISIBLE CHANGES
Changes in version 1.3:
New argument ‘isLog’ to RUV* methods: if counts provided on the log scale, normalizedCounts will also be on the log scale.
Fixed a bug: epsilon is now removed from the corrected counts.
New function makeGroups to make scIdx matrix for RUVs.
Changes in version 1.0.0 (2015-05-01):
Initial version
All the APIs of the SBG platform are supported
First vignette added
Changes in version 1.1.8:
Used Sys.info() rather than sessionInfor() to extract platform information
Avoided the use of “\” in R
Added a parameter “Ontology” to the function FisherTest_GO_BP_MF_CC()
Changes in version 1.1.6:
Corrected the python path for Linux users
Activated the demo code in R help files and vignettes
Changed the maintainer
Changes in version 1.1.4:
Update the Fisher’s exact test used mouse gene background.
Replace the mm10 GENCODE database V3 with V4 in the seq2pathway.data
Changes in version 1.1.2:
Changes in version 1.0.2:
Changes in version 1.10.0:
Changes in version 1.7.9:
Changes in version 1.7.7:
Changes in version 1.7.6:
Changes in version 1.7.5:
Changes in version 1.7.4:
Changes in version 1.7.3:
Add methods for duplicateDiscordance with two datasets
Add alternateAlleleDetection
Changes in version 1.4.0:
Added importTranscripts() for importing annotation from GFF format
Added plotCoverage() for visualization of per-base read coverage and junction read counts
Added predictVariantEffects() for predicting the effect of splice variants on annotated protein-coding transcripts
findSGVariants() is now able to deal with more complex gene models
SGVariants columns closed5p and closed3p now refer to individual splice variants rather than the splice event they belong to
Bug fixes and other improvements
Changes in version 1.27:
SIGNIFICANT USER-VISIBLE CHANGES
fastqFilter allows several input ‘files’ to be written to a single ‘destinations’.
readAligned() for BAM files is defunct. QA and associated methods removed.
srapply removed
Changes in version 1.1.01:
paramether tsne.theta has been added to function sc_DimensionalityReductionObj
function sc_InSilicoCellsReplicatesObj has been expanded to incorporate a forth model of noise generation following the negative binomial (NB) distribution. For each gene, dispersion parameters for the NB can be estimated in three alternative ways allowing different types of estimates (e.g. technical noise provided by the user). See documentation of sc_InSilicoCellsReplicatesObj() function.
Changes in version 0.99.0 (2015-08-07):
Changes in version 1.4.0:
Changes in version 1.3.7:
USER UNVISIBLE CHANGES
Changes in version 1.3.5:
USER UNVISIBLE CHANGES
Changes in version 1.3.4:
USER VISIBLE CHANGES
USER UNVISIBLE CHANGES
read.bibliospec - replaced old code (for loop) by using mcmapply
added time meassurements to read.bibliospec
Changes in version 1.3.3:
USER VISIBLE CHANGES
USER UNVISIBLE CHANGES
.mascot2psmSet buxfix
renamed column name in spectronaut outpu from irt to irt_or_rt
Changes in version 1.3.2:
USER VISIBLE CHANGES
added ssrc (Sequence Specific Retention Calculator) function
added a CITATION file
Changes in version 1.3.1:
USER VISIBLE CHANGES
USER UNVISIBLE CHANGES
Changes in version 1.0.0:
Changes in version 1.7.3:
NEW FEATURES
Changes in version 1.7.2:
NEW FEATURES
Changes in version 1.11.2:
Changes in version 1.11.1:
Changes in version 1.3:
OVERVIEW
systemPipeR is an R/Bioconductor package for building and running automated analysis workflows for a wide range of next generation sequence (NGS) applications..
The most important enhancements in the upcoming release of the package are outlined below.
NGS WORKFLOWS
Added new end-to-end workflows for 3 additional NGS application areas: - Ribo-Seq and polyRibo-Seq - ChIP-Seq - VAR-Seq The previous version of systemPipeR included only a complete workflow for RNA-Seq.
Added the data package ‘systemPipeRdata’ to generate systemPipeR workflow environments with a single command (genWorkenvir) containing all parameter files and sample data required to quickly test and run workflows. This change will also allow evaluation of much more code examples in the vignettes during the package build/test process than this was possible in the past.
About 20 new functions have been added to the package. Some examples are: - Read pre-processor function with support for SE and PE reads - Parallelization option of detailed FASTQ quality reports - Read distribution plots across all features available in a genome annotation (see ?featuretypeCounts) - Visualization of coverage trends along transcripts summarized for any number of transcripts (see ?featureCoverage) - Functionalities to predict uORFs/sORFs and to use them for expression profiling - Differential expression/binding analysis includes now DESeq2 as well as edgeR
Added param templates for additional command-line software including, but not limited to: BWA-MEM, GATK, BCFtools, MACS2
Adoption of R Markdown for main vignette. Future plans are to provide for all workflows the report templates in both formats: Latex/PDF and R_Markdown/HTML.
WORFLOW FRAMEWORK
Simplified design of complex analysis workflows. Workflows can now include any number or combination of R and/or command-line steps
Improvements to workflow automation and parallelization on single machines and computer clusters. This also includes now many additional parallelization examples in the workflow vignettes.
Changes in version 1.26.0:
SIGNIFICANT USER-VISIBLE CHANGES
BUG FIXES
Fix potential potencial pearson correlation errors that occur when the standard is deviation zero. If that is the case, replace the resulting NA/NaN by zero.
Fix R check warnings.
Changes in version 0.99.9:
CODE
Modifications in pileupCounts in order to consider stranded counts
Changes in plot methods. arrangeGrob from gridExtra was changed by plot_grid form cowplot package.
Update the package vignette.
Changes in version 0.99.8:
CODE
Modifications in pileupCounts and buildFeaturePanel in order to process overlapped features.
Wrap plotting examples.
Changes in version 0.99.7:
CODE
Modifications in pileupCounts and buildFeaturePanel in order to process overlapped features.
Modifications in bedFile building in order to remove duplicated features based on duplicated start, end and chromosome definitions.
Changes in version 0.99.6:
CODE
Definition of pileupCounts as a function instead a TargetExperiment S4 method.
Adaptation and optimization of pileupCounts and bplapply usage in the buildFeaturePanel method.
Changes in version 0.99.4:
DESCRIPTION file
Changes in version 0.99.3:
CODE
Changes in version 0.99.2:
CODE
Changes in version 0.99.1:
DOCUMENTATION
Changes in version 0.99.0:
DOCUMENTATION
NEWSfile was added.
Changes in version 1.9.3:
changed default value. Set ‘test.method = “DESeq2” as default value when analyze multi-group without replicate data.
add ‘makeFCMatrix’ function for generating the foldchange matrix that is used in ‘simulateReadCounts’ funtion.
add function to simulate DEGs using fondchange matrix into ‘simulateReadCounts’ function.
Changes in version 3.9.1:
new parameter ‘plotchroms’ in function ‘chrom.barplot’ that allows to specify the chromosomes (and their desired order) that shall be included in the plot
bug fix regarding use of ‘Offset’ bases in ‘TEQCreport’
Changes in version 1.7.2:
NEW FEATURES
New class TFFMFirst and TFFMDetail for next generation TFBSs.
Novel TFFM sequence logo.
BUG FIXES
Changes in version 1.9.9:
Major update to the CCR-part: It is now possible to fit and plot multiple experiments simultaneously.
It is now possible to perform user-specified comparisons of different experiments. They are specified in the ‘comparison’ column of the config table.
TR-part: Hypothesis testing is now separated from result table creation. Therefore, a new function was introduced (tpptrAnalyzeMeltCurves) -> see vignette.
CCR-part: Curve fitting and plotting are now conducted by separate functions -> see vignette.
Bug fixes
Introduced color coding of the columns belonging to different experiments in the excel output. This requires openxlsx version >= 2.4.0.
The CCR workflow now only returns normalized measurements if normalization was actually performed. Unmodified measurements are always returned and indicated by the suffix ‘unmodified’.
Data import from tab-delimited files now ignores quotes so that protein annotation fields can contain single ‘ or “ characters.
Now enabling arbitrary numbers of plot colors for melting curves or dose response curves.
Changes in version 1.2.5:
CCR-import: Argument nonZeroCols can be NULL if no additional filtering is needed.
CCR output: To make filtering easier, the ‘passed_filter’ column now shows FALSE even if proteins could not be used for fitting (instead of NAs).
CCR output: To make filtering easier, the ‘passed_filter’ column now shows FALSE even if proteins could not be used for fitting (instead of NAs).
CCR output: column with normalization results was renamed from ‘normalized’ to ‘median_normalized’ to distinguish from the newly introduced normalization to value at lowest concentration.
Excel export: Columns are only color-coded by experiment, when the number of experiments is > 1.
Excel export: Columns are only color-coded by experiment when the number of experiments is > 1.
Excel export: Relative paths to the plots work now for TR- and CCR part
Bug fix for data import: Unique identifiers now treated correctly again.
Bug fix for Excel output: Boolean column entries are only transformed to “yes”/”no” for non-missing values.
Bugfix in TR-QC plots: do not attempt to create Tm difference histograms if only one experiment is provided.
Bugfix in TR normalization: fixedReference argument works again
Changes in version 1.1.4:
Changes in version 1.1.3:
Changes in version 1.1.2:
Changes in version 1.1.1:
Changes in version 1.1.0:
Changes in version 1.5.6:
update documentation.
add new feature for optimizing the styles with theme.
Changes in version 1.5.5:
NEW FEATURES
BUG FIXES
Changes in version 1.5.4:
NEW FEATURES
BUG FIXES
Changes in version 1.5.3:
NEW FEATURES
BUG FIXES
Changes in version 1.5.2:
NEW FEATURES
Add GRanges operators: +, -, *, /
export parseWIG function.
BUG FIXES
Changes in version 1.15.1:
Changes in version 2.0.0-16:
Changes in version 0.99.8:
Changes in version 0.99.7:
added new class varPartResults to store results of fitExtractVarPartModel() and fitExtractVarPartModel() - the user will not notice any change, only the backend is different
Allow computation of adjusted ICC in addition to ICC.
add warning when categorical variables are modeled as fixed effects
fix computation of variance fractions for varying coefficient models
add getVarianceComponents() to return variances from lmer() or lm() model fit
showWarnings=FALSE suppresses warning messages
add fxn argument to fitVarPartModel to evaluate any function on the model fit
Changes in version 0.99.6:
Changes in version 0.99.5:
Changes in version 0.99.4:
add documentation for example datasets
convert calcVarPart() to S4 from S3 function call
fix typos in vignette
Changes in version 0.99.3:
Changes in version 0.99.2:
rename sort.varParFrac to sortCols
support ExpressionSet
change options for plotStratifyBy() # Before Bioconductor submission
Changes in version 0.99.0:
Changes in version 1.16.0:
NEW FEATURES
support REF and ALT values “.”, “+” and “-“ in predictCoding()
return non-translated characters in VARCODON in predictCoding() output
add ‘verbose’ option to readVcf() and friends
writeVcf() writes ‘fileformat’ header line always
readVcf() converts REF and ALT values “*” and “I” to ‘’ and ‘.’
MODIFICATIONS
VRanges uses ‘*’ strand by default
coerce ‘alt’ to DNStringSet for predictCoding,VRanges-method
add detail to documentation for ‘ignore.strand’ in predictCoding()
be robust to single requrested INFO column not present in vcf file
replace old SummarizedExperiment class from GenomicRanges with the new new RangedSummarizedExperiment from SummarizedExperiment package
return strand of ‘subject’ for intronic variants in locateVariants()
BUG FIXES
writeVcf() does not duplicate header lines when chunking
remove extra tab after INFO when no FORMAT data are present
filteVcf() supports ‘param’ with ranges
Changes in version 1.6:
USER VISIBLE CHANGES
Update on the scores() method for PhastConsDb objects that enables a 10-fold faster retrieval of mean phastCons scores over genomic intervals.
Added two new annotated regions coded as fiveSpliceSite and threeSpliceSite and the scoring of their binding affyinity, if scoring matrices are provided.
BUG FIXES
Fix on the scores() method for PhastConsDb objects, that was affecting multiple-nucleotide ranges from an input GRanges object with unordered sequence names.
Fix on snpid2maf() method when decoding MafDb variants with AF values whose significant digits start with 95.
Changes in version 1.45.7:
USER VISIBLE CHANGES
Changes in version 1.45.6:
NEW FEATURE
BUG FIXES
Changes in version 1.45.5:
USER VISIBLE CHANGES
The sampclass method for xcmsSet will now return the content of the column “class” from the data.frame in the phenoData slot, or if not present, the interaction of all factors (columns) of that data.frame.
The sampclass<- method replaces the content of the “class” column in the phenoData data.frame. If a data.frame is submitted, the interaction of its columns is calculated and stored into the “class” column.
BUG FIXES
Changes in version 1.45.4:
BUG FIXES
Changes in version 1.45.3:
NEW FEATURE
xcmsSet now allows phenoData to be an AnnotatedDataFrame.
new slots for xcmsRaw: - mslevel: store the mslevel parameter submitted to xcmsRaw. - scanrange: store the scanrange parameter submitted to xcmsRaw.
new slots for xcmsSet: - mslevel: stores the mslevel argument from the xcmsSet method. - scanrange: to keep track of the scanrange argument of the xcmsSet method.
USER VISIBLE CHANGES
show method for xcmsSet updated to display also informations about the mslevel and scanrange.
Elaborated some documentation entries.
rtrange and mzrange for xcmsRaw method plotEIC use by default the full RT and m/z range.
Added arguments “lty” and “add” to plotEIC method for xcmsRaw.
getEIC without specifying mzrange returns the ion chromatogram for the full m/z range (i.e. the base peak chromatogram).
BUG FIXES
Checking if phenoData is a data.frame or AnnotatedDataFrame and throw an error otherwise.
xcmsSet getEIC method for water Lock mass corrected files for a subset of files did not evaluate whether the specified files were corrected.
Changes in version 1.45.2:
BUG FIXES
Changes in version 1.45.1:
NEW FEATURE
plotrt now allows col to be a vector of color definition, same as the plots for retcor methods.
Added $ method to access phenoData columns in a eSet/ExpressionSet like manner.
Allow to use the “parallel” package for parallel processing of the functions xcmsSet and fillPeaks.chrom.
Thanks to J. Rainer!
Changes in version 3.2:
VERSION xps-1.29.1
Changes in version 1.29.1:
No packages were removed in this release. | http://bioconductor.org/news/bioc_3_2_release/ | CC-MAIN-2019-13 | en | refinedweb |
Haskell: A simple parsing example using pattern matching
As part of the second question in the Google Code Jam I needed to be able to parse lines of data which looked like this:
3 1 5 15 13 11
where
The first integer will be N, the number of Googlers, and the second integer will be S, the number of surprising triplets of scores. The third integer will be p, as described above. Next will be N integers ti: the total points of the Googlers.
This seemed like it should be easy to do but my initial search led me to the Parsec chapter in Real World Haskell which seemed a bit over the top for my problem.
All we really need to do is split on a space and then extract the parts of the resulting list.
I thought there’d be a ‘split’ function to do that in the base libraries but if there is I couldn’t see it.
However, there are a bunch of useful functions in the ‘Data.List.Split’ module which we can install using cabal - a RubyGems like tool which came with my Haskell installation.
Installing the split module was as simple as:
cabal update cabal install split
There’s a list of all the packages available through cabal here.
I needed the splitOn function:
import Data.List.Split > :t splitOn splitOn :: Eq a => [a] -> [a] -> [[a]]
We can then split on a space and extract the appropriate values using pattern matching like so:
let (_:surprisingScores:p:googlers) = map (\x -> read x :: Int) $ splitOn " " "3 1 5 15 13 11"
> surprisingScores 1
> p 5
> googlers [15,13,11]
About the author
Mark Needham is a Developer Relations Engineer for Neo4j, the world's leading graph database. | https://markhneedham.com/blog/2012/04/15/haskell-a-simple-parsing-example-using-pattern-matching/ | CC-MAIN-2019-13 | en | refinedweb |
One a method that can be applied to many density
functions. Essentially, given a density function over [latex]
\mathbb{R}\^m[/latex], [latex] f(x) = \frac{h(x)}{H}[/latex] where
[latex]H[/latex] is a normalization constant (ie. [latex] h(x) \geq
0[/latex], [latex] H = \int h(x)dX[/latex]). Given a parameter [latex]
c > 0 [/latex] and a parametrization [latex]\phi[/latex] from [latex]
\mathbb{R}\^{m+1}[/latex] to [latex] \mathbb{R}\^{m}[/latex] expressed
as: \$\$ \phi(v_0, v_1, …, v_m) = \left ( \frac{v_1}{v_0\^c},
\frac{v_2}{v_0\^c}, …, \frac{v_m}{v_0\^c} \right )\$\$
Define the set [latex] \mathcal{C} = \{\mathbf{v} \big | \gamma(\mathbf{v}) \leq 0, v_0 > 0\} \in \mathbb{R}\^{m+1}[/latex] where
\$\$\gamma(\mathbf{v}) = \log v_0 - \frac{\log h(\phi(v_0, v_1, …, v_m))}{mc + 1}\$\$ If [latex] \mathcal{C}[/latex] is bounded and we sample a uniform vector [latex] \mathbf{V} \sim \text{Uniform}(\mathcal{C})[/latex] then [latex] \phi(\mathbf{V}) \sim f(x)[/latex]. Also note that the measure (volume) of the set [latex] \mathcal{C}[/latex] is [latex] \frac{H}{mc + 1}[/latex]. I do not have any references for the proof, except for a book in Romanian, but if you are interested, just leave me a comment and I’ll do a follow-up post with the proofs.
Univariate scenario
For the univariate case, all the above simplifies to \$\$ \mathcal{C} =
\left \{(u, v) \Big | 0 \< u \< \sqrt
{h\left (\frac{v}{u\^c}\right )} \right \} \$\$. We generate [latex] (U, V) \sim \text{Uniform}(\mathcal{C})[/latex] and take [latex] \frac{V}{U\^c} \sim f(x)[/latex].
Since we are looking at the (univariate) Gamma distribution, described by: \$\$ f(x; \nu, \theta) = \frac{x\^{\mu - 1} \exp(\frac{-x}{\theta})}{\theta\^k\Gamma(k)}\$\$ [latex] \nu[/latex] is the shape parameter and [latex] \theta[/latex] is the scale parameter.
But because of the property that if [latex] X \sim \text{Gamma}(\nu, \theta)[/latex], then for any [latex] k > 0[/latex], [latex] kX \sim \text{Gamma}(\nu, k\theta)[/latex], we conclude that we can fix [latex] \theta[/latex] to 1 without loss of generality. Replacing in the style of the definition in the previous section, we have [latex] h(x; \nu) = x\^{\nu-1}e\^{-x}[/latex] and [latex] H_\nu = \Gamma(\nu)[/latex].
This allows us to compute the equation of the boundary of the set [latex] \mathcal{C}[/latex] which ends up being described by [latex]\gamma(u, v) = \log{u} - \frac{\nu - 1}{c + 1} \log{\left(\frac{v}{u\^c}\right)} + \frac{1}{c+1} \frac{v}{u\^c}[/latex]. For visualisation purposes, here is how it would look like for [latex] \nu=6, c=1[/latex] (plotted using Wolfram Alpha):[
]
Sampling algorithm
In order to uniformly sample from this set, we can apply basic rejection
sampling: just uniformly sample from a rectangular region surrounding
the set, and reject the points that do not satisfy the condition. In
order to do this as efficiently as possible, we need to compute the
minimal bounding box, which can be done by solving a couple of
optimization problems using Lagrange multipliers and the KKT conditions.
Also by looking closely at the image, you can see that the lower left
corner is exactly the origin: this turns out not to be a coincidence. I
won’t go into detail here, but here are the bounds I derived:
\$\$ 0 \< u \< (\nu - 1)\^\frac{\nu - 1}{c + 1} e \^ {-\frac{\nu - 1}{c + 1}} \text{ and } 0\< v \< \left(\frac{c\nu + 1}{c}\right)\^{\frac{c\nu + 1}{c + 1}} e \^ {- \frac {c\nu + 1}{c+1}}\$\$
The probability of acceptance (which can be seen as the efficiency) of the rejection sampling method is given by the ratio of the areas of the set [latex] \mathcal{C}[/latex] and the bounding box. The larger this probability, the less points we throw away and the more efficient the algorithm is. Using the values derived above, this probability is: \$\$ p(\nu, c) = \frac{\Gamma(\nu)e\^{\nu}}{(c+1) (\nu - 1)\^{\frac{\nu - 1}{c + 1}} \left(\frac{c\nu + 1}{c}\right)\^{\frac{c\nu + 1}{c + 1}}}\$\$
Personally I got stumped here. The idea would be to determine the ideal [latex] c[/latex] for a given [latex] \nu[/latex] in order to maximize the probability, but I didn’t manage to do it (I leave it as an exercise for the reader ;)). Anyway, this is enough to proceed with an implementation, so I’m gonna give the Python code for it. Note that I used the name k for the shape parameter instead of [latex] \nu[/latex]. Also note that the case when [latex] 0 \< \nu \< 1[/latex] needed to be treated separately, which I did using the following property: Let [latex] \nu \in (0, 1)[/latex]. If [latex] X’ \sim \text{Gamma}(1+\nu, 1), U \sim \text{Uniform}(0, 1)[/latex] then \$\$ X = X’ \cdot \sqrt[\nu]{U} \sim \text{Gamma}(\nu, 1)\$\$ For a proof of this fact, see [1], which is a great article on generating Gamma variates.
Implementation
[sourcecode language=”python”]
from import numpy as np
def _cond(u, v, k, c):
“”“Identity function describing the acceptance region”“”
x = v / u ** c
return (c + 1) * np.log(u) \<= (k - 1) * np.log(x) - x
def vn_standard_gamma(k, c=1.0, rng=np.random):
“”“Generates a single standard gamma random variate”“”
if k \<= 0:
raise ValueError(“Gamma shape should be positive”)
elif k \< 1:
return vn_standard_gamma(1 + k, c, rng) * rng.uniform() ** (1 / k)
elif k == 1:
return rng.standard_exponential()
else:
a, b = get_bounds(k, c)
while True:
u, v = rng.uniform(0, a), rng.uniform(0, b)
if _cond(u, v, k, c):
break;
return v / u ** c
def vn_gamma(k, t, shape=1, c=1.0, rng=np.random):
“”“Vectorized function to generate multiple gamma variates”“”
generator = lambda x: t * vn_standard_gamma(k, c, rng)
generator = np.vectorize(generator)
return generator(np.empty(shape))
def get_bounds(k, c=1.0):
“”“Computes the minimal upper bounds surrounding the acceptance region”“”
a = ((k - 1) / np.e) ** ((k - 1) / (c + 1))
b = ((c * k + 1) / (c * np.e)) ** ((c * k + 1) / (c + 1))
return a, b
def prob_acc(k, c=1.0):
“”“Calculates the probability of acceptance for the given parameters”“”
from scipy.special import gamma
a, b = get_bounds(k, c)
return gamma(k) / ((c + 1) * a * b)
[/sourcecode]
Results
And of course I should show you that it works. Here are some histograms for various values of [latex] \nu[/latex], with the theoretical density plotted in dotted red, after sampling [latex] 10\^5[/latex] values. The y-axis is the frequency (sorry for labeling in Romanian), and for the red dotted line it can be interpreted as the theoretical probability. You can clearly see the goodness of fit is excellent.
1: George Marsaglia and Wai Wan Tsang. 1998. The Monty Python method for generating random variables. ACM Trans. Math. Softw. 24, 3 (September 1998), 341-350. DOI=10.1145/292395.292453
[
]:
[
]:
[
]:
[
]: | http://vene.ro/blog/sampling-gamma-random-variates-through-the-ratio-of-uniforms-method.html | CC-MAIN-2019-13 | en | refinedweb |
Member Since 3 Years Ago
4,265.
tronix left a reply on Multiple Connection Use Orm And SetConnection Way,it Can Not Work!
Hi, I had this problem too. I solved putting this code in the constructor of your Model
<?php namespace App\Models; class SecondModel extends \Illuminate\Database\Eloquent\Model public function __construct(Array $attributes = []) { parent::__construct($attributes); $this->setConnection('yourOtherConnectionName'); // see config/database.php where you have specified this second connection to a different DB }
Then your "Test" class must extend this "SecondModel", so that it inherits this connection. Now you can use:
Test::find($id); // it uses the non-default connection
tronix started a new conversation Laravel Uses The Default Queue Even If I Specified A Different Queue/tube
I'm using Laravel 5.0.2. I need to use two different queues in my code. They must use the beanstalkd driver. So I specified those queues in config/queue.php:
'default' => env('QUEUE_DRIVER', 'sync'), 'connections' => [ 'sync' => [ 'driver' => 'sync', ], 'bean-high' => [ 'driver' => 'beanstalkd', 'host' => '127.0.0.1', 'queue' => 'bean-high', 'ttr' => 60, ], 'bean-low' => [ 'driver' => 'beanstalkd', 'host' => '127.0.0.1', 'queue' => 'bean-low', 'ttr' => 60, ], [...]
In my code, I used:
Queue::pushOn('bean-low', new SendEmail($message ));
My listener is:
php artisan queue:work --daemon --queue="bean-high","bean-low" --tries=3 --env="production"
My actual environment is "production".
It seems ok, but Laravel uses always the default queue (the "sync" driver) even if I specified a different queue. I tried to change the default driver to a fake one and I've seen that it uses this driver (throwing an exception).
If I specify the "bean-high" or "bean-low" connection as the default driver in the queue.php file, my queues works correctly, but the queue/tube parameter in "Queue::pushOn" is always skipped.
What am I doing wrong?
tronix left a reply on Google Map Problem
I had the same problem. The map is hidden because you didn't specify the height of the . I solved adding a "height: 400px" to the map-canvas-0 id. You can add this css style to your file:
into thetag. Every "map-canvas-xy" IDs are targeted by that css rule.
Hope this helps | https://laracasts.com/@tronix | CC-MAIN-2019-13 | en | refinedweb |
%I
%S 1,2,4,6,8,9,12,15,16,18,20,24,25,27,28,30,32,35,36,40,42,44,45,48,49,
%T 50,52,54,55,56,60,63,64,65,66,70,72,75,77,78,80,81,84,85,88,90,91,95,
%U 96,98,99,100,102,104,105,108,110,112,114,115,117,119,120
%N Positive integers x that are (x-1)/log(x-1) smooth, that is, if a prime p divides x, then p <= (x-1)/log(x-1).
%C This sequence is a monoid under multiplication, since if x and y are terms in the sequence and p < x/log(x), then p < xy/log(xy). However, if a term in the sequence is multiplied by a number outside the sequence, the result need not be in the sequence.
%e 1 is in the sequence because no primes divide 1, 2 is in the sequence since 2 divides 2 and 2 < 2/log(2) ~ 2.9, but 10 is not in the sequence since 5 divides 10 and 5 is not less than 10/log(10) ~ 4.34.
%t ok[n_] := AllTrue[First /@ FactorInteger[n], # Log[n] <= n &]; Select[ Range[120], ok] (* _Giovanni Resta_, Jun 30 2018 *)
%o (PARI) isok(n) = my(f=factor(n)); for (k=1, #f~, if (f[k,1] >= n/log(n), return(0))); return (1); \\ _Michel Marcus_, Jul 02 2018
%Y Cf. A050500.
%K nonn
%O 1,2
%A _Richard Locke Peterson_, Jun 29 2018 | http://oeis.org/A316350/internal | CC-MAIN-2019-13 | en | refinedweb |
While getting data from one of web service quote(") is coming as (?) when i use Rest Template. I tested the web service in the postman on chrome and it giving correct characters. I tried encoding UTF-8, but no success. I checked following are encodin
I want to write something to the end of the file every time the file is modified and I'm using this code : public class Main { public static final String DIRECTORY_TO_WATCH = "D:\\test"; public static void main(String[] args) { Path toWatch = Pa
As per the Java ternary operator expression ? statement1 : statement2, if expression is true then statement1 will be executed, if expression is false then statement2 will be executed. But when I run: // some unnecessary codes not displaying char y =
Here is an use case of general java multithreading implementation: I have one cpu with four virtual cores. I have four cpus with four physical cores. Which hardware should I choose to efficiently implement a multithreaded application. As far as I kno
I'm trying to use annotations with a custom message in spring/hibernate validation. What I want to do is support internationalization while being able to pass in a parameter. For instance, here is the field in the java class: @NotEmpty (message = "{e
My goal is add data to listView, after push on notification shows dialog, if user press Yes, app will show activity with fragment, and again will display new dialog to add new item. But if I press add, I get: java.lang.NullPointerException: Attempt t
I'm trying to call my paintComponent method by using repaint but it is never being called. This is my first class: public class start { public static void main(String[] args){ Frame f = new Frame(); f.createFrame(); } } And this is the class that I w
I am getting an error and I can only assume there is something wrong with my query. I am trying to initialize a class with the "new" key word in JPQL like so: @Query("SELECT NEW com.htd.domain.ShopOrder(po.id, po.po_number, " + "p
I have problem with can't set text in UITextView .see below code , TwxtView value not change after setText() . when i press Button "hello word" not change. i want to change "hello world" to "How are you" when i press Button.
Let's say I have a class (the equal method also exists): public class SomeClassA { private int a; private int b; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; return
I have this code: button2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panel.add(label, BorderLayout.LINE_START); panel.add(label2, BorderLayout.LINE_START); panel.add(textfield, BorderLayout.LINE_EN
I used Java for building Image upload tag: Map options = ObjectUtils.asMap("resource_type", "auto"); options.put("callback", ""); Map htmlOptions = null; String html = cloud
My application flow is as follow. JAVA APP ----> MS SQL (Tables)---> MS SQL (Stored procedure) ---> Another DB Here from Java application i am pushing certain Sensitive information that i even want to hide from DBA. So i want to encrypt those col
public class TestException extends except2 { public static void main(String[] args)throws Exception { try { try { throw new TestException(); } catch (final TestException e){ } throw new except2(); } catch (TestException a){ } catch (Exception e){ thr
I am trying the coding bat problem repeatFront: Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the lengt
I need to extend an existing Liferay webservice (created with Service Builder) to handle an additional optional parameter. With Service Builder, you have to specify every parameters inside the method signature: public String getList(String param1){ .
I make a procedure that get a nvarchar and it return a table by using like and it works well. but when I want to use this procedure in java it doesn't work. here is the java code. String query = "exec Predict ?"; pst = conn.prepareStatement(quer
I have one Activity and six different Fragments attached to it. Each fragment has OnFragmentInteractionListener interface and activity implements all these listeners in order to receive callbacks. It looks a little messy, so I'm interested are there
I am developping an application for my android phone, and I am trying to enable the Wifi hotspot. I am using Qt 5.4.1 so I developp in C++. As there is not any function to do this in the NDK, I am using JNI to call Java Methods. My java code is (than
Usually I'd love all my POJOs to be immutable (well, to contain only final fields as Java understands immutability). But with my current project, a constant pattern is that I need to change a single field from a POJO. Working with immutable POJO's in | http://www.dskims.com/category/java/6/ | CC-MAIN-2019-13 | en | refinedweb |
Wrap around components to hide them if keyboard is up
react-native-hide-with-keyboard
Devices screen are small especially when the keyboard takes half the space, when you're working with forms for instance.
One of the best way to handle that is to hide part of the view when the keyboard shows up.
Install it
npm install -S react-native-hide-with-keyboard
Use it
import HideWithKeyboard from 'react-native-hide-with-keyboard'; ... render() { return ( <View> <HideWithKeyboard> <Text>Hidden when keyboard is shown</Text> </HideWithKeyboard> <Text>Never hidden</Text> </View> ) }
Show components when keyboard is shown
In the case that you want to do the opposite, there is also
ShowWithKeyboard which only shows a component when the keyboard is displayed. To use this, instead import
react-native-hide-with-keyboard like so:
import { HideWithKeyboard, ShowWithKeyboard } from 'react-native-hide-with-keyboard'; | https://reactnativeexample.com/wrap-around-components-to-hide-them-if-keyboard-is-up/ | CC-MAIN-2019-13 | en | refinedweb |
Scala Collections are the containers that hold sequenced linear set of items like List, Set, Tuple, Option, Map etc. Collections may be strict or lazy. The memory is not allocated until they are accessed. Collections can be mutable or immutable.
In this article, let us understand List and Set.
Table of Contents
- 1 Scala List
- 2 Scala Set
Scala List
The elements of the list have same data type. Lists are similar to arrays with two differences that is Lists are immutable and list represents a linked list whereas arrays are flat.
List is represented as
List[T] where T is the data-type of the elements.
Consider an example;
Copyval StudentNames[String] = List("Rohan", "Andreas", "Rob", "John")
Empty list can be created as
Copyval em: List[Nothing] = List()
Two dimensional list can be created as
Copyval twodim: List[List[Int]] = List( List(1, 0, 0), List(0, 1, 0), List(0, 0, 1) )
Basic Operations on Scala List
The basic operations include;
head: returns first element in the list.
tail: returns all the elements except the first element in the list.
isempty: returns true if the list is empty.
Consider an example for these operations;
Copyobject Student { def main(args:Array[String]) { val names= "Harry" :: ("Adam" :: ("Jill" :: Nil)) val age = Nil println( "Head of names array : " + names.head ) println( "Tail of names array : " + names.tail ) println( "Check if names is empty : " + names.isEmpty ) println( "Check if age is empty : " + age.isEmpty ) } }
We are creating student object with two lists – names and age. We are invoking the head, tail and empty method on the array names and age.
Run the output by typing
Student.main(null) and you will see below output.
CopyHead of names array : Harry Tail of names array : List(Adam, Jill) Check if names is empty : false Check if age is empty : true
You can also save the above code in Student.scala file and run as
Copy$scalac Student.scala $scala Student Head of names array : Harry Tail of names array : List(Adam, Jill) Check if names is empty : false Check if age is empty : true
Scala Concatenating lists
To concatenate lists we use ::: or List.:::() or concat method to join two or more lists.
Consider an example of how to concatenate the lists
Copyobject Country { def main(args:Array[String]) { val country_1 = List("India","SriLanka","Algeria") val country_2 = List("Austria","Belgium","Canada") val country = country_1 ::: country_2 println( "country_1 ::: country_2 : " + country ) val cont = country_1.:::(country_2) println( "country_1.:::(country_2) : " + cont ) val con = List.concat(country_1, country_2) println( "List.concat(country_1, country_2) : " + con ) } }
We have created two lists country_1 and country_2. We are concatenating two lists country_1 and country_2 into a single country list using ::: operator. In the second case we are using .::: operator to concat country_1 and country_2 into “cont” list and the second list country_2 data will be first inserted and then country_1 list data is displayed.
Finally we use concat method to concatenate country_1 and country_2 into the list “con”.
Run the above code by typing
Country.main(null) and you will see below output.
Copycountry_1 ::: country_2 : List(India, SriLanka, Algeria, Austria, Belgium, Canada) country_1.:::(country_2) : List(Austria, Belgium, Canada, India, SriLanka, Algeria) List.concat(country_1, country_2) : List(India, SriLanka, Algeria, Austria, Belgium, Canada)
Scala Reverse List Order
The List data structure provides
List.reverse method to reverse all elements of the list.
Consider an example below.
Copyobject Country { def main(args:Array[String]) { val country = List("Denmark","Sweden","France") println("Country List before reversal :" + country) println("Country List after reversal :" + country.reverse) } }
Here we are using reverse method to reverse the elements of the country list.
Run the code by typing
Country.main(null) and you will see below output.
CopyCountry List before reversal :List(Denmark, Sweden, France) Country List after reversal :List(France, Sweden, Denmark)
Scala Creating Uniform Lists
The
List.fill() method creates zero or more copies of the same element.
Consider an example;
Copyobject Student { def main(args: Array[String]) { val name = List.fill(6)("Rehan") println( "Name : " + name ) val id = List.fill(6)(12) println( "Id : " + id ) } }
Here we are using fill method and creating the name list with same name “Rehan” for six elements . The id list created with the same id 12 for all the six elements.
Copyscala>Student.main(null) Name : List(Rehan, Rehan, Rehan, Rehan, Rehan, Rehan) Id : List(12, 12, 12, 12, 12, 12)
Scala List Methods
Some of the other methods supported by List are;
def distinct: List[X] → Builds a new list from the list without any duplicate elements.
def indexOf(elem: X, from: Int): Int → Finds index of first occurrence of some value in the list after or at some start index.
def length: Int → Returns the length of the list.
def sorted[Y >: X]: List[X] → Sorts the list according to an Ordering.
def sum: A → Sums up the elements of this collection.
def toString(): String → Converts the list to a string.
def min: A → Finds the smallest element.
def max A → Finds the largest element.
def lastIndexOf(elem: A, end: Int): Int → Finds index of last occurrence of some value in the list before or at a given end index.
def toMap[X, Y]: Map[X, Y] → Converts this list to a map.
Scala Set
Set is a collection of unique elements of the same type. Unlike list Set does not contain duplicate elements. Sets can be mutable or immutable. When the object is immutable the object itself cannot be changed.
Scala uses immutable set by default. Import
scala.collection.mutable.Set to use the mutable set explicitly.
For example;
Copyval country = Set("Russia", "Denmark", "Sweden")
Set of Integer data type can be created as
Copyvar id : Set[Int] = Set(4,5,6,7,8,9)
Empty Set can be created as;
Copyvar age = Set()
Basic Operation on Set in Scala
The basic operations include;
head → returns first element of a set.
tail → returns all the elements except the first element in the set.
isempty → returns true if the set is empty else returns false.
Consider an example;
Copyobject Student { def main(args: Array[String]) { val name = Set("Smith", "Brown", "Allen") val id: Set[Int] = Set() println( "Head of name : " + name.head ) println( "Tail of name : " + name.tail ) println( "Check if name is empty : " + name.isEmpty ) println( "Check if id is empty : " + id.isEmpty ) } }
Here we are creating student object with two sets “names” and “id”. We are doing head, tail and empty operations on these arrays and printing the result.
Copyscala>Student.main(null) Head of name : Smith Tail of name : Set(Brown, Allen) Check if name is empty : false Check if id is empty : true
Scala Concatenating Sets
To concatenate one or more sets use ++ operator or Set.++() method. While adding the sets duplicate items are removed.
For example;
Copyobject Furniture { def main(args: Array[String]) { val furniture_1 = Set("Sofa", "Table", "chair") val furniture_2 = Set("Bed", "Door") var furniture = furniture_1 ++ furniture_2 println( "furniture_1 ++ furniture_2 : " + furniture ) var furn = furniture_1.++(furniture_2) println( "furniture_1.++(furniture_2) : " + furn ) } }
We are creating two sets furniture_1 and furniture_2 and concatenating these two sets into furniture and furn using ++ and Set.++ operators.
Copyscala> Furniture.main(null) furniture_1 ++ furniture_2 : Set(Door, Sofa, Bed, Table, chair) furniture_1.++(furniture_2) : Set(Door, Sofa, Bed, Table, chair)
Common Values in a Set
The
Set.& method or
Set.intersect method can be used to find the common elements in two or more sets.
Consider an example below.
Copyobject Numbers { def main(args: Array[String]) { val n1 = Set(11,45,67,78,89,86,90) val n2 = Set(10,20,45,67,34,78,98,89) println( "n1.&(n2) : " + n1.&(n2) ) println( "n1.intersect(n2) : " + n1.intersect(n2) ) } }
We are creating two sets of numbers n1 and n2 and finding common elements present in both the sets.
Copyscala> Numbers.main(null) n1.&(n2) : Set(78, 89, 45, 67) n1.intersect(n2) : Set(78, 89, 45, 67)
Maximum and Minimum elements in a Set
The
Set.min method is used to find out the minimum and
Set.max method to find out the maximum amongst the elements available in a set.
Consider an example;
Copyobject Numbers { def main(args: Array[String]) { val num1 = Set(125,45,678,34,20,322,10) println( "Minimum element in the Set is : " + num1.min ) println( "Maximum element in the Set is : " + num1.max ) } }
We are finding the minimum and maximum numbers in set “num1” using the min and max methods.
Copyscala> Numbers.main(null) Minimum element in the Set is : 10 Maximum element in the Set is : 678
Other useful Scala Set Methods
Some of the Set methods in scala programming are;
def contains(elem: X): Boolean → Returns true if elem is contained in this set, else returns false.
def last: X → Returns the last element.
def product: X → Returns the product of all elements of this immutable set with respect to the * operator in num
def size: Int → Returns the number of elements in this immutable set.
def sum: X → Returns the sum of all elements of this immutable set with respect to the + operator in num.
def toList: List[X] → Returns a list containing all elements of this immutable set.
def toSeq: Seq[X] → Returns a sequence containing all elements of this immutable set.
def toArray: Array[X] → Returns an array containing all elements of this immutable set.
def subsetOf(that: Set[X]): Boolean → Returns true if this set is a subset of that, i.e. if every element of this set is also an element of that.
def mkString: String → Displays all elements of this immutable set in a string.
That’s all for now, we will look into other Scala Collection classes in coming posts.
ravi says
Declare the list in the below fashion
val SNames = List[String](“Rohan”, “Andreas”, “Rob”, “John”) | https://www.journaldev.com/8068/scala-collections-example | CC-MAIN-2019-13 | en | refinedweb |
Still…
I wrote a much cleaner version now (in C++) with sorting upfront. There you go:
class Card{ public: int suit; int rank; }; int compareCards(const void *card1, const void *card2){ return (*(Card *)card1).rank - (*(Card *)card2).rank; } int evaluateHand(Card hand[]){ qsort(hand,5,sizeof(Card),compareCards); int straight,flush,three,four,full,pairs; int k; straight = flush = three = four = full = pairs = 0; k = 0; /*checks for flush*/ while (k<4&&hand[k].suit==hand[k+1].suit) k++; if (k==4) flush = 1; /* checks for straight*/ k=0; while (k<4&&hand[k].rank==hand[k+1].rank-1) k++; if (k==4) straight = 1; /* checks for fours */ for (int i=0;i<2;i++){ k = i; while (k<i+3&&hand[k].rank==hand[k+1].rank) k++; if (k==i+3) four = 1; } /*checks for threes and fullhouse*/ if (!four){ for (int i=0;i<3;i++){ k = i; while (k<i+2&&hand[k].rank==hand[k+1].rank) k++; if (k==i+2){ three = 1; if (i==0){ if (hand[3].rank==hand[4].rank) full=1; } else if(i==1){ if (hand[0].rank==hand[4].rank) full=1; } else{ if (hand[0].rank==hand[1].rank) full=1; } } } } if (straight&&flush) return 9; else if(four) return 8; else if(full) return 7; else if(flush) return 6; else if(straight) return 5; else if(three) return 4; /* checks for pairs*/ for (k=0;k<4;k++) if (hand[k].rank==hand[k+1].rank) pairs++; if (pairs==2) return 3; else if(pairs) return 2; else return 1; }
I think it won’t get a straight from ace to five…
Xeroderma, in legal poker a straight cant start with an ace.
Mike, who told you that? It’s called wheel straight or smthn.
Anyways there is much to hand evaluation than implemented here.
I know this is old, but IMHO a better way is to first compute a histogram of suits and ranks. If one of the rank bins is 4 you’ve got 4 of a kind. If one is 3 and another 2 a boat. If a suit bin has 5 cards you have a flush. etc etc etc.
For straights, if hi card – lo card == 4 you’ve got a straight, special case being an ace high straight.
And yeah, A-5 and 10-A are both straights. | https://www.programminglogic.com/a-better-poker-hand-evaluator-in-c/ | CC-MAIN-2019-13 | en | refinedweb |
Map a Mediator to a Baseclass.
Hello guys!
I've just run into a problem as building my robotlegs application. I hope you'll be able to get me some help :) Let me explain.
I have a world map within an external swc, that contains all the countries in the world in specific movieclips. I need to be able to map each and every one of them to a common mediator, say "CountryMediator". My first idea was to create a baseclass that every movieclip extends, but nothing was mapped to these classes when they were added to the stage (and they surely were). I think it's kind of normal as the concrete class that gets exported every time is"France" "United Kingdom" "Spain", based on the class "Country".
Is there any workaround so I just have to write one mapping rule allowing me to map all the countries base on the Country class to the Country mediator?
Thanks for you help!
Comments are currently closed for this discussion. You can start a new one.
Keyboard shortcuts
Generic
Comment Form
You can use
Command ⌘ instead of
Control ^ on Mac
Support Staff 1 Posted by Stray on 23 Oct, 2012 02:05 PM
Hi Thomas,
If you make sure that Country implements an interface, you can use the ViewInterfaceMediatorMap utility to have one rule manage all instances of Country.
The util is here:...
hth, if you have any problems with it do come back,
Stray
Support Staff 2 Posted by Ondina D.F. on 23 Oct, 2012 02:08 PM
Hi Thomas,
Please take a look at the discussion and the utility I linked below, and if you can’t find an answer in there, come back with more questions:)-......
Cheers,
Ondina
3 Posted by thomas.pujolle on 23 Oct, 2012 02:33 PM
Thanks for that ! i'm at this moment trying this ViewInterfaceMediator.
I have 6 WorldZones in my swc, based on the class WorldZone which implements IWorldZone.
But for my 6 views, I get 5 errors (after the first instantiation) saying:
Warning: Injector already has a rule for type "com.worldmap.view::WorldZoneMediator", named "".
If you have overwritten this mapping intentionally you can use "injector.unmap()" prior to your replacement mapping in order to avoid seeing this message.
I have this in my mediator:
[Inject] public var worldZone:IWorldZone;
And this in my mediator map:
mediatorMap.mapView(IWorldZone, WorldZoneMediator);
Am I doing this right? It's weird because it works once, and then fires a warning.
Support Staff 4 Posted by Ondina D.F. on 23 Oct, 2012 04:47 PM
You’re getting those warnings because you’re (probably) using robotlegs 1.5+ and SwiftSuspenders 1.6.
ViewInterfaceMediatorMap worked well with robotlegs v1.4, where robotlegs and swiftsuspenders were in sync.
Stray had a patch for robotlegs’ Context.as, but I can’t find any swcs reflecting the changes.
Try using Stray’s fork of robotlegs.
Support Staff 5 Posted by Ondina D.F. on 23 Oct, 2012 04:52 PM
Context.as:......
6 Posted by thomas.pujolle on 25 Oct, 2012 08:53 AM
Thanks a lot for you help!
I've try to add the previous fixes to my code but it does not seem to help avoiding the warnings. I'm sorry my comprehension of RL is not good enough to allow me to fix this all by myself :/
Do you think I may construct my context the wrong way? I have this:
public class ApplicationContext extends InterfaceEnabledMediatorMapContext {
And this:
public class InterfaceEnabledMediatorMapContext extends Context {
Thanks a lot!!!
Support Staff 7 Posted by Ondina D.F. on 25 Oct, 2012 10:13 AM
Hey Thomas,
No problem:)
It would be easier if you used robotlegs source and replaced Context.as with the patched one. It would work with SwiftSuspenders 1.6, too. I’ll attach rl source with those changes.
Let us know if it worked.
Ondina
8 Posted by thomas.pujolle on 25 Oct, 2012 10:31 AM
All right!
So if I understand the .zip contains the RL sources with the patched Context.as, which will prevent me from getting stuff like:
Warning: Injector already has a rule for type "com.worldmap.view::WorldZoneMediator", named "".
If you have overwritten this mapping intentionally you can use "injector.unmap()" prior to your replacement mapping in order to avoid seeing this message.
And I should just add SwfSuspender 1.6 at the top of this, right?
Support Staff 9 Posted by Ondina D.F. on 25 Oct, 2012 10:33 AM
Exactly.
10 Posted by thomas.pujolle on 25 Oct, 2012 10:36 AM
It does not seem to work :( I didn't find the required adapters in your .zip so I used so ones in the latest RL (1.5.2).
What do you think could cause this? My context extends this one, which extend the one in your .zip:
Support Staff 11 Posted by Ondina D.F. on 25 Oct, 2012 10:39 AM
Have you deleted the rl swc and refreshed the project?
12 Posted by thomas.pujolle on 25 Oct, 2012 12:44 PM
I have.
I have the swf suspender SWC + your .zip source code + the two adapters found in the latest robotlegs (master branch).
Still something seems to be wrong :(
13 Posted by thomas.pujolle on 25 Oct, 2012 12:48 PM
I need to tell my SWF works perfectly anyway, I just wonder if it's going to impact performances, maybe not?
Support Staff 14 Posted by Ondina D.F. on 25 Oct, 2012 01:10 PM
One moment, please. I'm about to answer.
Support Staff 15 Posted by Ondina D.F. on 25 Oct, 2012 01:41 PM
I’m back.
I guess it’s because you’re initializing your context in actionscript.
Try initializing your context inside of the declaration tag, like in piercer’s example:
<fx:Declarations>
<mvcs:InterfaceEnabledMediatorMapContextExample
</fx:Declarations>
See if this works with the patched Context. If it doesn’t work either, then maybe I gave you the wrong patch. I don’t know whether there is a newer version or another solution.
Stray would know more about this.
The warnings aren’t that important, and won’t affect your app’s performance, so, I guess, you could live with it;)
16 Posted by thomas.pujolle on 25 Oct, 2012 01:51 PM
I'm not using flex so I won't be able to try this out, but I think I'm going to stand by what I have right now if you say it does not impact the application, thanks anyway for your time :) RL rules!
Support Staff 17 Posted by Ondina D.F. on 25 Oct, 2012 02:28 PM
No problem, Thomas.
I’ll close this discussion for now. You can re-open it, if need be.
Cheers,
Ondina
Ondina D.F. closed this discussion on 25 Oct, 2012 02:28 PM.
thomas.pujolle re-opened this discussion on 12 Nov, 2012 02:18 PM
18 Posted by thomas.pujolle on 12 Nov, 2012 02:18 PM
Hello guys,
I think I'll have to get through this another time, I have issues when deleting views.
No errors thrown but the flow gets broken at some point, after a mediator deletion. After that, no other mediator of this type is created.
Has anyone in one of his project a version of RL core + the context fix + ViewInterfaceMediatorMap working?
Otherwise I'll have to create this by myself, although I didn't get it right last time.
Thanks for you help :)
Support Staff 19 Posted by Ondina D.F. on 14 Nov, 2012 04:40 PM
Sorry, that you didn't get any answers. I don't know how to help you.
Support Staff 20 Posted by Ondina D.F. on 11 Dec, 2012 11:51 AM
Hi Thomas,
Have you found a solution?
If not, have you considered using robotlegs 2? I don’t know if you can afford to migrate your project to rl2, but rl2 offers easier and cleaner solutions for your use case. Just saying:)
Ondina
P.S. As you know, you can reopen the discussion, if you want to answer
Ondina D.F. closed this discussion on 11 Dec, 2012 11:51 AM. | http://robotlegs.tenderapp.com/discussions/problems/664-map-a-mediator-to-a-baseclass | CC-MAIN-2019-13 | en | refinedweb |
In looking for ways to make couplets of items I've discovered four brilliant methods in the
itertools module.
In making couplets its important to understand how the pairing should be defined. Once an item is chosen, can it be chosen again as the next element in the group? If a set is defined as
{0, 1, 2, 3}, can we define a group as
(0, 0)? This is referred to as replacement.
In making these groups, does the order of the elements matter? is
(0, 1) unique to
(1, 0)? If it doesn't matter than my set of groups should only include one of the pair, but if it does the set should include both. A good analogy to make is if you were choosing a leader for each pair, the leader being the first in the pair, then the order would matter—
0 is the leader in
(0, 1) and vice versa—versus if you were just choosing teams where each member held the same status; it wouldn't matter in what order you defined the group they're all the same group.
The itertools methods are the following
from itertools import ( product, combinations, combinations_with_replacement, permutations)
l = list(range(3)) npairs = 2
print(l)
[0, 1, 2]
list(permutations(l, npairs))
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
This is essentially the different ways to order a pair measured by the Binomial Coefficient
list(combinations(l, npairs))
[(0, 1), (0, 2), (1, 2)]
list(combinations_with_replacement(l, npairs))
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]
product operates on multiple lists, returning pairings between items of different lists. To use on the same list (you probably shouldn't) you would specify the size of the group with the parameter keyword
repeat
IF used in this way one think of it as WITH replacement, where order DOES matter, so
(0, 0) is acceptable, and
(1,0) is unique to
(0, 1)
list(product(l, repeat=npairs))
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
A better way to use product is with different lists
shirts = ['hawaii', 'collared'] shoes = ['sneakers', 'slippers'] pants = ['jeans', 'shorts'] outfits = list(product(shirts, shoes, pants))
outfits
[('hawaii', 'sneakers', 'jeans'), ('hawaii', 'sneakers', 'shorts'), ('hawaii', 'slippers', 'jeans'), ('hawaii', 'slippers', 'shorts'), ('collared', 'sneakers', 'jeans'), ('collared', 'sneakers', 'shorts'), ('collared', 'slippers', 'jeans'), ('collared', 'slippers', 'shorts')] | https://crosscompute.com/n/hS1rBUtOEOPuYYBwjFxDydAxWGMRXUZn/-/different-combinations | CC-MAIN-2019-13 | en | refinedweb |
These are chat archives for django/django
@jdaltonchilders sure, something like this:
import json from myapp.models import Thing lines = [] with open('/path/to/file.json') as f: lines = json.loads(f.read()) for line in lines: Thing(**line).save()
you'd have to make sure each json entry has the exact fields as your model, or else you'd just have to make a new dict and reassign as needed
beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler'
filepath = "BreastCancer201510/*_activities.json.gz" files = glob.glob(filepath) for file in files: with gzip.open(file) as f: lines = json.loads(f.read()) for line in lines: cur.execute("INSERT INTO study_tweet (study,data) VALUES (%s,%s)", (study,line))
filename + ? + current timebecause if the src were the same it wouldn't refresh the picture but obviously django doesn't like that and gives me 404 "". Any ideas?
filename + ‘?’ + current_timeor whatever you have to do to not encode it as
%3F.
'{% static "current.jpg?" %}'. Thank you for help
Has anyone else had this error when inserting json into the database table?
Detail: u0000 cannot be converted to text
I’m trying to use regex to resolve it, but I haven’t had any luck yet. | https://gitter.im/django/django/archives/2016/11/22 | CC-MAIN-2019-13 | en | refinedweb |
Create ArcSDE Connection File (Data Management)
Summary
Creates an ArcSDE connection file for use in connecting to ArcSDE geodatabases.
Usage
Although you can enter any file extension for the ArcSDE Connection File Name, you must use the standard file extension .sde in order for it to be recognised correctly by ArcGIS.
When valid connection information is entered the tool will connect to the ArcSDE server in order to populate the versions list with versions the connected user has permissions to connect to.
Please see A quick tour of connections to ArcSDE geodatabases for a more complete explanation of ArcSDE connection properties.
- If you want to prevent your connection information from being saved in the Results window or stored in the geoprocessing history log files, you will need to disable history logging and save the ArcSDE Connection file without saving the connection information you wish to hide.
This tool should only be used to create application server connections to your geodatabase. If you want to create direct connections then you should use the Create Database Connection tool.
Syntax
Code Sample
The following Python window script demonstrates how to use the CreateArcSDEConnectionFile function in immediate mode.
import arcpy arcpy.CreateArcSDEConnectionFile_management(r'c:\connectionFiles', 'gpserver', '5151', '', 'toolbox', 'toolbox', 'SAVE_USERNAME', 'SDE.DEFAULT', 'SAVE_VERSION')
The following stand-alone script is a simple example of how to apply the CreateArcSDEConnectionFile function in scripting.
# CreateArcSDEConnection.py # Description: Simple example showing use of CreateArcSDEConnectionFile tool # Import system modules import arcpy # Set variables folderName = r"c:\connectionFiles" fileName = "Connection to gpserver.sde" serverName = "gpserver" serviceName = "5151" databaseName = "" authType = "DATABASE_AUTH" username = "toolbox" password = "toolbox" saveUserInfo = "SAVE_USERNAME" versionName = "SDE.DEFAULT" saveVersionInfo = "SAVE_VERSION" #Process: Use the CreateArcSDEConnectionFile function arcpy.CreateArcSDEConnectionFile_management (folderName, fileName, serverName, serviceName, databaseName, authType, username, password, saveUserInfo, versionName, saveVersionInfo) | http://resources.arcgis.com/en/help/main/10.1/0017/0017000000pt000000.htm | CC-MAIN-2017-17 | en | refinedweb |
So the other day I was just experamenting with some code, just for fun, and I ran into some difficulties. So I suppose my question is why the following code does not write to the original bigints array. I am sure I am doing something dumb, but please bear with me. I made my own simple "state machine" thinking that I could return what is essentially a reference to the value in the array, and get away with only two BigIntegers being in memory at any given time. What seems to be happening though is that the value of the BigInteger is copied and then the copy is returned. I thought that whenever you did this "SomeObj obj = new SomeObj();" the left hand side was essentially a really safe pointer. Now this code is really convoluted, so as you can see I was just messing around, and wouldn't use this anywhere else. Perhaps when I access "array[current]" in the getCurrent() method the array copies the datatype instead? I know I am being too clever for my own good, be gentle. Are BigInts value types?
/*Author: overwraith*/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Numerics; namespace Fibonacci { class Program { static void Main(string[] args) { BigInteger[] bigints = new BigInteger[2] { new BigInteger(1), new BigInteger(2) }; try{ LoopingStateMachine<BigInteger> enumerable1 = new LoopingStateMachine<BigInteger>(bigints); //advance one on second state machine LoopingStateMachine<BigInteger> enumerable2 = new LoopingStateMachine<BigInteger>(bigints); enumerable2.MoveNext(); while(enumerable1.MoveNext() && enumerable2.MoveNext()){ BigInteger current = enumerable1.getCurrent(); current += enumerable2.getCurrent(); Console.WriteLine("Fibonacci Number: " + current); }//end loop }catch(OutOfMemoryException){ //can't go any higher } Console.Write("Press any key to continue... "); Console.ReadLine(); }//end main }//end class public class LoopingStateMachine<T> { T[] array; UInt32 current = 0; public LoopingStateMachine(T[] arr){ array = arr; }//end method public T getCurrent(){ return array[current]; } public bool MoveNext(){ //reset the current index if (current == array.Length - 1) current = 0; else this.current++; return true; }//end method }//end class }//end namespace | https://www.daniweb.com/programming/software-development/threads/493823/convoluted-fibonacci | CC-MAIN-2017-17 | en | refinedweb |
std::basic_istream::sync
Synchronizes the input buffer with the associated data source.
Behaves as
UnformattedInputFunction, except that gcount() is not affected. After constructing and checking the sentry object,
if rdbuf() is a null pointer, returns -1
Otherwise, calls rdbuf()->pubsync(). If that function returns -1, calls setstate(badbit) and returns -1. Otherwise, returns 0.
[edit] Parameters
(none)
[edit] Return value
0 on success, -1 on failure or if the stream does not support this operation (is unbuffered).
[edit] Notes
As with readsome(), it is implementation-defined whether this function does anything with library-supplied streams. The intent is typically for the next read operation to pick up any changes that may have been made to the associated input sequence after the stream buffer last filled its get area. To achieve that,
sync() may empty the get area, or it may refill it, or it may do nothing. A notable exception is Visual Studio, where this operation discards the unprocessed input when called with a standard input stream.
[edit] Example
Demonstrates the use of input stream sync() with file input, as implemented on some platforms.
#include <iostream> #include <fstream> void file_abc() { std::ofstream f("test.txt"); f << "abc\n"; } void file_123() { std::ofstream f("test.txt"); f << "123\n"; } int main() { file_abc(); // file now contains "abc" std::ifstream f("test.txt"); std::cout << "Reading from the file\n"; char c; f >> c; std::cout << c; file_123(); // file now contains "123" f >> c; std::cout << c; f >> c; std::cout << c << '\n'; f.close(); file_abc(); // file now contains "abc" f.open("test.txt"); std::cout << "Reading from the file, with sync()\n"; f >> c; std::cout << c; file_123(); // file now contains "123" f.sync(); f >> c; std::cout << c; f >> c; std::cout << c << '\n'; }
Possible output:
Reading from the file abc Reading from the file, with sync() a23 | http://en.cppreference.com/w/cpp/io/basic_istream/sync | CC-MAIN-2017-17 | en | refinedweb |
Simple MVVM in WPF
The WPF scene has exploded as the now-dominant desktop application scene for Windows desktop applications. Couple that with the new Windows 8-style store apps and XAML, it looks like it has a very rosy future indeed.
The problem is, WPF is hard, very hard. You have Prism, MVVM Light, MVVM Cross, Catel, and dozens of other frameworks that all claim to be the best way to do MVVM in a WPF application. If you're still relatively wet behind the ears with WPF, and still much prefer the simplicity of sticking with Windows forms, then like me you may have or may be finding that all this choice just seems to make things way too complicated.
There Has to Be an Easier Way
The good news is, there is, but before we come to that, you need to understand why all these frameworks are needed in the first place. The MVVM model that WPF employs is not all that straightforward, especially when you compare it to things like KnockoutJS, Angular, and many others in the HTML world.
For a starters, before your data objects will even begin to start telling their parent application about what's going on, you need to add something called property notifications to them. This generally means that you need to build a base class, and then derive all your models from that base class. Your base class would typically have the stubs in to allow you implement these notifications so that the parent app and its XAML can see the changes to data in your objects.
Secondly, you need to use different variable types to those you may be more used to as a Win-Forms developer. For example, many of you might be used to using 'List<T>' for many lists of objects. In WPF, you nearly always have to use an 'ObservableCollection<T>', which you wouldn't ever know until someone pointed it out to you. Why? A 'List<T>' will work quite happily with no obvious errors other than the fact you'll see no list changes when you add/remove data from your list, and adding all the Property Notifications in the world won't help.
Once you get your head around all the object changes, you then have the binding syntax to deal with in the XAML itself, and there are about 100 different ways here to do the same thing with the same bit of data. The net result is that all these frameworks have sprung up to 'Make it Easier' to deal with.
This new ease comes at a cost generally, though. You have the learning curve that the framework itself exposes, and each framework tends to implement MVVM in what it believes to be a correct use of the pattern. This 'Correct Use' does not always align with how many developers understand, or might even implement, the pattern themselves.
If you're coming from Win-Forms and are used to how that works, the gap between the stepping stones is even larger, because many will already have a good set of pre-conceived notions as to exactly what desktop application development entails, and I can pretty much grantee that mentality goes something like:
- Load Data
- Manipulate Data
- Push Data into a Data Context
- Let the Component draw it how it needs to
In contrast, the WPF version is a lot longer, and involves way more fluff to get the data displayed in the form. Now you have a firm Idea of where I'm heading with this, I'm going to introduce you to "Fody"
"Fody"? Isn't That a Small Bird of Some Description?
Yes it is, but it's also the name of a rather nifty .NET toolkit designed not just for WPF, but for .NET in general. Fody consists of a very simple transparent kernel (that you typically don't even have to touch or do anything with) and a number of 'Plugins', which in most cases you don't have to do anything with either. Fody, as described at its github page, is
"An Extensible tool for weaving .net assemblies"
In a nutshell, Fody's exact purpose for existence is to inject 'Stuff' automatically into your code, that you may need but without you having to do the injecting. It handles the link between your project and MSBuild, it makes sure all the dependencies are met, and various other things that you simply just don't need to deal with. The net result is you get value added goodness without the overheads.
Okay, So Fody's Great, but What's That Got to Do with WPF?
The easiest way to answer that question is to build a simple WPF application. Fire up Visual Studio, head to New Project, and create a new WPF Application project. Name it however you wish; I'll be calling mine 'EasyWpfWithFody'.
Once your application is up and running, the first thing we're going to do is design the UI. This won't be anything particularly pretty. I'm a developer by trade and I left my box of crayons behind when I left pre-school. My sense of design is not a particularly good one, so instead of describing the UI step by step, I'm just going to give you a screen shot and the XAML that produces it.
Figure 1: Product of the following XAML code
The XAML code to produce this screen is as follows: (Warning; there's a lot of it!!)
<Window x: <Window.Resources> <Style TargetType="{x:Type ListBox}"> <Setter Property="HorizontalContentAlignment" Value="Stretch"/> <Setter Property="ItemTemplate"> <Setter.Value> <DataTemplate> <Border BorderBrush="Silver" BorderThickness="1" CornerRadius="0" Margin="3"> <Grid> . <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. </Grid> </Border> </DataTemplate> </Setter.Value> </Setter> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBox"> <Grid Background="{TemplateBinding Background}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid Grid. > <Grid.Resources> <Style TargetType="TextBlock"> <Setter Property="FontSize" Value="15"/> </Style> </Grid.Resources> <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. </Grid> <ScrollViewer Grid. <ItemsPresenter x: </ScrollViewer> </Grid> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ItemContainerStyle"> <Setter.Value> <Style TargetType="ListBoxItem"> <Setter Property="Margin" Value="0"/> <Setter Property="Padding" Value="0"/> </Style> </Setter.Value> </Setter> </Style> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="50" /> <RowDefinition Height="100" /> </Grid.RowDefinitions> <ListBox Grid. <Grid Grid. <Grid.ColumnDefinitions> <ColumnDefinition Width="0.6*" /> <ColumnDefinition Width="0.4*" /> <ColumnDefinition Width="0.8*" /> <ColumnDefinition Width="0.4*" /> <ColumnDefinition Width="0.8*" /> <ColumnDefinition Width="0.6*" /> </Grid.ColumnDefinitions> <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. </Grid> <Grid Grid. <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> . <TextBlock Grid. <TextBlock Grid. <TextBlock Grid. <TextBox Grid. <TextBox Grid. <TextBox Grid. <TextBox Grid. <Button x: </Grid> </Grid> </Window>
If you look through the various 'Text', 'Content', and other properties in the XAML, you'll see many of the '{binding xxxx}' entries that bind the data values between our UI and the code we'll write in just a moment. The Jobs list, for example, has its collection bound to 'Jobs', which, as you'll see in just a moment, in an 'ObservableCollection<JobEntry>' bound to a local object in the windows code behind. Most of the bindings used in the UI are purposely done the most simple way possible, so that a developer coming over from WPF can see the relationship to how this may have been done using Win-Forms.
Once we have the UI added, it's then time to turn our attention to the code behind the UI, and here's where it gets strange. Many developers used to Win-Forms will be used to having a LOT of code in the code behind. In WPF, the situation is drastically reversed. As you can see above, the code to draw the UI is not by any means short; the code for the code behind is, well... see for yourself:
using System.Windows; using EasyWpfWithFody.Models; namespace EasyWpfWithFody { public partial class MainWindow : Window { public JobSheet CurrentJobSheet { get; private set; } public MainWindow() { CurrentJobSheet = new JobSheet(); InitializeComponent(); } private void BtnAddNewClick(object sender, RoutedEventArgs e) { CurrentJobSheet.Jobs.Add(CurrentJobSheet. JobEntryToAdd); } } }
Yes, you're reading that correctly; that's ALL there is. It may take some believing; you could even remove that button handler if you wanted, but doing things the button click way feels comfortable (at least to me, anyway). One important thing to point out is the order of initialising the data. You'll see that I create my local data object BEFORE I let .NET initialize the various components and so forth on the UI. If you get this the wrong way around, the bindings simply won't work even if you have all the various property notification stuff correctly wired in.
You can see that my local variable 'CurrentJobSheet' is of type 'JobSheet', the UI is connected to this via the following line in the XAML:
DataContext="{Binding CurrentJobSheet, RelativeSource={RelativeSource Mode=Self}}"
You can see right away, at the very top in the 'Window' definition. From this point on, any bindings that simply point to a variable or property name are expected by XAML to be available inside this object.
The class definition for a 'JobSheet' looks like this:
using System; using System.Collections.ObjectModel; using System.Linq; using PropertyChanged; namespace EasyWpfWithFody.Models { public class JobSheet { public Double TaxRatePercentage { get; set; } public ObservableCollection<JobEntry> Jobs { get; private set; } public Double TotalCostBeforeTax { get { return Jobs.Sum(x => x.TotalCost); } } public Double TotalCostAfterTax { get { var temp = TotalCostBeforeTax/100; return TotalCostBeforeTax + (TaxRatePercentage*temp); } } public JobEntry JobEntryToAdd { get; set; } public JobSheet() { Jobs = new ObservableCollection<JobEntry>(); TaxRatePercentage = 20; // Default for UK is 20% SetUpDemoData(); } private void SetUpDemoData() { Jobs.Add(new JobEntry { JobTitle = "Fix Roof", ClientName = "Joe Shmoe", CostPerHour = 30, NumberOfHours = 2 }); Jobs.Add(new JobEntry { JobTitle = "Unblock Sink", ClientName = "Fred Flintstone", CostPerHour = 20, NumberOfHours = 4 }); Jobs.Add(new JobEntry { JobTitle = "Mow Lawns", ClientName = "Mr Mansion Owner", CostPerHour = 40, NumberOfHours = 6 }); Jobs.Add(new JobEntry { JobTitle = "Sweep Path", ClientName = "Jane Doe", CostPerHour = 10, NumberOfHours = 1 }); JobEntryToAdd = new JobEntry(); } } }
There's not a great deal to it, and most of its bulk consists of setting up the initial dummy data. The other class you'll need to create is the actual job entry itself; it looks like this:; } } } }
Once you get to this point with the two models—the code behind and the UI—you should actually be able to hit F5 and get something up and running. You'll notice, however, that adding new entries to the job sheet doesn't update the display, and if anything is entered into to any of the text boxes on the form, the respective elements in the code behind won't get populated as expected. This is exactly the problem that trips up most devs coming from Win-Forms to WPF. They go ahaed and build up a UI in a not too dissimilar way to how they might do it in a Win-Forms application.
Then, they inevitably hit a brick wall and don't understand why the updates don't work. This is where you need to start adding your property notifications and sub classing things so you don't have to repeat your code; it's also at this point where Fody comes into play.
Jump into your NuGet package manager. You can use the console if you want, but I tend to use the GUI becauses it's easier to do partial name searches. Pop 'fody property' into the search box, and you should see the following:
Figure 2: The search results
As you can see, I've already selected and clicked install on 'Fody' and 'PropertyChanged.Fody' because these are the only two we need for this example. There are, however, many others, for all sorts of different purposes.
I mentioned previously that we could remove the Button Handling from the code behind. Well, you would use 'Commander.Fody' to help you with that one. Feel free to explore; there's some great tools in the kit. For the rest of this article, we'll be looking only at 'PropertyChanged'.
At this point you might be thinking, "Okay, great, we have the code, we have the UI, but now I have to learn this Fody thing, so I'm still not skipping the learning curve step."
Well, yes, you can dig in and learn all about Fody and everything it can do.
OR
You can take a quick peek in the object browser and note that all you really need to know is that it implements an 'Aspect' or, as some may know, an 'Attribute'
We've not got space here for a full discussion on AOP (Aspect Orientated Programming), but those of you who've used tools such as 'Postsharp' or are very familiar with ASP.NET MVC will have used this model very often.
To add the Fody property notification stuff to our data classes, we simply have to make ONE change. Let's take the 'JobEntry' class as an example.
Before adding Fody:; } } } }
After adding Fody:
using System; using PropertyChanged; namespace EasyWpfWithFody.Models { [ImplementPropertyChanged] public class JobEntry { public string JobTitle { get; set; } public string ClientName { get; set; } public Double CostPerHour { get; set; } public int NumberOfHours { get; set; } public Double TotalCost { get { return CostPerHour*NumberOfHours; } } } }
Spot the difference? The addition is that line just before the class definition that looks like an array declaration. That's the aspect that Fody makes available, and the one that at compile time will ensure any additional code required to make your objects implement 'IPropertyNotification' is injected into them.
Go ahead; add the same line just before the class definition on your 'JobSheet' class, then run and test the app. You should see that when you now add a new entry, everything updates correctly. Now, wasn't that easy?
If you've been introduced to desktop programming under Windows using WPF and are one of the newer breed of developers out there, much of this article will be pretty meaningless to you. If, like me, however, you've been used to Win-Forms, and possibly even further back than that to the original WIn32 GDI model, this will hopefully make a lot more sense.
Old dev or new Dev, however, Fody in my mind shows just how simple this CAN BE. I Like Fody simply because I don't for one second believe that we have to have all the complexity that all these large frameworks have, which in many cases is simply complexity for the sake of complexity. A developer's job is to find the best, quickest, and most stable solution to a problem, and at this moment in time Fody ticks all those boxes.
I'll put a copy of the project from this article on my github page at:
for those who want to clone it, and develop WPF in a far simpler way than is the norm.
If you have a particular subject that you'd like to see covered, or an issue that's been chewing away at you, please do come and find me lurking around the interwebs. My Twitter handle is @shawty_ds and I can usually be pinged quite easily using that. Let me know your thoughts and ideas either there, or in the comments below this article. If I can accommodate your suggestions, I most certainly will.
How to use with vb.netPosted by Leon B on 05/04/2016 06:05am
This is very useful, I've tried to use it with vb.net but didn't manage to get the ball rolling. Always telling me that the [ImplementPropertyChanged] is invalid.Reply
questionPosted by mahmoud on 04/20/2016 03:52am
how to implement PropertyChanged the above code give me a fault in PropertyChangedReply
Good ArticlePosted by Vandana on 05/16/2015 02:32pm
Very helpful ....Reply
Total fields?Posted by fred on 12/29/2014 09:06am
hello, thanks for this. What does [ImplementPropertyChanged] is useful for in JobSheet class? I've tried by many way to update the TotalCostBeforeTax and TotalCostAfterTax values but no way. Am I missing something? Thanks for your answers.Reply
Nice ArticlePosted by Nagarajan on 12/04/2014 01:01am
Thanks for the article, Peter. It has thrown up a new avenue for WPF developers especially since Aspect Oriented Programming has been used in a way that can definitely reduce coding effort and minimize errors. I would definitely dig further into Fody and check it out. I could not find the code for the sample project in the link specified by you in github.
RE: Nice ArticlePosted by Peter Shaw on 12/23/2014 07:52am
oops my bad. i honestly thought i'd uploaded it. it's there now though, you can find it at shawtyReply | http://www.codeguru.com/columns/dotnet/simple-mvvm-in-wpf.html | CC-MAIN-2017-17 | en | refinedweb |
VisualBasicSettings Class
.NET Framework (current version)
Namespace: Microsoft.VisualBasic.Activities
Contains settings that VisualBasicValue<TResult> and VisualBasicReference<TResult> instances use to compile the source text of the expressions they contain.
Assembly: System.Activities (in System.Activities.dll)
System.Object
Microsoft.VisualBasic.Activities.VisualBasicSettings
Microsoft.VisualBasic.Activities.VisualBasicSettings
These settings include assembly references and imported namespaces required to compile an expression.
.NET Framework
Available since 4.0
Available since 4.0
Return to top
Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show: | https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.activities.visualbasicsettings.aspx | CC-MAIN-2017-17 | en | refinedweb |
gl_setscreenoffset - set a memory offset for copyscreen
#include <vgagl.h> void gl_setscreenoffset(int o);
Set the offset in pixels into video memory for copyscreen(3) and copyboxtocontext(3), copyboxfromcontext(3) and thus allows for page- flipping. Must be a multiple of the scanline width in bytes. It is reset to zero after the completion of copyscreen(3).
svgalib(7), vgagl(7), svgalib.conf(5), threedkit(7), testgl(1), gl_copyboxfromcontext(3), gl_copyboxtocontext(3), gl_copyscreen(3), gl_enablepageflipping. | http://huge-man-linux.net/man3/gl_setscreenoffset.html | CC-MAIN-2017-17 | en | refinedweb |
Hi, We have containers running without usernamespaces enabled. They have persistent volumes attached to them. After enabling usernamespace the containers and volumes will be under a different directory and old containers dont appear via docker ps as well. What can be the right way to bring the old containers back again with proper permisssions on volumes. Thanks Shashank
Advertising
-- You received this message because you are subscribed to the Google Groups "docker-dev" group. To unsubscribe from this group and stop receiving emails from it, send an email to docker-dev+unsubscr...@googlegroups.com. For more options, visit. | https://www.mail-archive.com/docker-dev@googlegroups.com/msg00219.html | CC-MAIN-2017-17 | en | refinedweb |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace PaulStovell.Samples.WpfValidation
{
/// <summary>
/// Interaction logic for SimpleWindow.xaml
/// </summary>
public partial class SimpleWindow : Window
{
public SimpleWindow()
{
InitializeComponent();
SimpleCustomer c = new SimpleCustomer();
c.Name = "Fred";
c.Address = "1/3 Powell Street";
this.DataContext = | http://www.codeproject.com/script/Articles/ViewDownloads.aspx?aid=15239&zep=WpfValidation%2FPaulStovell.Samples.WpfValidation%2FPaulStovell.Samples.WpfValidation%2FSimpleWindow.xaml.cs&rzp=%2FKB%2FWPF%2Fwpfvalidation%2F%2Fwpfvalidation.zip | CC-MAIN-2017-17 | en | refinedweb |
Question: If the price increases by 10 percent by how much
If the price increases by 10 percent, by how much does the quantity of household
(a) Natural gas and
(b) Electricity change in the short run and in the long run?
(a) Natural gas and
(b) Electricity change in the short run and in the long run?
Answer to relevant QuestionsSummarize the differences between tax financing and bond financing, and, thinking like an economist and not a politician, explain the circumstances wherein each means of financing is best suited.SoonerCo has $15 million of common stock outstanding, earnings before interest and taxes (EBIT) of $2.5 million per year, and $15 million of debt outstanding with a required return (interest rate) of 8%. The required rate of ...R&D Computer Corporation sells its product, which has a variable cost equal to $21 per unit, for $50 per unit. Fixed operating costs are $360,000. To support operations, the firm requires $1,000,000 in debt, which has a cost ...Customer service is often the key link between logistics and marketing within an organization. Define and discuss the Marketing/Logistics interface. What role does logistics play?Given the demand curve in the following graph, find and lable the monopolist's profit maximizing output and price?
Post your question | http://www.solutioninn.com/if-the-price-increases-by-10-percent-by-how-much | CC-MAIN-2017-17 | en | refinedweb |
> From: Stefan Monnier <address@hidden> > > For a single user, with an almost entirely "local" environment, > > implementing undo (even of commits) is quite practical, although a tad > > tedious. Arch needs to keep a more detailed track of the revision > > libraries it knows about, the mirrors, the timing of mirror updates, > > and the location of project trees. Matthew Dempsky has recently > > started working on this problem, although his time is very limited (he > > is a student) and so no particular rate of progress can be promised. > Sounds like a lot of work, with a lot of room for "errors" (i.e. things we > can only assume to hold even though they may not always do so). > And for very little benefit (in my case at least) since most/all my archives > are pretty quickly disseminated to revlibs and stuff on various machines. > I think we'll be better off following an approach similar to NNTP (where the > problem is also that once data is sent, you can't in general trace back all > the copies): create a new kind of changeset which modifies a previous one. Ick. Sorting out such a collection of changesets by hand seems horridly tedious and, operating globally (rather than in the special-case local form I advocate for above) in the arch namespace but extended with some kind of undo semantics sounds hopelessly intractible (what is to become of mirrors, for example? When can they safely be used in your Brave New World other than when an authoritative master server can be contacted?). > This way we can change the past (e.g. change the log message of an old > revision), and the info will be disseminated using the same mechanisms as > every other change: no need to keep track of mirrors, caches, revlibs, ... Build higher-level data structures atop the arch namespace if you want to do that. -t | http://lists.gnu.org/archive/html/gnu-arch-users/2004-10/msg00348.html | CC-MAIN-2017-17 | en | refinedweb |
UFDC Home myUFDC Home | Help <%BANNER%> The Jacksonville free press ( March 3, Table of Contents Main page 1 page 2 page 3 page 4 page 5 Main: Faith page 6 Main continued page 7 page 8 page 9 Main: Around Town page 10 Main continued page 11 page 12 Full Text Third Rail of Politics May Shock Most Blacks Page 4 I Mlr.[l. Salute 30 Life Lessons from Trailblazing African-American Women Page 10 Alabama Lawmakers Urge Black Athletes to Boycott Auburn MONTGOMERY, Ala. Lawmakers in the state's Black caucus are call- ing for a Black athletes' boycott of mostly white Auburn University until the school agrees to rehire two black administrators fired in a reorgani- zation of the athletic department. The caucus voted unanimously last week for the boycott Auburn President Ed Richardson maintains the restructuring \as not racially motivated. "We asked athletes to boycon Auburn until this issue is resolved because of the money going into Auburn from sports." said Democratic Rep. Laura Hall, caucus chairwoman. The roughly 30 caucus members met last week \ ith Richardson and asked him to rehire associate athletic director Stac\ DarJle and assistant athletic director Eugene Harris, even if the. had to be placed in positions outside the athletic department. Both were fired earlier this month as part of a department restructur- ing; a white assistant athletic director also was fired. Auburn is the largest unmersity in Alabama. with an enrollment of approximately 22,000, according to its Web site. Democratic state Rep. Alvin Holmes said the caucus does not expect athletes already at Auburn to leaxe. "We're just asking those being recruited not to come to Auburn." Holmes said. Texas Study Shows Minorities Get Searched More AUSTIN, Texas Two out of three Texas la\w enforcement agencies searched black and Hispanic drivers at higher rates than white motorists at traffic stops in 2003, according to a recently released racial profiling When searched, however, white motorists were at least as likely as blacks or Hispanics to be found with illegal items such as drugs or weapons, the report found. The data were compiled from information more than 1,000 Texas law enforcement departments were required to record under state law. Most of the agencies responded to public information requests for the stud,. The stud\'s recommendations include adopting uniform reporting stan- dards for racial profiling data; requiring extra data to be collected b,, police agencies: and establishing an independent state\ ide repository for reports. The report also recommended banning consent searches when an officer seeks a motonst's permission to do a search to look for illegal items, even if there is no probable cause. The study found three out of five Texas police agencies were more likely to ask blacks and Latinos than whites for a consent search. The report conducted by Ste\ard Research Group \was commissioned by the ACLU of Texas, NAACP Texas, the Texas Criminal Justice Coalition and the state chapter of the League of United Latin American Citizens. Trial Delayed in 1964 Civil Rights Students Killings PHILADELPHIA, Miss. The trial of a reputed Ku Klux Klansman in the 1964 slaying of three ci il rights workers as postponed Thursday to April 18, in part to give the defense time to review tips received as part of the reopened investigation. Edgar Ray Killen, an 80-N ear-old part-time preacher and former lum- ber mill operator, had been scheduled to go on trial March 28 in the killings of James Chaney, Michael Schwerner and Andrew Goodman, volunteers helping blacks register to \ore. Defense attorney Mitch Moran asked for time to look into information received via a tip line that was set up by a church organization after pros- ecutors reopened the case. Circuit Judge Marcus Gordon said the three-\week delax would also allow more time to prepare a questionnaire for prospective jurors. Black Farmers Seek Compensation From Government Thousands of black farmers who say they have been left out of a land- mark civil rights case are turning to Congress as their last hope to get compensation for years of being denied loans by the government. "This is not discrimination that took place in the 1950s. That discrim- ination is taking place right now, and it took place a few years ago for me. in 1996," said John Boyd, a Virginia farmer who is president of the National Black Farmers Association. "Congress needs to help us fix this."' In the 1999 case, the department agreed to pay S50.000 or more to each farmer who filed for compensation within six months. About 13,500 peo- ple have qualified for more than $830 million under tins settlement. But the Environmental Working Group and Boyd's association say as many as 66,000 black farmers missed out because they were improperly notified of the settlement, and thus, filed late claims. Lawyers for some of the farmers say they notified their clients, but the farmers didn't file for damages because they didn't believe the govern- ment would pay them. "We're not asking for any handouts. We're asking to be treated like you treat large white farms or corporate farms," Boyd said. "What happened to these black farmers was wrong. And the longer this issue festers, the worse it gets." r Oscars Historically End a - Month of History Page 11 50 Cents Volume 19 No. 6 Jacksonville, Florida March 3 9, 2005 Smiley Hosts Black State of the Union Mrs. Ella Simmons, who traced her DNA to a tribe in Atrica, holds a picture of her great great grandfather Chief Sehlabana of the BapediTribe in the Northern Province of South Africa. Weaving the Web of Our An intimate gathering of friends and acquaintances culminated the 5th Annual Weaving the Web of our History Black history celebration hosted by Ms. Carlottra Guyton. The annual gathering, held in his- toric Springfield, celebrated the legacies and attributes of local fam- ilies but most importantly the impact and relevance of Black History. "Everyone views Black history differently," says hostess Carlottra Guyton. Throughout the evening, each guest was given a total of ten min- utes to discuss a historical topic of their choice. While some chose to focus on different aspects of their upbringing or people in their fami- History ly, others discussed African visits. The idea came out of a discus- sion between her and a friend about going to all of the traditional Black history month programs.This year over forty participants assembled to share their vision. "We are so used to hearing about Frederick Douglass, Sojourner Truth, Harriet Tubman and others. Though they inspire us, they are not the ones who have the significant difference in our lives." Said Guyton. Thus the inspiration of the program. To some, that history is that which is in the encyclopedias, to others, it's the monuments and statues, but Continued on page 5 Tavis Smiley LITHONIA, Ga. Black leaders debated Saturday how to develop a checklist of political priorities that could be submitted to politicians seeking support from black voters. Tavis Smiley, the PBS late-night talk show host, asked about 40 lead- ers to consider whether a checklist could further the black American political agenda. He. "Black folk have always been the conscience of this country," Smiley said. "We are doing our part to help redeem the soul of America ... When we make black America bet- ter, we make all of America better." There was no consensus on how the contract would be used. More meet- ings will be held to develop the list, which could include as many as 10 priorities. Farrakhan said politicians and political parties could not be trusted to fulfill a contract. He said any checklist should be used to mobi- lize black Americans. "Power concedes nothing without a demand, but power won't even concede to a demand if it comes frorim a' weak constituency," Farrakhan said. Other panels at the symposium included former U.S. Surgeon General Dr. Joycelyn Elders, Princeton professor Cornel West, former Detroit mayor Dennis Wayne Archer and the Rev. Jesse Jackson. Links Explore Blaxploitation With Youth The Bold City Chapter of the Links, Incorporated took more than twenty-five band students from Darnell-Cookman Middle School to the Jacksonville Museum of Modern Art (JMOMA) in order to provide field and cinematography experience for youth. The activity focused on photographic and cine- matic visual arts. The participants were provided a special guided tour of the "Game Face" exhibit which focused on women and girls in sport. Additionally, the students viewed excerpts from a documen- tary on the "blaxploitation" film genre and given an opportunity to analyze the material presented as it relates to their modern day context. Their commentary was filmed and were presented in mini-documen- tary format at the opening of the 2nd Annual Black on Black Film Series offered by JMOMA. Ritz Concludes Griot Festival Dick Gregory Visits UNF Campus Author, actor and civil rights activist Dick Gregory (seated, center) takes a moment before his speech at the annual Martin Luther King Scholarship Luncheon at the University of North Florida to pose with this year's schol- arship recipients. They are (standing, from left) Harold Briscoe Jr., and Osiel Torres, (sitting, from left) Marissa Saladeen, and Derek Frazier. (L-R) Madafayo Lloyf Wilson Storyteller/Musician, Museum Director Carol J. Alexander, Valerie Tutson, Storyteller, and Awodesu Abayomi Musician, joined together to conclude the Ritz's Griot's Festival. Three day event explored many diverse varieties of African-American storytelling and featured a different genre each night.. FMPowell PHOTO A i r I III I Africa Hosts First Miss HIV Pageant Page 5 -I I a. 2 I Iy3r 'IcA IrM2 Boost Your Credit Score in Three Days So-called "rapid rescorers" claim to raise your credit score in just a few days, helping you to qualify for a better mortgage rate. You may hear about these new credit reporting agencies when you are applying for a loan. If you do, consider yourself lucky. These are not shady opera- tions like many of the heavily adver- tised "credit repair" outfits. Rapid rescorers will quickly fix errors and omissions on your credit report, resulting in potentially huge savings on mortgage payments, as well as on payments for credit cards and any other loans you take out down the road. You can always make fixes on your own, of course, but the arduous process normally takes four to six weeks or longer. The Real Deal More than 100 credit-reporting agencies act as middlemen between mortgage lenders and the major credit bureaus. When you apply for a mortgage, your mortgage lender will have a credit agency pull and com- bine your credit reports from the major credit bureaus. If you have written documentation from your creditor and collections, judgments, or high balances listed in the report have, in fact, already been paid, your mortgage lender can have the credit agency expedite the correction proc- ess. An Arizona mortgage broker who used rapid rescoring for the first time in mid-December said that his client had a credit score of 729-one point shy of the score needed to se- Scholarships Available for Collegiate Entrepreneurial Program The Black Business Professionals and Entrepreneurs, a global network of business owners and professionals committed to creating opportuni- ties for existing and emerging companies, has announced the launch of its Collegiate Entrepreneurs Series (CES) program. The program provides entrepreneurship training, development and mentorship for high-achieving students ages 18-24 currently enrolled in an accredited college or university. The CES program will be facilitated from June 22-25, 2005 at Savannah State University. Savannah, Geor- gia. Interested students can request to participate in the program as well as apply for admission through the George and Diane Yarbrough Schol- arship Fund. Scholarship applications are currently being accepted through March 15, 2005. The scholarship will cover a student's housing, meals and pro- gram tuition. Upon successful graduation from the program, students are placed in a mentorship program and provided with complimentary ac- cess to the national Black Business Professionals and Entrepreneurs Conference. Students will gain knowledge from real-life business models and they will be placed in groups that are given business challenges to complete prior to graduation. Organizers say one of the major goals of the pro- gram is to help students understand the importance of gaining on-the-job experience that will also help sharpen their skills prior to starting a busi- ness. Scholarship recipients will be announced in April. Applications are available via the web at: Questions about the program may be directed to: ces@blackbusinessprofessionals.com or b) contacting the program of- fices at: (912) 354-7400. mn oI.t tm0 cure a 5.8 per- cent mortgage rate. Two errors lowered the score: His credit report incor- rectly listed a tax lien that had already been paid, and large credit-card pay- Tax Q&A ^ ments were not recorded. Once proof of the lower balances and satisfied lien was submitted and his reports were updated, his credit score rose by 3 points. The result: His monthly mort- gage payments dropped by an im- pressive $101 a month. The $200 cost of correcting and reissuing the credit reports and scores was picked up by the mortgage broker. The Bottom Line If you are applying for a mort- gage, be sure to request a free copy of your credit report and score from your lender. (Ideally, you should order credit reports from the three bureaus a few months before apply- ing for a mortgage.) And if you see errors ask your lender if it works with a credit agency that offers paid rescoring. There are no guarantees that your score will go up, and your lender may not even have heard of these agencies because they're so new. But it's worth a try. Unfortunately, the service is not available directly to consumers. You can only work with a credit agency through your lender. "Rapid rescor- ing was designed primarily for modi- fying inaccurately reported informa- tion in a consumer's credit file when that consumer was in the middle of a loan application and needed quick assistance in getting new scores," explains Ginny Ferguson, who heads up the National Association of Mort- gage Brokers Credit Score Commit- tee. And that's too bad for consum- Q. I already sent in my return but I realize now that I didn't claim all of the deductions that I'm entitled to. Is it too late to do anything about it? A. No, you have up to three years from the date you filed the original return or two years after the date you paid the tax (whichever is later) to file an amended return. So you can still amend your returns for 2001 (until April 15), 2002, 2003, and 2004. Use Form 1040X. Q. My husband and I filed a joint return for 2003 but have since learned that our total tax bill would have been lower if we had filed separately. Can we file amended returns? A. Unfortunately, one you file jointly, your union as a couple is irreversible in the eyes of the IRS, at least for that tax year. You can file separately in succeeding years, however, and even go back and forth from year to year. Curiously, if you had originally filed separate returns, you could amend to a joint return. Q. I don't understand many of the forms that I've received from my banks and brokerages. Should I simply put them in a shopping bag and let my tax pre- parer sort them out? A. If your preparer's fee is based on the time he spends work- ing on your return, he may be happy to wade through your shop- ping bag and figure out what is relevant. If you want to keep the bill within reason, however, you should try to do that job yourself. S your preparer t "a will need: W- S2 wage state- c Sments and r t of there a. 1099s reflect- o I sury- I ing interest, V I- .-al Intdividends, and other pay- ments. If you haven't moved your accounts, it may help to check the payers listed on your 2003 return to make sure you haven't missed any- thing. Q. I mailed my January 2005 f mortgage payment to the bank in c late December. Since the bank didn't process the check before year-end, it is not reflected on the Form 1098 interest statement for 2004. Can I deduct the interest portion of that check on my 2004 return? A. You are entitled to deduct expenses in the year paid. For this purpose, an item is paid when you mail the check. Line 10 of Schedule A (Form 1040) should reflect the interest reported by the bank on Form 1098. The additional interest should be claimed on line 11, de- scribing it as "additional interest paid to Bank, but not included on Form 1098." Remember: Unless you prepay again at the end of 2005, you'll only be entitled to de- duct 11 months of interest on your 2005 return (even though the 1098 for 2005 will reflect 12 months' worth). Q. My bank no longer returns canceled checks to me. Without them, how can I prove my deduc- tions, such as contributions, or even that I paid my IRS bill? A. A new federal law known as "Check 21" permits banks cut the paperwork and handle checks elec- tronically. Instead of physically moving checks from one bank to another, the bank where the check is deposited can take a picture of ansogin=i "Copyrighted Material "Copyrighted Material Syndicated Content Available from Commercial News Providers" * 0 a e.- 4m- a --40 - ~ a Ducote Federal Credit Union acksonville's OOldes African-American Credit Union, Chartered938 Current and Retired k I- Duval County School Employees, and Family Members .... Are Eligible to Join - New & Used Auto Loans Personal Loans Consolidation Loans Draft/Checking Savings Payroll Deduction Direct Deposit I 2212 N. Myrtle Avenue -Jacksonville, FL 32209 Phone (9041354-0874 4%-. Chamber of - S rti Commerce March 3-9, 2005 PazeP 2 Mrs. Perrv's Free Press he front and back of the check and ransmit it electronically to your )ank. Legally, an electronically created "image replacement docu- nent" (IRD) is the same as the original canceled check. While a canceled check or IRD s generally accepted as proof that you made a payment, it doesn't necessarily establish that the pay- nent was for the purpose claimed. For example, a check written to a doctor may represent a deductible or nondeductible medical expense for a person who is not a depend- ent. To back up your claims, you should keep bills, receipts, and other documents. In addition, spe- cific records are required for certain items, such as business travel and contributions over $250. Q. If the IRS is going to audit my return, how soon am I likely to receive notification? A. Selection of returns for audit doesn't begin until the filing season is over. So it's unlikely you'd be notified before the end of this year. The IRS generally has up to 36 months from the time you file to determine if. you owe additional taxes. Q. I understand that there is a child tax credit of $1,000 for chil- dren under 17. My wife and I have two preteens at home, but the software program I used to prepare our taxes computed a credit of only $1,700. Have I done something wrong, or is there an error in the program? A. Probably neither. The credit is $1,000 per child, but the total is reduced by $50 for each $1,000 of income above $110,000 for couples filing jointly. You didn't indicate what your income is, but we sus- pect that your adjusted gross in- come (line 36 of your 1040 return) is between $115,000 and $116,000. If it is, your tax credit would have been reduced by $300. .m qu Q-dm MxcI U00 x 3 PaUP AT&T Retirement Mother Hazel M. Williams Ross Party Held For Retired Educator Succumbs Shown above is Patricia Pearson, Maxine Engram, Martha Hemphill, Jean Downing and Longineu Par- sons with Priscilla Williamson. RSilver PHOTO We, Salute The Ribault 10! Text and Photo by Rhonda Silver JACKSONVILLE Prior to the 1954 U. S. Supreme court decision "Brown vs. Board of Education", across America, there were two different worlds: one white, one black; but even in the white world there were black water fountains, black restrooms, and separate entrances and facilities at: lunch counters in Woolworths, movie theaters (Blacks were usually designated to the balconies), and of course, the back of bus. The Supreme Court decision forced the two races together for the first time. But in Jacksonville, Florida, the decision went relatively unnoticed. It was twelve (12) years after "Brown vs. Board of Education" that ten (10) Black students would stand at the entrance of the all-white Ribault Senior High School. These courageous students took steps to effect change in a massive way. They were the pioneers who enrolled, attended, and suffered the consequences to graduate while blazing the trail for integration, despite racial tensions. These twelve students don't look forward to Class Reunions. Remembering the daily. hurts and knowing full well,.the hurts would be repeated the next day, was very difficult. The Ribault 10 stayed the course, and for they deserve thanks. We honor our own today, and rightly so. They created change, they paved the way. The Ribault 10 believed they were doing something for the betterment of their race, and country. We can't erase the past, but we can look to the future with bright hope. Because of the suffering and sacrifice, thee ten students endured, there is a great freedom that students in Jacksonville enjoy. saw ad Ie WeN Iat %% Seam "Copyrighted Material Syndicated Content Available from Commercial News Providers" Sandra Sablon Text and Photo by Rhonda Silver To look at Sandra Sablon, she hardly seems ready for retirement, but after 30 long years at AT&T, she says she is ready for retirement. She was commended at AT&T for serving with dependability, courte- sy, leadership and love. The retirement Celebration was hosted at the Potter's House Christian Fellowship Multiplex, Saturday, February 26, 2005. Co-workers, friends and family gathered to celebrate Sandra's retirement. The Master of Cerem- ony, Elder Coleman expressed that he was honored when asked to. preside. Long-time friend and co- worker (also retired) Laura Fench of Atlanta, GA., sang with fervor, "It's Your Time." Remark after remark allowed me to learn of a woman who with faithfulness, encouragement and excellence, will be missed by these whose lives she continues to touch. There will be new dreams for her to dream, and new mountains for her to climb. Orchid Show The Jacksonville Orchid Society, whose sole purpose is to encourage the study, appreciation and growing of orchids, both species and hybrids will have their annual show on March 19-20, 2005 at the Garden Club of Jacksonville, 1005 Riverside Ave. r!oanar~a ;!5a~ion Hazel Marion Williams- Ross made her transition into life eternal on February 26, 2005 at her home with her family. Mother Ross, was born June 2, 1912 to the late Rev. F.W. Williams, Sr and Mrs. Emma Berry Williams, in Starke, Florida. Upon the untimely death of her father, she helped her mother to raise her brothers and sisters. From an early age, she was very passionate about education. In fact she would "hitch" rides on a pulpwood truck to Jacksonville so that she could complete her high school studies. She was a graduate of the Edward Waters College High School Department. She then went on to continue her education by earning degrees at Florida Memorial College (then in St. Augustine) and graduate work at Florida Agricultural & Mechanical University. Always one to help those in need, Mother Ross began her teaching career in Fargo, Georgia. At that time "colored" teachers were only paid twenty-five dollars per week. While there the local church served as the school but because of her vision and insight she rallied the community and helped to build the first school in that town. She could be seen daily after school on ladders working right beside everyone else. She accepted the Lord into her heart at an early age. Anyone who knew her, knew that she was willing to tell you about the goodness of God. She joined Shiloh Metropolitan Baptist Church after moving to Jacksonville and in recent years was in prayer accord with Alexander Temple Community Church. She met a man who forever captured her heart, Jackson C. Ross, Jr. They were united in matrimony. Jackson preceded her in transition. She always said that when he passed on so did all men in her eyes. Her teaching career blossomed. From teacher to principal to every job in between, Mother Ross loved teaching and helping people. After forty-seven years of educating Lake Park Homeowners Meeting March 17th The Lake Park Homeowners' will meet at 6:30 p.m. on March 17th (Thursday) in the Community Room of the Bradham Brooks NW Library, on West Edgewood Ave. April, May, June and July will be Neighborhood Beautification month. An officer of the Sheriffs Department will speak on safety in Zone V. Information: 765-3728. B(ackPahjqes9US S Division ofThomas-McCantsMedia, Inc. "CELEBRATE BLACK HISTORY MONTH EVERYDAY" Pick up a copy of the Jacksonville First Coast Black Pages at the following locations: AAATROPHY MART 6936 Beach Blvd. 725-8686 ATTORNEY CHARGE J. GILLETTE, JR. 603 NorthMarketStreet 358-1304 BLACK PAGES USA 101 Century 21 Drive, Suite 120 727-7451 DUCASSE CHIROPRACTIC 4204 Baymeadows Road 737-9334 EXCLUSIVE MEN'S WEAR 1403-16 Dun Avenue 757-3066 FIRST COAST AFRICAN AMERICA CHAMBER 1817-A Myrtle Avenue 358-9090 IMAGINE LTIS HAIR DESIGNS 5949 A- Macy Avenue 745-5422 JACKSONVILLE BEAUTY INSTrITOE 5045 Soutel Drive, Suite #80 768-9001 JACKSONVILLE CHAMBER OF COMMERCE 3 Independent Drive 366-6600 JACKSONVMlUE PUBUC UBRARY 122 North Main Street 630-2416 JAMES E. DANIELS REALTY, INC. 1954 Southside Blvd. 720-5696 JOSLYN AVANN, DS - FAMILY, COSMETIC & SPA DENTISTRY 2166 CassatAvenue 384-5700 LAW OFFICES OFGRAYULNG E BRANNON, PA 1536 N. Jefferson Street 358-9151 LAW OFFICES OF REGINALDESBTL JR, PA 505 N. Uerty Street 225-5735 PEDIATRIC SMILES, INC. 2622 Dunn Avenue,Suite 4 751-5126 REALTY OPTIONS/MORtIAGE OPTIONS 1909 N.3rd Street 242-0202 ROBIN K. ROBERTS, ATTORNEY AT LAW 625W. Union Street Suite 2 355-6002 SIMMONS & JOYNER PEDIATRICS. 1711 Edgewood Avenue, Suite 1 S766-1106 SOUTH. DENTAL CENTE 5475 Soutel Drive 904-764-4576 SOUTEL DENTAL CENTER 3539 N. University Blvd. Gazebo Shopping Center 904-745-0243 SUNTRUST 200W.FosythStreet 632-2536 *Check Your Local Church 101 CENTURY 21 DRIVE, SUITE 120 JACKSONVILLE, FL 32216 (904) 727-7451 (800) 419-2417 MARK[ YOUR CA! l] V:I=LENDlA.R: March 10th-12th Charleston, SC (6th Annual) May 19th -21st ' Columbia, SC (8th Annual) August 19Th-20Th Norfolk, VA (1st Annual) October 6th- 8Th Florida Black Expo (4th Annual) TBA Wilmington,NC (9th Annual) blackexpousa.com Mayor's Neighborhood Matching Grants Program To continue the City of Jacksonville's efforts to improve neighborhoods, the Neighborhoods Department announces the opening of the 2005-2006 Mayor's Neighborhood Matching Grants Program. Funding is expected to be $308,800 for next year. However, the amount is subject Services Division, 1 17 W. Duval St., Suite 3 10-A, City Hall at St. James. Proposals will be accepted until May 31, 2005, no later than 5 p.m..or postmarked by 5 p.m. WORKSHOPS ARE MANDATORY! Matching Grants Pre-application Workshops are scheduled for the following Thursdays March 17, 6:30-7:30 p.m. March 24, 10:30-11:30 a.m. April 21,6:30-7:30 p.m. April 28, 10:30-11:30 a.m. All training workshops will be held at: City Hall at St. James, 117 W. Duval St., Renaissance Room (Lobby) Workshops will include an overview of the application process, project eligibility and assistance with application preparation. Please remember: No applications for fiscal year 2005-2006 will be accepted without a representative of the organization attending one of the technical assistance workshops. Call the Neighborhood Services Division at (904) 630-7398 to reserve a seat at the workshop of your choice. John Peyton, Mayor Roslyn Mixon-Phillips, Director Neighborhoods Department Blo byBlock. March 3-9. 2005 Ms. Perrv's Free Press Page 3 Hazel Marion Williams Ross students she retired from the Duval County Public School System in 1988. One of her most stellar accomplishments was that she has traveled the entire continental United States learning African- American historical facts about each state that she visited. She was also very involved politically as precinct committee woman for District 9L. She was preceded in transition by sisters, Alberta Watkins, Annie Mae Allison, brothers Leon Williams, Sr. and Fred Williams, Jr. She leaves to carry on her legacy, a devoted daughter and grandson who took care of her until the last, Ida Ross- Johnson and Rahman K. Johnson, Jacksonville, FL. Daughter Peggy Celestine Ross- Williams (Andrew), Pompano Beach, FL; grandson Marty Phontanza Ross and one great- grandchild Marteshia T. Ross both of Pompano Beach, FL. Brothers Sidney Williams, Sr. (Christine) Starke, FL; Samuel D. Hughes, Bronx, NY; and a host of nieces, nephews, cousins, students and loving friends. Ritz Chamber Players Performance The Ritz Chamber Players, the nation's only all African-American Chamber Music Society, presents "A New Day," Spring Concert 2005 on March 19, 2005 at 8:00 p.m. at the Terry, Theater,, K Pae4-Ms er' Fre Prs MarhII9,00 BlacKoffee H o + St r o Sober1"nsq by Charles Griggs THIRD RAIL OF POLITICS MAY SHOCK BLACKS MOST LIVE FROM CITY HALL by Jacksonville City Councilman Reginald Fullwood EWC's Accreditation Issue a Crisis for the Community "Father Time is not always a hard parent, and, into play when though he tarries for none of his children, often lays his age. This, rep6 hand lightly upon those who have used him well; mak- tem that would Sing them old men and women inexorably enough, but In other w leaving their hearts and spirits young and in full Even for thosi vigour With such people the grey head is but the share all of the impression of the old fellow's hand in giving them his The probl blessing, and every wrinkle but a notch in the quiet cal- it doesn't addr endar of a well-spent life." ulation. Especi -Charles Dickens Under the There is a huge and interesting debate brewing in Security blacks America right now. First of It has seemed to worm its way near the top of the Americans is hearts and minds of Americans all over the country. ethnic groups. For the moment, I'm not talking about the ongo- plan they would ing war in Iraq. Which in itself has is the cause of And, chan much concern among Americans. run investment Today, for reasons that are obvious to many, the everyone will t Bush administration has decided to pull a Social ease. It'll be a Security reform rabbit out of their hat. all over again. Social Security is known as the "third rail" of No one is politics. Meaning that it has always been too danger- problems. In f ous to handle. government ru With the president feeling the pressure of the war fixed, or else... in Iraq, many feel as if he has not paid enough atten- issue of this m tion to domestic issues. essary homewc Critics have said that Bush, because of his per- a true remedy 1 sistence with war and foreign policy, has teken his The presi eyes off the economic ball on American soil. In doing Security drawir so, he has left the economy exposed to weaknesses story of who re, that hurt lower and middle class Americans on the There he will I economic home front. have nowhere e Now in his second term, Bush has struggled to of the financial build the confidence of Americans in this area. His In promote policies have been beneficial only to those who need indicated that financial help the least. worry about an With that being said, many view the president's If that's tl efforts at Social Security reform as a smoke screen to seem to be raise help mask the realities of the war in Iraq. If that's th A key part of the Bush proposal to reform Social eye squarely or Security is for Americans invest their money in mouse for the I "Private'Accounts" set up by the government. The At this stag viability of these accounts would depend heavily on es to be heard: the success and failure of Wall Street and the econo- American lifest my of which it depends on for survival. equation of refi At present the Social Security system depends on It is impo Sp'ay-ins by an already existing work force in order to "third rail" effe satisfy the obligations of those who are currently receiving benefits. You can send The problem with survival of the system comes . Troub lead qW quo 44. 00-a ,. Q 00 ommu 0 41w a 41 *1o-f l 40 a I__a. -"Copyrighted Material Syndicated Content __ Available from Commercial News Providers" UNN 0, .. e. t 040 . sop b am 0 m-m W f, 0--0110 4. a. O -w -.000.41M. t -- 4 .- 4W. .qopp aw- 41 -a.-010. 01- massas,. M. M. .t -- wo If 0.1% -4-100-____a - 40 ft --Row- "No. a 5 a - 41001- G~_ - -% oo- ma-m a. .0 -00 GO a. ___ - 40. _- 1- w . s*M-00 me a 0*OW -w -WW Q- mW-- -- - .0 ft ft. -maw -a. a serge of baby boomers hit retirement irtedly, would cause a drain on the sys- I send it into bankruptcy. 'ords, not enough money for everyone. e who have diligently paid their fair ;ir working life. em with the president's proposal is that ess the actualities of the American pop- all African Americans. e president's proposal to fix Social s would suffer at the end of the road. all, the life expectancy for African shorter than that of whites and other Many blacks would be paying into a d never benefit from. ces are that dealing with a government plan doesn't seem like something that be able to maneuver with the greatest of like learning how to file income taxes denying that Social Security has its act, you could single out almost any n program and say "this needs to be ." However, to begin the debate on an magnitude without doing all of the nec- ork indicates a lack of sincerity to find for. the problem.' dent should go back to the Social ng board and dig a little deeper in the ally benefits from the program and why. find a segment of people who literally lse to go. This "third rail" is the conduit dignity for which they survive. ing his plan to save the system, Bush people over the age of 50 need not ly effects caused by his reforms. he case, why are they the ones who ing the most concerns? e case, then that puts the reform bulls- n the back of my generation as the test president's legacy experiment. ge of the game, it is important for voic- It is important the realities of African :yles and experiences be counted in the orm. rtant that President Bush realize the 'cts some more than others. us an e-mail with your comment to: griggorama@aol.com. DcI" SIW a .- - a. -* * by Malcolm Moore 1 recently learned about an African-American male who died of lupus at the age of 40. He is survived by a wife and four children with the youngest only two years old. Although the cause of his death is somewhat rare, the story in its essence is quite common. African-American men often die young. According to a 2003 report from the Centers for Disease Control, the average African- American male can now expect to live 68.6 years. This is generally attributed to the poor quality of health in African-American communities along with poor lifestyle decisions. It is also common knowledge that married persons generally survive longer, so the African-American community's relatively low marriage rate doesn't help. This is all relevant to the debate. As argued by Representative Bill Thomas (R- CA), it makes good sense to consider race and sex when assessing what Social Security has to offer. Financial planners are first to advise devel- oping an investment portfolio tailor-made to indi- vidual needs. When given the opportunity, work- ers individualize retirement portfolios. Why should Social Security be any different? Think about it. One presently cannot fully ac- Black are more likely to suffer from the inadequacies of Social Security reform. Martin Luther King, Jr. once said that when America gets a cold, the black community gets the flu. Let's take that concept and look at Jack- sonville's African American com- munity. There are certain institutions in Jacksonville that are critical to blacks in this city and I believe that Edward Waters College is at the top of that totem pole.-So when EWC is hurting so is the African American community. Although the college is no stranger to pain and challenges, this most recent hurdle may be to high to overcome. The historically black college learned late Friday afternoon that it had lost an appeal to keep its ac- creditation. Most of us are in shock, because of the broad ranging sup- port the school has received from not only black leaders, but also the Mayor, Governor and business lead- ers from around the state. There are several distinct publics that are affected by this decision. Most obvious are the students. Be- cause only accredited colleges may receive federal, financial aid, chances are that an overwhelming majority of the schools current stu- dents will either have to transfer or quit school all together because of the cost of tuition. In fact, more than 90%of Edward Waters' students rely on federal aid to pay for their education. The other major student-related fall out is that a historically black school must be accredited to be a member in the United Negro College Fund, a key founder of scholarships. Student athletes will also be af- fected. The NAIA rules ban unac- credited schools from all postseason tournaments and playoffs, and dis- qualifies the teams record. Typi- cally, small colleges like EWC use a dlom - a -a - a- '5 a cess what has been paid into Social Security until age 65. That means that, on average, African- American males enjoy only 3.6 years of payback for decades of paying into the system. This is why African-Americans alike should favor a privatization of Social Security and the establishment of personal saving accounts. Furthermore, African-Americans should want reforms that go far beyond the current debate. First, African-Americans should want Social Security reform that includes provisions that limit the cost of investing. Social Security reform should not be a license for investment companies to steal from the cookie jar owned by working- class African-Americans. As the cost of computer technology continues to cheapen, personal invest- ment should be organized so that investors can monitor and alter their portfolios at will and at a very low cost. Second, African-Americans should want a pro- vision that allows the use of these personal sav- ings to become homeowners. If increasing Afri- can Americans homeownership is a national goal. it seems only reasonable to permit investors to use their savings to purchase a home. This provision which allows people to essen- tially borrow from'themselves rather than be be- mixture of financial aid and scholar- ships to pay for many of their stu- dent athlete's tuition and housing. If the school is not accredited athletes would lose their financial aid, and the undoubtedly look towards trans- ferring to another institution. Last week I talked about how important EWC is to the neighbor- hoods surrounding the college, but let's look at how important it is to the black economy in Jacksonville. I don't have the exact figures, but it would be easy to argue that the col- lege is a major employer of African Americans in Jacksonville with be- tween 100 to 150 staff members according on the number of students are at the school at any given time. As enrollment drops, so does the need for teachers, administrative support and even maintenance per- sonnel. So we could be potentially looking at dozens of people out of a job. Currently, African Americans have the highest unemployment rate of all races at 11 percent, which basically is double the national rate of 5.2 percent, according to the Bu- reau of Labor Statistics. The unemployment rate in Jack- sonville mirrors the national average at a little more than 5 percent. But again, the black unemployment rate in the city is doubled. These stats are important because if institutions like EWC, that em- ploy a fairly large number of blacks, have to close their doors or make significant jobs cuts it will have a ripple effect in the African Ameri- can community. At issue here are the loss of jobs, the training-and education of stu- dents that is needed to receive qual- ity jobs and the economic impact the college has had on the local community. EWC has been a key catalyst for - a- holden to a lender is available in most retire- ment savings plans today. Homeownership has historically provided a very good rate of return. Owned property is an excellent source of income in the form of reverse mortgages or simply their resale value. Such a provision is not yet part of the current debate. Claims and counterclaims about the fairness of Social Security for selected demographic groups - particularly African-American males continue to be disconcerting. Numerous articles on this topic exist, but most are based on microsimula- tions and not actual Social Security data. Not until this issue is put to rest can a true de- bate begin on reforming the Social Security to best benefit African-Americans. To end the controversy, African-Americans should be calling on the Social Security Admini- stration to produce comprehensive and corrobo- rated studies that provide a definitive answer to the question, "How do different demographic groups fair under the current Social Security sys- tem?" If it cannot provide such studies, it should tell us why not. IN JACKSONVILLE FREE PRESS OiFDLBhIAflfI I'lMIlffYlAKWEfgYfiEWSPMPEB MAILING ADDRESS PHYSICAL ADDRESS TELEPHONE (904) 634-1993 P. O. BOX 43580 903 Edgewood Ave. West FAX (904) 765-3803 EMAIL: JFreePress(aaol.com WEBSITE: JFreePress.com Rita E. Perry, Publisher ,T change in Jacksonville's black com- munity and more particularly in the New Town and College Gardens neighborhoods, which borders the school's campus. As the institution has rejuvenated itself over the past several years, so have the neighbor- hoods. With the city investing $13 mil- lion into a new joint-use gymnasium and music center, not to mention the hundreds of thousands in additional funds the city, state and federal gov- ernments have given to the school, Jacksonville has a vested interested in assuring, that EWC's accredita- tion is reinstated. When I ran for office six years ago, economic development, spe- cifically jobs, was one of the most important issues to the African American community. Today, the same lack of job opportunities prob- lem exist, and when a dozens of people become jobless at one time, it only worsens the situation. With the Southern Association of Colleges and Schools now denying EWC's appeal, the battle moves to federal court, where the schools main argument will be that its due- process rights were violated. Hopefully, the federal courts will show more mercy than the SACS. It is often hard for academics like the ones that sit on the governing body for the SACS, to look beyond the educational functions of a college and realize the impact these institu- tions can have on a community. I can only imagine the ripple ef- fect a final negative decision on accreditation will have on the black community .At this point, we are as Cornell West once said, "Prisoners of hope." Signing off from the EWC/City construction site on Kings Road, Reggie Fullwood -t 0 - - a. t -W '0-. 410 . African-Americans Deserve More from Social Security Page 4 Ms. Perry's Free Press March 3-9, 2005 Mrs. Perry's Free Press Page 5 Researchers Explore Southern Slave Site 1, 1 )'Mo i 'l4 I Shown above are participants listening intently to Pat Nelms describe growing up in Jamaica and the im- pact of Jamaican independence on the country's citizens. In the bottom photos are hostess Carlotta Guy- ton with guests Phyllis Pratt and Derya Williams. Three year veteran Evelyn Young. FMPowell PHOTO Weaving the Web of Our History to others in attendance, it was the impact of the own family's history too. The invitation read: Black History Month will Soon come to a close All throughout the month, Programs have been done, Our stories being told But before the books are put away, And the last spiritzial has been sang, Join us in celebrating The history bur own families have began. Guests were asked on their invita- tion to bring a small artifact from their family digest and a covered dish. "If you didn't have a picture, a great story is fine." Said Guyton. A highlight of the evening was Ms. Ella Simmons who delighted te attendees with a picture of her great, great, great grandfather.. Mrs. Simmons has been one of the few African-Americans taking advan- tage of today's technology and had her DNA traced back to its exact tribe in South Africa. Last summer, she made the trip to the motherland and met her relatives. "It came back that I was de- scended from royalty," said Sim- mons. Eleanor .Hughes, who had also been to Africa, continued her seg- ment with insights on her visit to Kenya. She encouraged everyone in attendance to try and at least make one trip to Africa. She also sug- gested that potential travelers try to travel with school programs. E.B. Johnson commented on the strength of the African people and .the..qourage .,of.sla.ves who.,endured the middle Passage, "When I think about what they went through and survived, it brings me great pride." He said. Other highlights of the evening included poetic readings and memo- ries of the civil rights movement and integration. According to the hostess, some people are afraid that they don't have enough to share. "But if they have a memory that makes them smile, a punishment that made them remember, .well then they have a legacy to share." She said. Following the sharing of rich fam- ily lore and memories, guests feasted on a buffet of potluck favor- ites ranging from jerk chicken and jambalaya to sweet corn bread, col- lard greens and crab pie. Itr -? f."W OSSABAW ISLAND, Ga. Sift- ing through dirt from the floor of a small cabin made from oyster shells and sand, archaeologist Dan Elliott is finding unexpected treasures. He unearthed a doll-sized porce- lain plate, clay marbles, lead shot and a French-made gunflint fasci- nating finds from a cabin that once housed plantation slaves. "We're dealing with the facts. These are all things they left be- hind," says Elliott, noting that toys and firearms' material "could sug- gest their masters were letting them have a little bit of latitude." Researchers say three cabins made of tabby a cement mixture of 1 oyster shells, lime and sand on this I undeveloped, state-owned barrier island are among the best-preserved slave quarters in the South. Now, 142 years after slavery ended, the Georgia Department of Natural Resources and the nonprofit Ossabaw Island Foundation are con- ducting the first archaeological digs here, hoping artifacts buried beneath the cabins will yield a better picture of how Southern slaves lived in the 18th and 19th centuries. "It is easily one of the most im- portant African-American slave sites in the Southeast," said Dave Crass, Georgia's state archaeologist. "Normally it's a big, white- columned plantation house that's still there. And the people who made the place work, their houses are long gone." Since most records on slaves were kept by their owners, "you're seeing their world through white eyes," Crass said. "You need archaeology to put a face on these very abstract ideas about what slave life was like." Ossabaw Island remains one of coastal Georgia's wildest places: Hogs, deer, armadillos and Sicilian donkeys roam the island's 11,800. acres of wishbone-shaped uplands among towering live oaks and In- dian burial mounds. Roads criss- crossing the island are all dirt. There is no bridge to the mainland. The first slaves arrived in the 1760s, when Jim Morel bought the island and established North End plantation to harvest live oaks for shipbuilding timber and to grow indigo and other cash crops. .... WllUA ,i*M I.. VA040, Researchers believe Morel had about 100 slaves. More came later to work three ad- ditional planta- tions his sons established on the island, which is about 6 miles from Savannah. The island had no clay suitable for making bricks, and they were Every bit of dirt at the site has to be carefully sifted expensive to ship, through. so slaves con- structed their homes using oyster shells plentifully piled in trash heaps left by Indians. Elliott, the lead archaeologist for a $1.3 million study, has located bur- ied tabby foundations indicating 18 slave cabins once stood at North End. Only three survived intact, built 32-by-16 feet and divided into two living quarters sharing a chim- ney and hearth in the center wall. Architectural conservator George Fore, hired to assess the cabins' con- dition and origins, found that the original wooden ceiling boards had marks from a circular saw, indicat- ing the cabins were likely built after 1840 when the first steam-powered saws became available. SOriginal window sashes in one cabin suggest it had glass windows, another unusual touch for a slave house. -. ".We don't have that many planta- mij b tion slave quarters that are fully intact like that," Fore said. "All three of these have their internal plaster intact. Nails are in the walls where they obviously hung various things, clothes to dry. It gives you a personal touch with that time." Elliott has unearthed even more personal relics, many dating to the 18th century a sign slaves may have built their tabby quarters on top of older housing. The finds in- clude a small lice comb of carved bone and shards of an Indian pottery called Colono-ware rare in Geor- gia. Bones from fish, birds, pigs and alligators hint at what slaves may have eaten. Ironically, the three slave cabins survived not because they were left alone, but because they continued to be used as living quarters until the 1990s by staff of the state and the island's last private owners. Africa Hosts Miss HIV Pageant GABORONE There is a cat- walk ard esti- mated third of the population in- fected. The government is using its min- eral wealth to provide life prolong- 1L~ I Thirty two-year-old HIV positive Cynthia Leshomo (R) hugs her doc- tor after winning the. 'Miss HIV Stigma Free' competition in Gabo- rone, Botswana. The competition aims to reduce the stigma attached to HIV/AIDS, which has infected roughly a third of the southern Afri- can country's population. ing anti-retroviral drugs -- but many do not know their HIV status or are unwilling to come forward for treat- ment. pag- eant,." FEELIN G L U K Y? C A LL C SI O S E E- Atlantic City's STrump Plaza On the Boardwalk $199 - SRoom, Air, Transfers, Luggage Handling on a chartered 757 passenger Jet. Monthly Weekend Trips $ Next trip March 11- 13 Fri-Sun 91-800-553-7773 .17 ..kno.r:Ikow- ... .. ...... .. ...... a u I i- WNNV. i;. ~ INEID WzD.. a. wag 5f a ar a r lU ii ii ut L ill. YffvuhhuummhuuuuuE noMun ummumuss %vital% xxxxxxx 1- r L 'VF,1,,IPuIEuIII I WEI 910 59 NI NIIEI II IallI II uu uum .T m- -- .-- ---- U -- -- -- -- -- -- -- -mu.. owl, rwiiiiiuiiwSCS~rnrnrnliiiiiiunurnwi ON V , ~-'--~ -- ~;-----=---~. -~-----:Y= '~=-~------~..:;---- -~---- L-=~--~ SCA MR Y Keep sharp. Keep smart. Keep evolving. With the Camry XLE3.3 liter V-6 enq'n- eIadher-lrimmed ,ririor power moonrooF JBL 6-diSc audio system with optional ioucn-screen DVD Nraviiqdion Svyem and nealed front eats The resf ,S up to you toyota.com .. .; % L U." W ". "" '' "" ; "" k .-. ' pa /J / ,.Ma rh o-, 2nn00 I1(C1~L LI-/) rvvv I I I ,"- -H; VP I I Shown above outside one of three cabins on Ossabaw Island, Ga., researchers say are the most important slave sites in the southeast. Researchers say the cabins of tabby, a cement mixture of oyster shells, lime and sand, are among the best-preserved slave quarters in the South. i.. -mm n m i COGIC Bishop Writes Powerful New Book "The New Slavemasters" Published by Life Journey Books Cook Communications Ministries ISBN O-78144-D60-2 Bishop George D. McKinney is bishop over the St. Stephen Church of God in Christ (COGIC), in San Diego, California. The bishop holds numerous academic degrees in sociology and theology. He is a magna cum laude graduate of Arkansas State College, Oberlin College School of Theology, and the California School Theology, in Glendale, California. He has received an Honorary Doctorate in Divinity form Geneva College in Beaver Falls, Pennsylvia He and his late wife, Jean, are the parents of five adult sons: George A., Grant, Gregory, Gordan, and Glenn McKinney. The Presiding Bishop of the international body of the Church of God in Christ, Bishop Gilbert E. Patterson says that "Bishop George McKinney has hit the mark once again, and this masterful and inspired work should be read by every parent and teacher. The Bishop further describes the book as "a strategy for victory". "The perpetrator today is one more insidious but no less destructive than history evidences; the new slavemaster is the evil that has imbedded itself in the African American culture as well as our broader culture," Bishop McKinney says. "This evil takes the form of teen pregnancy, domestic violence, adult' anrd -child'' 'pornography, illegal drug use, and gangs. Its evil permeates the behavior of men and women through the diseases of anger, rage, and irresponsibility. Stanford University Dean of the Beeson Divinity School, Dr. Tim- othy George says that Bishop McKinney has written a fascinating book that speaks to one of the most urgent needs in our society today, "the strengthening of African American families". He further stated that "Bishop McKinney, one of America's most sensitive and influential pastoral leaders, has written from the cauldron of personal experience. And, that this book will inspire, encourage, and provoke." Bishop McKinney has power- fully identified through, the meta- phor of slavery the new slave- masters of our culture. Shiloh Metropolitan To Present Evening Of Women in Praise The Music Ministry of .Shiloh Metropolitan Baptist Church, 1118 West Beaver Street, Darrell L. Gilyard Sr., Pastor; will present "Women in-Praise" at 5 p.m. on Sunday, March 13, 2005. Director of Music and Arts, Roger D. Sears, plans an anointed evening of Gospel Music. Evangel- ist Tarra Conner Jones, Ms. Amy Hall, Mrs. Keecia King, Mrs. Karen Winston Rozier and Mrs. Henrietta Telfair will be among the anointed women of God to be presented in "Women in Praise". The public is invited. A Famity That Prays Together, Stays Together. Wbr"hip' at the Church of Your Choice With Your Family. The new slavemasters are societal predators with one goal: destruct- tion. The destruction of both an individual, and the destruction of the family." Bishop McKinney writes from a soul of conviction and a mind filled with wisdom, He speaks the words that we must not only listen to but also practice. We must tell others, and we must educate our own minds, praying that our lives will be tools of healing and power. This is a clarion call to the African American community, as well as, to our society in general. Evil is no respecter of race or gender. It is time to break the imprisonment of one's mind and spirit, and to embrace the warrior strength that Our God has securedfor us. The Bishop boldly reveals the subtle and powerful migration of man-imposed slavery in America to' self-imposed slavery- the destruct- tive evils such as violence, materialism, promiscuity, drugs and instant gratification. These are The New Slavemasters. In the cultural debate that often shuffles blame for society's evils from race to race, Bishop McKin- ney presents an illuminating, mes- sage that dares to place blame where it truly belongs, at the root of all evil. He dares to boldly point to God and the community of faith as the lonely logical hope for true restoration and freedom from today's evils. Be sure and check out the Religious Section of your favorite bookstore, to find BishoptMcKin-.: ney's new book; or visit an African American-owned bookstore, such as Neferiti's on Lem Turner Road, between 1-95 North & Edgewood. Rev.Gene White & Ribault Choir to Sing at Sisters Network Benefit The Sisters Network Northeast Florida will present a Gospel Bene- fit Musical at 6 p.m. on Sunday, March 6, 2005. This benefit will be held at the Grace Baptist Church of East Springfield, 1553 East 21st St., Rev. John J. Devoe Jr., Pastor. Appearing on program will be the Nu-Testaments, the Miracles, the New Creations, Jerry Cannon & The Caravans, and Soloist Pastor Stephanie White. Special appearances of Rev. Eugene White & the Ribault Senior High School Chorus; and Soloist Brother Brandon Jones, of the Douglas Anderson School of the Arts. Donations will be accepted for the work' of the Sisters Network Northeast Florida. The public is cordially invited to enjoy the spirit of this evening of Gospel Music. Saint Thomas Missionary Baptist Lent Worship The St. Thomas Missionary Baptist Church, 5863 Moncreif Road, where Ernie L. Murray Sr. is Pastor; will hold Lent Worship Service each Wednesday night at 7 p.m. The Lord's Supper will be administered. You are invited to come, bring your Prayer Requests, and expect a Miracle. Pastor Murray will deliver the Spoken Word each Wednesday. Friends, and the public are invited to attend all services. Shown above is Rosemary Washington, Rev. Dotson, Rev. McKissick Jr. receiving an award from Deacon Scott as Mrs. Kimberly McKissick looks on.. RSilverPHOTO BBIC Celebrates 90 Anniversary of Pastor Rudolph NcKlssick Jr. By Rhonda Silver The sky was a mist with tears of joy as the Bethel Baptist Institutional Church recognized nine glorious years of excellence and pastoral leadership by Rev. Rudolph W. McKissick Jr. A full day of worship and celebration honoring God's Choice for His House called Bethel, on February 27, 2005. What looked like a dreary day was transformed into a powerful day of praise. A mighty man of God, Rev. McKissick Jr., a prophet and vis- Sionary, spoke of Spiritual Reforma- tion and awakening. "A new day dawning," he said. "A reformation is coming. A Spiritual reformation that will release gifts of the Spirit in this place to do greater things for the Kingdom." With the theme: "9th Annual God's Choice Award," Rev. Mc- Kissick Jr. was nominated, and won "Best Animation," "Best Mus- ic Video," "Best Executive Produ- cer," and "Best Dramatic Testimo- ny." BBIC's 1st Lady Kimberly Joy McKissick- was nominated for and won, "Best Leading Lady; while their children won, "Best Suppor- ting Cast." Preaching both the 7:45 and 10:45 services, Pastor Craig Oliver of Elizabeth Baptist Church in Atlanta, GA, graced the pulpit with fervor. Under his leadership thousands have been led to Christ at his home church, and he didn't let no rainy day, water down his anointing. Now for the finale! Pastor Ernie Murray of St. Thorpms,M-issionaryp Baptist Church, Jacksonville, open- Cont. on Page 7. I p.m. Wednesday.S:00 p.m. Dinner and Bible Study at 6:30p) 'It'll7 _! U -A A 1 I.AA ---- fXT- "- '7 1 Pastor Ernie L. Murray, Sr. weanesaay iz:uu noon (Noon uay) MA"* GREATER MACEDONIA BAPTIST CHURCH 3Pasto40r -y-nlmd L3A. VWilTsinrca S, 33r Mlxim .- 1880 WestEdgeiood Avenue Jacksonville, Florida 32208 "Seeking thelost oar web site at / E-mail GreaterMac@aol.com LISTEN FOR OUR RADIO BROADCAST EACH SUNDAY 2-3 PM ON WCGL 1360 AM Evangel Temple Assembly of God It's Time To Visit With Us! Exciting Children and Youth Ministries. SPreaching Hope and Faith to Fulfill God's Destiny. Sunday Services March 6, 2005 8:25 a.m. & 10:45 a.m. & 6:00 p.m. Jesus Still Heals the Sick Today. Have Faith in God. S Something Good is Going to Happen to You. -l - J&mmectnin4 Sunday- March 13th 5755 Ramona Blvd. Jacksonville, FL 32205 904-781-9393 ...... --- --- -W-M Page 6 Ms. Perry's Free Press March 3-9, 2005 - .6 r_i~~~QJ~ .. .. 2 .. ... Ebenezer UMC Celebrates Black History Month PICTURED (left to right, top row) Ms. Lettie Hood, Juliette and Clarence Fields, Ms. Betty Emanuel; Ebenezer Benita Harrison, who directed the Children's Moment and Ms. Monya Sharpe who recited a special reading which United Methodist Church's Pastor, Reverend and Mrs. Newton (Derya) Williams. Second Row: The Ken inspired all. Reddicks, Ms. Evelyn Galvin and M,. Velma Grant, Johnny and Ceciley Davis, Ms. Delores Ashley, and Ms. Mrs. Alma Green read the Scriptures from the Old Testament (Joshua 4:19), and from the New Testament Christine Dobson. Third row: Mr. and Mrs. Green, Ms. Maxine O'Neal and guest, Ms. Demita Hamilton and son, (Mathew 7:24-29), which was followed by the Song of Preparation, Jesus Christ is the- Way. and Ms. Minnie Reed. Mrs. Gertrude Peele, the guest speaker, used .he theme Remembering Our Pastand Celebrating4Our Future;A The program 'egan onSunday' Morning, February 20, 2005 with the processional hymn, Kum Ba Yah, My which stimulated the mind and the heart an"conciluded with he )Organ Postlude, Make Us One, with Mr. James Lord, and was followed by the Call to Worship where many more inspirational hymns were sung including Lift Lanier, musician. Every Voice and Sing, and We Shall Overcome. The congregation gathered in the church's Fellowship Hall for a Soul Feast which included over thirty entrees, Several members of the congregation contributed to this special program: Mr. William Reed gave the as well as, desserts. Inovcation and Mr. Zebedee Shoemaker led the Psalter. Dr. Lorenzo led the selection Seek Ye the Lord. Sister -.1 Rabia Court No. 25 to Present .-'O A Gospel Celebration 2005 The Rabia Court No. 25 March- its kind in Region 3, which consists units compete ing Units, Daughters of Isis, will of the states of Alabama, Mississ- units from across host their first annual gospel ippi, Georgia, Florida and South This first concert, entitled ."A Gospel Carolina. The hard work,. dedica- Celebration" is I Celebration 2005" featuring the tion, effort and talent of this unit the public. You a Rescue of Love Choir, composed was displayed in its debut perfor- out and enjoy of the Emphasis and Breath of Life mance at the Desert of Florida state evening. Seventh Day Adventist Churches, convention's 2002 Gala Day where Pastor Claude Matthews is Celebration in West Palm Beach. director. The concert is set for 6 The Rabia Court No. 25 March- Shelwoo p.m. on Sunday, March 20, 2005, at ing Unit consists of women who PlaradlS Pi the Simpson United Methodist take pride in their tireless and Church, 1114 Cleveland Street, relentless pursuit in establishing a Let Your Vi corer New Kings Rd, across from drill legacy. the U S Post Office. Rev. Moses The Award Winning Rabia Don't miss Johnson is Pastor. Court No. 25 Color Guard took let your voice *The Rabia Court No. 25 March- first place at the 2002 & 2003, 2nd what's happen ing Units is in its fourth season as Place in the 2004 Imperial Drill munity. Make the first and only marching unit of Competition at the Daughter of Isis be present and Bethel cont. Baptist Church, Jacksonville, open- ed our hearts with the profound question, "Art thou the Christ, or shall we look for another?" From Matthew 11:2-3. John The Baptist was in jail, awaiting execution. He heard how Jesus had gone to Galilee teaching and preaching, and he sent his disciples to ask: Art thou the Christ, or shall we look for another?" John .was in jail for preaching. Preaching got him in trouble, even unto death. He was perplexed as to why Jesus (know- ing his situation) would go to Galilee. Christ is the same yesterday, today.and tomorrow. When John's disciples found Jesus, and ques- tioned him as John instructed, he simply told them to "Go back and report to John what you hear and see. The blind shall receive sight, the lame will walk, those who have leprosy will be cured, the deaf will hear, the dead are raised, and the good news is preached to the poor. Blessed is the man who does not fall away on, account of me." A reception was held immedi- ately following the worship experience, where well wishers,' ministries and members made presentations. Imperial Court Sessions in Wash- ington, DC, Philadelphia, and Atlanta, respectively. The Imperial Session is the national convention of the organization where marching p.m., Thursday at Rutledge H. tary, 4346 R your communi think counts! I against other drill the country. annual "Gospel FREE and open to ire invited to come the spirit of the id Forest & irk Residents voice be Heard the opportunity to be heard about ring in our corn- it your business -to be counted at.6:30 y, March 10, 2005 . Pearson Elemen- oanoke Blvd. Its ty too! What you Be there! How can U help keep a kidoffdrugs? The ih a little of your SOcan make alfeUme ofdiference. Y ei. I First Baptist Church 89 St. Francis Street St. Augustine, FL (904) 824-6590 SUNDAY SCHOOL 9:30 A.M. DISCIPLESHIP HOUR 9:30 A.M. MORNING WORSHIP SUNDAY 11:00 A.M. "MIRACLE MONDAY" YOUTH AND ADULT BIBLE STUDY 6:30 P.M. FELLOWSHIP DINNER MONDAY NIGHT 7:45 P.M. March 3-9, 2005 Ms. Perry's Free Press -'Page II( Par R- Mr Tlrp~ rpQ arh -9 20 Essence Bestselling Author Kayla Perrin's Pens "The Delta Sisters" The Next Hiv/AIDS Victim Could Be You! GET TESTED, YOU MIGHT BE SA VING YOUR LIFE KAYLA PERR.IN FLiielnce bc.mlmi ii a-ithor 'of The Siiers of 7T;::i IPu 1\ai;' eel t-col,~ f3~ha3 This Essence best-selling author of the Year list, two times. has penned fifteen novels. She has Kayla Perrin's first foray into received an Arts Acclaim Award mainstream fiction came with The for her writing from the city of Sisters of Theta Phi Kappa. In "The Brampton, Ontario; and won a spot Delta Sisters, she sensitively on the Romance Writers of explores the relationships between America's Top Ten Favorite Books mothers and daughters with insight 'into the power of love and the meanings of family. She delivers a gripping story about three genera- tions of African American women, their deepest secrets and their most cherished lies. The best-selling author's book, The Delta Sisters centers around the Grayson family, one of the pillars of New Orleans' African American community. The book reveals that the family matriarch, Sylvia Grayson, has deep secrets that she has hidden while creating and maintaining the proper image relative to her prominent stature in the community. Sylvia Grayson keeps a tight rein on her daughter Olivia to carry out the perfectly mapped out life she had reserved for her. Olivia's life is to include going to college, joining the Delta Sorority, and marrying the proper young man. In 1975, on a summer day, the town's "bad girl" is found murder- ed. This event causes Sylvia Grayson to pull her daughter Olivia into an even 'tighter circle. But,' eventually her tight control shatters the ties between the mother and daughter. SYears later, Olivia's own daughter Rachelle is trying to make her way into the world. A killer is watching in the shadows, deter- mineed that the secrets of the past will not come to light. The Delta Sisters is a spell-binding, intimate portrait of what happens when these passionate women have to join together at least in the face of danger. Look for this exciting and mys- terious novel in your favorite bookstore. We recommend Neferi- ti's, located on .Lem Turner Road between I-95N & West Edgewood. Applications Are Now Being for Future Grants Grantto Mental Counseling and Nurse, Expand Clara White Mission's Services JACKSONVILLE The Blue the activity and officially establish- mission's efforts to meet the needs Foundation for a Health\ Florida. ed her "mission work" as an agency of the underserved. Blue Cross and Blue Shield of in 1904. The two women gained The Blue foundation n will pre- Florida's (BCBSF) philanthropic the respect and love of both black sent grants totaling $532,112 this affiliate, recently awarded the Clara and white citizens for their untiring winter to nonprofit health clinics White Mission a two-year grant of efforts to meet the need of the poor. and community outreach programs $45,450 to help fund a full-time In 1928, eight years after across Florida. The Foundation mental health counselor, and apart- Clara's White's death, the Clara supports programs that increase time nurse practitioner. White Mission was established by access to quality health-related "This gift represents the her daughter, as a memorial to her services for the uninsured and uh- continued support we see from the mother. Inspired by the.dedication derserved. Annually the Founda- business community as we carry and love her mother had for other tion awards up to $1 million in out the charge left to us by Clara people, Eartha M. M. White used .grants during two grant cycles. and her daughter, Eartha," said her skills as a businesswoman, The deadline to submit applica- Ju'Coby Pittman, CEO and presi- educator and philanthropist to serve tions for the next grant cycle is dent of the mission. "These funds humanity until her death. Her March 18, 2005. For an application will allow us to assist deserving efforts live on through the Please call 1(800) 4773736, ext. clients who come to us for help .preservation and expansion of the 63215. The. spirt of the Clara White Mission began in the late 19th S - century when. Clara White indiscriminately served free hot Family Service Specialist--Youth position soup from her back door to the Applicant must possess college credits in pursuit of a Sociology or hungry and homeless in our city. Psychology degree, or related fields with a minimum of four years ex- Clara White was a former slave perience in Social Service or an acceptable combination of education who had worked as a stewardess and experience; must have computer skills and knowledge of various aboard luxury steamships that software and their 'operation. Apply in person at: 421 W. Church St. cruised the St. Johns River at the Suite 705, Jacksonville, FL 32202 or fax resume to: (904) 791-9299 close of the 19"t century. Attn: Human Resources Dept. Clara White's Daughter, Eartha Salary Range: $16,864--$24,915 Mary Magalene White, expanded .. \ . According to the CDC, the highest rates of sexually trans- mitted diseases (STDs) are those for African Americans. The CDC notes that the presence of certain STDs can increase one's chances of contracting HIV by 3 to 5. Nearly 1 in 4 African Americans lives-in poverty. Studies have found an association between higher AIDS incidence and lower income. Minority populations are dispro- portionately affected by the HIV epidemic. To reduce further the incidence of HIV, CDC's initiative, Advancing HIV Prevention can be found at partners/AHP.htm. Many teenagers are at risk for HIV and other,. STD infection Because adolescence is a time of sexual exploration and risk taking, often with multiple partners. Alarming rates of STDs indicate that teens engage in behaviors that put them at risk for HIV, as well as unintended pregnancy. Any young teen mother, or teen that is pregnant must realize .that the. incident that caused her to become pregnant could also cause her to become HIV/AIDS infected. Abstinence is the only answer. Unprotected sex is taking a risk or your life no matter whether you are a teen or you're 50 years old. For teens, unprotected sex is no accomplishment, it's a risk. Surprisingly, the rates for teen pregnancy began rising at the height of the AIDS epidemic, and is no longer a moral 'issue, but a risky health issue, that could even become a death sentence, if infec- ion with HIV/AIDS is transmitted. Based on current trends, an average of two young people are infected with HIV every hour of the day. One in 4 new HIV infections-in people under the age of 22. One half of all new HIV infections occur in people under the age of25. AIDS is the 6th leading cause of death among 15-to-25-year olds. Heterosexual sex accounts for 75 percent of reported cases in young women 20 to 24 years old. America's STD rates are among the highest in the developed world and as the HIV epidemic moves well into its third decade, hundreds of thousands of people have died from AIDS, mostly 20 to 24 year. olds. New treatment of AIDS has overshadowed the fact that the epidemic continues and that the rate of AIDS reported among young Americans continues to escalate. In young people,more than any other group, HIV is spread sexually More young people are having sex in their teens than ever. CET TESTED, AND YOU MAY SAVE Y OU LIFE! We, African Americans have been at the top of the news, as we enter the month of March 2005. The good headliners are that the incomparable Morgan Freeman, at last won an academy award. He had previously been nominated no less than three times. He won as.the Supporting Actor in Million Dollar Baby. Better still young, black and beautiful (well handsome), talented Jamie Fox won the big one as Best Actor in his portrayal of the late Ray Charles in Ray. It was his second nomination, both this year. That was the good news, even if USA Today sort of ignored the success of Jamie Fox, they wrote a great story on Morgan Freeman. The Bad and Sad News is that the latest statistics released on the Hiv/AIDS crisis is that the virus has risen in the African American community by fifty (50) percent. Get tested! When the drama of the AIDS Virus first begin to play in the early 1980s, all appearance was that it was a disease than only male gay person was subjected to. How that has changed! In the year 2005, many new revelations have been made, one of the most adverse is that African American men may not only be sometime unfaithful, but that many are also bi-sexual, and that is a major cause of the virus being transmitted to women. Of course, prostitution and illegal drug use can also contribute to the transmission of HIV/AIDS to many- women, African American or of other racial characteristics. My good friend, Dr. Maude Lofton, a Jacksonville native, told me in the early ,1980s that the HIV/AIDS virus can harbor in one's system for sometimes as long as fourteen (14) years before it does become active. I've never forgotten that, and neither should you. GET TESTED! Dr. Lofton.also told me, and now it is common, but often ignored data, that when you have sex with anyone, you are also having sex with everyone that he or she has ever had sex with. GET TESTED! The fact that the HIV/AIDS virus can incubate in one's system for such a long period is devastate- ing. Many persons have changed their live styles when facts about the HIV/AIDS virus have become known. But, the incubation period is still reason to get tested. If, you are tested, and find that you have harbored the virus, there is a chance that through medications that have been developed, your life can be saved. 'No matter your previous lifestyle, no matter, your present lifestyle, no matter your gender, no matter whether you are ! The next HIIV/AlUS Victim Could Be You! single or now married, remember the facts, and GET TESTED! Last, but not least, remember that the HIV/AIDS virus has infected persons of all genders, all races, all walks of life, the poor, the rich, the "low lifes", the famous, and some of the last persons on earth that you would think could ever become infected. Keep in mind that you, me, and hardly anyone that you may come in contact with, knows someone that has been infected with the virus; it may be a neighbor, a church member, family member, or a friend, or just someone that you have come across. That's how prevalent the virus has run rapport in our communities. Keep in mind always, even if you've been monogamous all of: your life, many persons harbor secrets, and you may not be your partner's only partner, and you're also having sex with everyone that he/she has ever had sex with. God bless, and please GET TESTED! -Rita Carter Perry In Jacksonville, you can get tested FREE, so take advantage of this opportunity that could save your life. FREE testing is offered by River Region. FCBBIC Seminar . Series to Present, Personal Financial Planning Seminar First Coast Black Business Investment Corporation (FCBBIC) will present a workshop entitled "Personal Financial Planning at 6p.m., Tuesday, March 8, 2005; at the Ben Durham Business Center, 2933 North Myrtle Ave., Suite 100. For most small business owners their business is their most valuable asset. This workshop will identify strategies that you might use to. determine the value of this asset and use it to help secure the financial future of you and your family. To register, or for information, call (904) 634-0543 or visit website. Simmons and Joyner Pediatrics Charles E. Simmons, ZII, Dr. Reginald Sykes welcomes Dr. Tonya Hollinger to the practice. WE PROVIDE TREATMENT FOR: *Hypertension * Elevated cholesterol *Obesity. March 3-9,,2005 Pape 8 Mrs. Perrv's Free~P Press .1UAe Q 2005 ss wc3MIEaow NsSl 111 l w M0N cIxAx. 30 Life Lessons from Female Trailblazers "If you are inter- ested in politics, learn about govern- ment first. The two are often confused, and without .some understanding of both, it becomes very easy to be misled by 'personality.'" Carol Moseley-Braun, first Black woman elected to the Sen- most people made was that after a certain age they stopped having adventures. We considered that a num- ber of our friends already seemed to be settling into routines. Now that I'm 50, I understand how easy it is to settle in. But I also know how much more fulfilling satisfying and fun it is to keep pushing yourself to see and do and be more, emotion- ate k ally, politically, spiritually--to con- "When I was in kin- tinue to engage the world and the dergarten, the teacher people around you, to plan and exe- asked members of the cute adventures meant to challenge class what we wanted your ideas of who you are and what to be when we gre\u up. ou are capable of doing." When it was my turn, I said I Pearl Cleage, best-selling au- wanted to be a scientist. She replied, thor, cultural critic, feminist 'Don't you mean a nurse?' I under- "My last defense/Is the present stand that she was trying to be help- tense." ful by steering me, a young Black Gwendolyn Brooks, poet girl growing up in the sixties, to an "Sometimes what your body attainable career objective. But I needs and what your soul needs are was indignant and stubborn and I two different things." said, 'No, I mean a scientist.' I Sister Souljah, activist, novelist, learned very early not to limit my- lecturer self because of others' limited "With your friends, you can imagination." experience life's possibilities--who Mae Jemison, NASA's first you may become. Your family will Black female astronaut teach you who you are." "Never give up on Rosa Parks, activist, legend yourself, no matter what .'2 "Philippians 4:13 says, 'I can do the obstacles may be. all things through Christ who Always know that God strengthens me.' I've learned that has more in store for you. someone else's no can be my yes. Always hold on to your faith, which For every door that's closed, there's is your strength and ultimately your another one waiting to be opened. solution. There's an inner Cynthia Cooper, 2X MVP Most spirit guiding me Valuable Player, Houston Comets every step of the "There's an old saying: It is way. If I can just difficult to free fools from take the time to lis- the chains they revere. I've ten to it and be true learned to pay no attention to it, the right peo- to the naysayers of this pie, the right places and the right world--the people who delight in circumstances will all come into my sitting on the sidelines and telling life when I'm ready for them." you that you can't do something. I've Dr. Suzan Johnson Cook, pas- found that it's important to follow tor; president, New York Coali- your own path. Life, when navi- tion of 100 Black Women gated with a positive spirit, a sense "I believe the key ingredient to of passion and commitment, can be success in one's life is quite simple: a tremendously rewarding journey.". Be yourself. Be au- Sylvia Rhone, chairman and thentic. Reflect your CEO, Elektra Entertainment %values and share your "On my friend Karen's fortieth unique God-given birthday, we were having drinks. gifts with all those Karen said shethought the mistake u encounter in life." Ann Fudge, executive vice- president, Kraft Foods, Inc.; president, Maxwell "Know that you are as blessed as you want to be. Bless yourself and your life each morning and all through the day. Say it: 'I am blessed.' Then walk in the assurance that you, your family, your loved ones, your projects, your relation- ships, your goals and dreams are blessed. Truly believing that you are blessed dispels fears, doubts and confusion--the enemies of a full life. Refuse to be pulled into other peo- ple's issues. Instead, be determined to walk in your own blessings." Tina McElroy Ansa, author, filmmaker "My motto is: Stay low, stay humble and keep moving. When I set goals, I focus on God instead of my surroundings. Surroundings can distract. God sees me through." Brandy, 21-year-old singer, actress "Great heights reached and kept by men were not attained through sudden flights, but those, men, while their. . friends were sleeping, toiled through the night." Mpule Kwelagobe, 1999 Miss Universe, Botswana "One of the hardest things about living in a society that regularly rejects or insults your humanity is figuring out a way to stay open to. others, to share who you are without second thoughts, paranoia and feat. This is not easy; it can feel as though you are asking to be hurt over and over. But the alternatives are actually more hurtful. To not share. To be like someone else. To stay scared to death of rejection. Being true to yourself and staying open in the face of pain are lessons I work on all the time." Tricia Rose, author, cultural critic, professor UNF Seeking Outstanding Teachers The UNF College of Education campaigns are prohibited and may dence of consistent excellent per- and Human Services is accepting eliminate a candidate. formance as a classroom teacher. nominations and applications for The Roddenberry Awards consist Those who wish to pursuegraduate two major teaching awards -- the of five graduate fellowships of degrees must meet the requirements Gladys Prior Awards for Career $3,500 each. The fellowships will for admission to the graduate pro- Teaching Excellence and the support credit and non-credit gram. Applications must be made Gladys Roddenberry Gradu- directly by teachers seeking ate Fellowships for Teaching the fellowships. The dead- Excellence. r line for applications is April "Saying yes is really wonderful. Yes opens up an opportunity to do something. No al- lows you to sit back i- and be scared, lonely and self-righteous. Yes means that you have to keep trying \ -- to find a way to make something happen." Nikki Giovanni, poet, professor, cultural activist "I believe fundamentally that all problems have a resolution. We all have the creative genius--left to us by generations of African-American women--to transcend and transform our circumstances and propel our- selves to greater heights. It is this gift from our foremothers, the im- perative of vision and faith that has brought me through, nurtured and given me the strength to work for new paradigms for justice. I am guided in life by the vision of the world of equality that should exist." Barbara R. Arnwine, executive director, Lawyers' Committee for Civil Rights Under Law . "For me, as the first Black person to own a mainstream modeling agency, accuracy of performance was absolutely necessary. That need for accuracy gave me the drive to get it right, so no one could point a finger and say 'She's just not to- gether.'" Bethann Hardison, president, Bethann Management Co., Inc. "A few years ago I took up gar- dening. It's a hobby I wish for eve- ryone because it contains a host of great lessons. It renews our belief in tomorrow. It rewards patience. It humbles us in the capriciousness of nature. And it reminds us that life rarely thrives without a measure of shit." Gloria Naylor, award-winning novelist, educator "The 1960's Civil Rights Move- ment :is historic because we did win much of what we fought for in laws that outlawed seg- regation and dis- crimination. Often, . 0," - -, '. . I I; however, what I have fought for has been small and personal--to defeat a bad habit, for example. Sometimes the fight has been for a large public goal, such as complete self- government and full congressional representation for the people of the. District of Columbia. Whether in- personal or political circumstances, a safe .calculation of the odds of winning can keep you from fighting. There is no complete victory on earth. Progress always brings new problems. The movement taught me that the good life is spent in strug- gle. You can't win what you don't fight for." Eleanor Holmes Norton, con-. gresswoman (D-D.C.) "I did what a many mothers do. I honored my son's evolving manhood. Not so easy with my daughters' wom- anhood. The day I decided to talk to my daughters as the adults they are instead of the children they were was the day I finally opened my eyes to their re- splendent womanhood. Indeed, I saw four self-defining women and they saw.me in themselves." Camille O. Cosby, philanthro- pist, businesswoman, educator "Do unto others as you would hate them do Sunto you. We Share all living in God's grace, and b he all have an obligation to n 'dance' in that light."Judith Jamison, artistic director Alvin Ailey American Dance Theater" My life song has been a challenge to thestatus quo. I believe that rules are meant to 'be broken, and risks are there to be taken. But when I get so far out on a limb that I'm about to fall, I remem- ber the advice I receive from Grand- mother Rose: A hard head makes a soft behind." Julianne Malveaux, economist, author, TV and radio personality I I r'' i - ap '- "Bloom where you are planted. When you do S your best where you are, your excellence will be noticed. This ak N work is the foun- dation of a solid career and good reputation." Alexis Herman, former U.S. Secretary of Labor" Be gentle to and forgiving of yourself and others. Life is too short and far too precious to be angry and spiteful. Meanness will destroy your spirit. Each day is unique and offers a lesson, so learn to treasure each one for the gift that it is." Valerie Wilson Wesley, author "I made a mess of my life, .person- ally and profes- sionally. I made countless mistakes and hurt lots of people. Even though God gra- ciously forgave me and others for- gave me, too, I was unable to for- give others or myself. I was bound in a self-imposed prison of anger and regret, hopelessly held hostage by my depression. Today I am no longer the victim of my circum- stances. Whether by the hands of others or my very own, I'm finally free from the past. My philosophy? Let others off the hook! Get yourself off the cross! And take your life off the hold button!" Jennifer Holliday, singer, ac- tress" Life, when fully lived, is about lessons. I have found that life is richest when it centers on learning, on exploring the unknown, and re- discovering what is working and what is not working well in our world. I find the ways I can contrib- ute, in some small measure, to mak- ing it a better world. I learn the most about myself as I come to under- stand and respect those who are different from me. And the most profound lesson of all flows from discovering who I am in relationship to my Mother/Father God." Dr.'Johnnetta B. Cole ;o i ~ .-> i b The Prior Awards consist of four annual awards of $12,000 each to honor and reward career teachers who have demonstrated "sustained teaching excel- - lence and inspiration of stu- i dents." The award is open to public or private school teachers in Duval County ' schools and who have taught at least i'O years. Anyone may nominate a teacher for these awards-students, former students, parents, colleagues or administra- tors. No special nomination form is required. Send a letter describing ways this teacher inspires students and the skills and strategies of their teaching excellence. The deadline is April 8. Self-nomination and courses at UNF. The criteria are current employment as a full-time classroom teacher in a public or private school in Duval County; a minimum of three and a maximum of 10 years of full-time teaching experience; demonstrated and docu- mented commitment to professional growth in K-12 education; and.evi-- berry, who taught sixth grade. This is the eighth year of the program. For more information, please contact the Dean's Office, College of Education and Human Services, University of North Florida, 4567 St. Johns Bluff Road, S., Jackson- ville, FL 32224; phone: (904) 620- 2520; fax: (904) 620-2522.. Georgia Carrots 1-lb. bag Russet Potatoes 5~lb. bag Technology Eases African-American Search for Roots Although African Americans face more challenges than almost any other ethnic group when it comes to tracing their roots, online records can make the discovery of family history easier than ever before. My- Family.com, the most popular and comprehensive' family history re- search and connection resource online, offers the following tips to make the search a bit easier: Sketch your family tree based entirely n .memory Even if it's full of question marks, a rough draft will tell you what you'll need to research in the coming months. Gather the records you have on hand and compare them with your outline. Birth certificates, marriage licenses, and death records can pro- vide much of the information you' are missing Search for U.S. Federal Census - For many African Americans, the paper trail begins with the 1870 Census. This is the first U.S. Cen- sus'that listed former slaves as citi- zens and may also include the last- known residences of their earliest free ancestors. Another great re- source is the Census Free Popula- insights into slave folklore, poetry, tion Schedules. These schedules list songs, recipes and even ghost sto- the names of African American ries. The entire Slave Narrative citizens living in the northern free collection is available online states prior to the Emancipation through MyFamily.com Proclamation of 1 863. Share and Preserve - Glancing at a census record. Show off your handiwork can reveal information like through a tangible heir- an ancestor's occupation, loom to pass on to chil- annual income and home dren and grandchildren. ownership. Census records are Consider creating a Web site available online at Ances- through MyFamily.com to try.com. conveniently share your, Read slave narraties family tree, pictures and Journals and slave narratives documents with family are among the most e\oca- members. tive of genealogical re- "For African Ameri- sources for African cans, piecing together fam- Americans. Now that ily history can present some these texts are available unique challenges," said online, researchers can Tom Stockham, president easily search for and CEO of MyFam- specific names and ... ily.com. "Fortunately, events.. More im- there is a vast collec- portantly these first-hand accounts tion of data available online that not only provide a snapshot view of' can provide insight into your family slave life in America, but also history. With more than 4 billion sometimes provide details about a records available online, it's easier slave's parents and/or owners. And everyday to discover who you are many of these accounts contain and where you come from." Large Cantaloupes Golden Pineapples IJA// Prices Effective: March 3rd through March 8th, 2005 pen 6am untlMidnight. W CaI* SA MWQ4 A4 Thurs. Fri. I Sat. Sun.Mon. Tues. 7Op7D manajtakmfhor SveRite proudly otrs 3 4 5 6 7 Ts8 1I 8 7-Po- 7Hallmark Cards JACKSONVILLE LOCATIONS: 1012 N. Edgewood Ave., Tel. 904-786-2421 5134 Firestone Road, Tel. 904-771-0426 201 W. 48th St., Tel. 904-764-6178 Ms. Perry's F~ree Press Page 9 March 3-9 2005 P e 10 Ms. Perry's Free Pre s March 3-9, 2005 Scrabble Soiree Do you love a good game of Scrabble or friendly competition? SLearn to Read is inviting the public to participate in the 7th Annual Letters for Literacy on Thursday, March 3, 2005 at St. John's Cathedral, 256 E. Church St., from 6:00 p.m.-8:00 p.m. The evening will consist of wine, hours d'oeuvres, silent auction and prizes. Scrabble teams of six to eight members will have 30 minutes to build the highest scoring Scrabble board. For more information, call 398-8894. Grief Support Group One of the most helpful ways of coping with the death of a loved one is to share with others who are experiencing a similar loss. In this 6-week support group, members have an opportunity to express their feelings and thoughts as well as gain an understanding of grief and how it impacts their lives. Sharing is voluntary and confidential. The meetings will be held March 8, 15, 22, 29 and April 5 beginning at 7 p.m. at the Hospice of Jacksonville, 8130 Baymeadows Way W. Ste. 202. To register or for more information contact, Richard Marsh at 733-9818. Native American Indian Festival The. 14th Annual St. Augustine Native American Indian Festival will be held March 4-6. Sponsored by the Seminole Tribe of Florida, the event takes place outdoors at the festival field on Castillo Dr. next to the Visitors Center in historic downtown St. Augustine. The weekend will feature performances, food, artists and craft vendors from all parts of North America. The festival starts 4-9 p.m. on Friday and begins at 10 a.m. on Saturday and Sunday. For more information, please call 940- 0902.. Sacred Jazz Concert The Second Harvest Food Bank will be holding a benefit concert on Saturday, March 5, 2005 at 8:00 p.m. in the Jacoby Concert Hall in the Times Union Center for the Performing Arts. The featured artist ill be Noel Freidline. For Roslyn Phillips at 764-9485 or 477-7398. Spring Carnival Palms Presbyterian School wi present their Spring Carnival c Saturday, March 5, 2005 froi 10:30 a.m.-3:00 p.m. at the school located at 3410 S. 3rd St. Jacksonville Beach. Highligh include children's games, ride cakewalks, prizes and great food Proceeds from the carnival wi benefit the scholarship fund an classroom equipment. For mot information call 247-0983. Masquerade Ball The Continental Society wi present their 4h' Annua Masquerade Ball with a Zulu Fla on Saturday, March 5, 2005 at th University Center at the Universit of North Florida. Festivities wi begin at 8 p.m. The ticket pric includes Hors d' oeuvres, buffe cash bar, live entertainment, casin and door prizes. A mask will I provided. For tickets or mot information, please call 745-5344. Friendly Yard Class On Saturday, March 5, 200 from 10:00 a.m. 1:.00 p.m. at th Duval County Extension Offici 1010 N. McDuff Ave., will ho "Florida Friendly Ideas For Florid Yards." The emphasis of th: program will be low volume irrigation and what it means to yo the homeowner. New rules ar coming and you need to kno' them. You will also learn the be; Florida Friendly landscape practices for spring. Please call t register 387-8850. Girl Scouts Women of Distinction Luncheon Girl Scouts of Gateway Counc will honor six women at the 17 Annual Women of Distinctio Luncheon at the Radisso Riverwalk Hotel, March 11, 2005 This year's honorees ar Congresswoman Corrine Browr Rita Cannon, Betty P. Cook, An C. Hicks, Janice G. Lipsky and Susan Wildes. The luncheon wil take place from 12:00 p.m. 1:30 p.m. and is open to the public with advance registration required. Fo reservations, please call 388-465. ext. 1142. ~ b' r L ' I ., i ~ ; Stanton Class of 1945 Bride and Groom ll Reunion Meeting Extravaganza on The Class of 1945 continues to Classic Fare Catering, 1301 m finalize plans for their 60th Class Riverplace Blvd., will host a Bride il reunion and look forward to seeing and Groom Extravaganza at their in you at their next class meeting on Southbank waterfront location on ts March 5, 2005, 3:30 p.m. 5:30 Sunday, March 13, 2005 from s' p.m., in the Community room of 12:00 p.m. 4:00 p.m. Over 75 .the Bradham/Brooks Northwest wedding professionals will attend, ld Library 1755 Edgewood Ave. W. showcasing everything from S For more information, contact V. wedding & reception facilities, r Crumley at 354-6747. catering, photography, floral Sisters Network services, ice sculpture and formal wear. Participants will also enjoy a 11 Gospel Benefit tearoom fashion show. Outside al The Sisters Network of tours will be available on the ir Northeast Florida A support Annabelle Lee and Lady St. Johns ie Group for African American riverboats. To keep grooms -to-be :y women surviving breast cancer will entertained; the event will feature 11 be hosting a gospel musical event live music, prizes and a cigar bar. :e on Sunday, March 6, 2005. The For more information, please call et, event will be held at Grace Baptist 354-0076 ext. 212. 0o Church of East Springfield, 1553 E. Kappa Golf ,e 21st. St. and will begin at 6 p.m. re Proceeds will be donated to Sisters Tournament Network. For more information, The Jacksonville Alumni please call Sis. Claudia Campbell at Chapter of Kappa Alpha Psi 708-4776. Fraternity, Inc. Guide .Right S Women's History Scholarship & Developemnt S W His ry Foundation, Inc. will hold their 11th S Day at MOSH Annual Charity & Scholarship Golf st The public is invited to Tournament on Saturday, March la celebrate Women's History Month 12, 2005, beginning at 1:00 p.m. is and female firsts including Marie with a Shotgun start. The le Curie, Amelia Earhart, Aretha tournament will be held at the Mill Du Franklin, and Oprah Winfrey at the Cove Golf Course on Monument e Museum of Science and History. Rd. For more information, please w The celebration, which is open to call 768-1964. st the public, will be held on March pe 11, 2005 from 1:00 p.m. 3:00 Bob Hayes Track Meet o p.m. For more information, contact The nation's most coveted MOSH at 904-936-7062. The track and field event for middle Museum is located at 1025 and high school students will take Museum Cir. place March 18-19, 2005 at Raines Literacy Seminar High School. Now in its 41"s year, It's never t ltevent organizers continue to expose It's never too early to start participants to top track and field teaching your kids to read. Mark coaches. Beyond the track and il your calendars for Monday, March field event, there will be a worship S14, 2005 from 6:30 8:30 p.m. as service, golf tournament and a Hall n Dr. Michael A. Sisbarro will of Fame Banquet. A minimum of n present a state of the art interactive 176 teams representing five states 5. free parenting seminar focusing on .(over 3500 aihleIic participants) e earl) literacy, brain invo cmenr, will be in the Track Meet. For more n, assessment and intervention information, please call 404-346- n options. A certificate of attendance 0410. d will be available by request. Please 11 RSVP to the JCA at 730-2100 ext. Learn How to 0 MOSH Easter Grow Herbs r Egg Hunt Duval County. Extension 3 MOSH, The Museum of staffers will present a program on Science and History, will host an Tuesday, March 15, 2005 from SEaster. Egg Hunt on Saturday, 10:00 a.m. noon at the Duval March 19, 2005 from 10:00 a.m. County Extension Office located at 1:00 p.m. The annual FREE Easter 1010 N. McDuff Ave. Learn all Egg Hunt is for children eight years about growing and using herbs, of age and younger. It will be held butterfly gardening,, selecting on the Museum grounds and in fertilizer, and calculating fertilizer adjacent Friendship Park. For more rates. There will also be herbs for information, please call the sale. Please pre-register by calling Museum. 387-8850. ww/w.wemakethechange.com Florida Department of Health Bureau of HIV/AIDS io1. AM- -OWN .- ~~~-" hat to do from social, volunteer, political and sports activities to self enrichment and the civic scene JCCI Forward Social: Night at the Symphony Join JCCI for a special evening of "Let's Dance" by the Jacksonville Symphony Orchestra and pre-show social on Friday, March 18, 2005. The evening will begin from 6:00 p.m.-7:30 p.m. at Mongo's Flat Hot Grill ( at the Jacksonville Landing). There you can learn more about JCCI Forward and their upcoming events while enjoying a special Happy Hour. The show begins at the Times- Union Center at 8:00 p.m. Tickets are complimentary. Respond now to reserve your seat. Call Tess at 396-3052 or email tess@jcci.org. Lighthouse Festival The St. Augustine Lighthouse & Museum will host a day of free family fun at the 13th Annual Lighthouse Festival on Saturday, March 19, 2005. Admission to the tower, museum and grounds is free all day. The Victorian-era light station will be filled with living history activities, children's games and crafts, pony rides, live entertainment, a photo contest, a silent auction and the Michelob Ultra 5K Run/Walk and Fun Run. For more information about Lighthouse Festival or the St. Augustine Lighthouse and Museum, go to or call 829-0745. Genealogist's Meeting The Southern Genealogist's Exchange Society is now meeting jointly with the Jacksonville Genealogical Society on every third Saturday at 1:30 p.m. in the Willow Branch Library. The next meeting will be held on March 19, 2005. For additional information please call Mary Chauncey at 781-9300. Workshop The Florida Department of Management Services and Office of Supplier Diversity will host the 2005 Regional Matchmaker Workshop in Jacksonville centering on the topic, "Doing Business with the State: What Vendors Need to Know". On site certification will be available. The event will be held on Wednesday, March 23, 2005 at the Radisson Riverwalk Hotel. For more information, please call 850- 487-0915. Rabia Temple Boat Ride Rabia Temple #8 clown Unit will present their 2"d Annual All White Boat Ride from 8:00 p.m. - 12:00 a.m. on March 25, 2005. The evening will feature a live DJ aboard the Lady St. John as they cruise down the St. Johns River. The Boat will load behind Chart House Restaurant and the ticket price includes food and door prizes. Must be 21 to sail. For more information, please call 338-4037, 721-0663, or 233-8473. Kids Poetry Slam There will be a Kid's Poetry Slam and Open Mic for youth ages 10-13 & 14-17 with cash prizes on Saturday, April 9, 2005 from 1-5 p.m. The Slam will be held at the Kennedy Center on Lona St. For more information, call 502-7444. I RAP Home Tour Riverside Avondale Preservation will present their 31s' Annual Spring Tour of Homes on Saturday and Sunday, April 23 and 24, 2005 in the Riverside Avondale Historic District. Hours are 10:00 a.m. 5:00 p.m. on Saturday and 12 noon 5:00 p.m. on Sunday. For more information, please call 389-2449. Shrimp Festival The Eight Flags Shrimp Festival will be held in historic downtown Fernandina Beach, April 29, 30 & May 1, 2005, and the Annual Shrimp Festival Pirate Parade will be held Thursday, April 28, 2005 at 6:00 p.m. For more information, visit. Links Old School Jam The Bold City Chapter of Links, Inc. will present their 2 Tillie Fowler who will be lauded for their community service and receive the organization's Silver Medallion Award. For more information about the dinner or for tickets, call 306-6225.. NEWS YOU CAN USE The Jacksonville Free Press will print your Church, Social and Community News, at no cost. News DEADLINE, 5PM Monday News may be faxed (765-3805) or at office, 903 W. Edgewood Ave. (across from Lake Forest Elem.) I annual Oscars Bedazled and Delihted movie ans Annual Oscars Dedazzled and Delighted Movie Fans w r1 I3 Shown above at the Oscars are (I-R) best Actor Jamie Foxx with his daughter Corrine, Tonya and Spike Lee, Host Chris Rock, Manuela Testoni and hus- band Prince, Kim Porter with boyfriend Sean Combs, (MIDDLE) Quincy Jones, Halle Berry and Oprah Winfrey, Be- yonce with boyfriend, Motown CEO Jay Z., Best Supporting Actor winner Mor- gan Freeman with daughter Morgana, Hotel Rwanda nominees Sophie Ok- onedo and Don Cheadle, LaTanya Richardson and husband Samuel Jack- son; (BOTTOM) Al and Starr Reynolds, "Ray" leading actress Kerri Washington and Melvin Van Peebles with son Mario and actress Vivica Foxx. Are we dreaming, or did the past ity tonight.' weekend at the Oscars really hap- said, in his be pen? It may have been "Million Foxx also Dollar Baby's" day in the sun on most emotion paper, but the night, belonged to talked about Jamie Foxx, who won the best actor raised him. Academy Award for his starring when he spok performance in "Ray." Foxx's sup- acting coach. porting actor nomination for She taugh "Collateral" was beaten by Morgan straight, put y Freeman's role in "Million Dollar and act like Baby," which also nabbed golden he said, addir statues for best picture, best direc- talks to him i tor (Clint Eastwood) and best ac- wait to go to tress (Hilary Swank). we got a lot The way things were going, it said. looked as if "Baby's" Clint East- Meanwhile, wood might take over the best actor nominee Mor category as well, but it was Jamie his first-ever Foxx's name that came out of pre- tricky." senter Charlize Theron's mouth. "After 'D When asked backstage the nature of became phil the lengthy whispering between the Oscar," he South African actress and the Ter- stage. "It occ tell, Texas native before he took the ning the nomi podium, Foxxjoked:"I said [to her], height for m 'Can we talk about you and me?'" pretty arbitrar "When you see people like Char- be best? But lize, like Halle, you see how beauti- name, all tha ful they are, but it's just great to dow." chat with them about the art," hec Foxx and continued. "Halle was tapping me on my shoulder saying 'are you ready.' It's just great to just be in that league." With Halle and Oprah look- ~ -- ing on from the audience like proud mothers, Foxx clutched his Oscar and thanked "Ray" director Taylor Hackford, his longtime managers Jamie and Marcus King, his late grand- mother Estelle, and his 11- year-old daughter and Oscar date Corrine. punch marked "She said, 'Dad after this, can in Oscar histo we go to the big awards The Kid's two of the for Choice Awards?'" Jamie told re- lowing Denz porters backstage. "She doesn't Halle Berry's know the significance of it right "Training Da now, but years from now when Ball." she's talking to her friends, she'll be Peppered t like, 'That night me and my dad...'" ceremony wer Foxx joins Denzel Washington ances of the and the legendary Sidney Poitier as songs, which the only African Americans to win number "Vois a best actor award in Oscar's 77- from the fil year history. During Foxx's accep- "Learn To tance speech, he thanked Oprah for "ThePhantom introducing him to Poitier. "Believe," a d "He said, 'I give you responsibil- from "The Po ity.' So I'm taking that responsibil- Ross-like outf Th st pr nal his Te e t ou yo ng in sli to gar r )riv osc to urr na e y. w It F anks Sidney," Foxx nied each performance, and her Poitier impression, man Jay-Z soaked in each moment provided the night's from the audience. moment when he And where do we begin with s grandmother who Chris Rock? ears began to well The comedian came out to a of her being his first standing ovation, then quickly be- gan slinging stingers toward Holly- him to "stand up wood's elite. He joked about seeing :r shoulders straight, films that made him think the star- u got some sense," ring actors needed money. After that sometimes she seeing Cuba Gooding Jr. in "Boat his dreams. "I can't Trip," Rock said he sent the actor a eep tonight because check for $80. talk about," Foxx In another bit urging filmmakers to wait for better talent instead of three-time Oscar rushing bad movies into theaters, n Freeman, 67, said Rock said: "Clint Eastwood's a star, win is "kind of ok? Tobey Maguire's just a boy in tights. You want Tom Cruise and ring Miss Daisy,' I all you can get is Jude Law? Wait. ophical about the You want Russell Crowe and all Id reporters back you can get is Colin Farrell? Wait. red to me that win- 'Alexander' is not 'Gladiator.' You tion is probably the want Denzel and all you can get is and after that its' me? Wait. Denzel's a fine actor. He How can any of us would never made 'Pootie Tang."' hen they call your Some two hours after that joke, goes out the win- Sean Penn took the stage to present the award for best actress, but first reeman's one-two took time out to defend Jude Law as "one of our finest actors." After the commercial break, Rock immediately addressed Penn's comment, stating: "Sean Penn, my accountant wants to see Syou," referring to the earlier joke "J about sending $80 checks to ac- S tors. After the ceremony, Rock was asked what he thought was his best line of the night. "I don't know, my jokes are like my children," he said. "I liked the Sean Penn comeback." nly the second time This Oscar ceremony was the that Blacks earned best year ever for African Ameri- acting awards, fol- cans, who earned a record five of Washington and 20 acting nominations, including ad-acting wins for the two for Foxx. Don Cheadle was and "Monster's nominated as best actor and Sophie Okonedo as best supporting actress oughout Sunday's for "Hotel Rwanda." Beyonce's perform- It means that Hollywood is con- Oscar nominated tinuing to make history," Freeman cluded the French said backstage. "We're evolving Sur Ton Chemin" with the rest of the world." "Les Choristes," Chris Rock's take on the pres- e Lonely" from ence of African Americans in the f the Opera," and Kodak Theater Sunday night? t with Josh Groban "It always feels good to see some ir Express." Diana color in the room that don't have changes accompa- mops." So ry ur ,el le Iay thr e E e in s m B of ue ola it 9**m e a m . * * * * - "Copyrighted Material Syndicated Content . Available from Commercial News Providers" Ms. Perry's Free Press Page 11 March 3-9 2005 March 3-9, 2005 Pam-11 -I Mr Pe1'w Fre Pressi P U B L I X C E L E B R A T E S H I S T O R Y my recipe for living, my history. '- / Leah Chase Chef, Restaurateur, Author Icon Dooky Chase Restaurant I New Orleans, La. Main Ingredient: Dedication Leah Chase's rise to Queen of Creole Cuisine didn't start with a hunger for fame and fortune, but instead from a desire to provide hot lunches to Black men beginning to work in nearby offices. Believing that "you have to put all your love in that pot," Chef Chase's passion isn't just about good food, but also a testament to her legacy of determination, cultural pride and community involvement. / ii; i' :t. -'r`' f;'.; ~" '' ~: . r : ? r ' r;.tr *r~i~nr~-- P 02005 Puhi ix A\sct Manlagcrcni, Inc. 2'3' a .Y;, I: ,, ,I 1 . Publix. WHERE SHOPPING IS A PLEASURE." rag~e jL iil. rery sivrevirx-n N I u .. ;. I i :. ' :. .. i | http://ufdc.ufl.edu/UF00028305/00011 | CC-MAIN-2017-17 | en | refinedweb |
hi everyone!
there are a few questions that I'd like to ask regarding a particular problem.
I havent seen an entry like this before... so if this is inappropriate, please delete this thread!
here's the program code....
//********************************************************************
// ReboundPanel.java Author: Lewis/Loftus
//
// Represents the primary panel for the Rebound program.
//********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ReboundPanel extends JPanel
{
private final int WIDTH = 300, HEIGHT = 100;
private final int DELAY = 20, IMAGE_SIZE = 35;
private ImageIcon image;
private Timer timer;
private int x, y, moveX, moveY;
//-----------------------------------------------------------------
// Sets up the panel, including the timer for the animation.
//-----------------------------------------------------------------
public ReboundPanel()
{
timer = new Timer(DELAY, new ReboundListener());
image = new ImageIcon ("happyFace.gif");
x = 0;
y = 40;
moveX = moveY = 3;
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.black);
timer.start();
}
//-----------------------------------------------------------------
// Draws the image in the current location.
//-----------------------------------------------------------------
public void paintComponent (Graphics page)
{
super.paintComponent (page);
image.paintIcon (this, page, x, y);
}
//*****************************************************************
// Represents the action listener for the timer.
//*****************************************************************
private class ReboundListener implements ActionListener
{
//--------------------------------------------------------------
// Updates the position of the image and possibly the direction
// of movement whenever the timer fires an action event.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
x += moveX;
y += moveY;
if (x <= 0 || x >= WIDTH-IMAGE_SIZE)
moveX = moveX * -1;
if (y <= 0 || y >= HEIGHT-IMAGE_SIZE)
moveY = moveY * -1;
repaint();
}
}
}
Questions I'd like to ask....
1. How do I move the smiley diagonally? I've tried experimenting with the moveX and moveY values, but to no avail. So, I don't really understand my java well...
2. At this stage, the smiley will run out of the window (right and bottom sides). Smiley should bounce back as soon as it touches the 4 sides of the window.
Write down the steps you take to solve this problem.
3. Using array implement 2 bouncing smileys. does this mean just declaring the necessary variables etc to get a second smiley??
4. Implement such that when i click the mouse on this window, the 2 bouncing smileys will stop. The next clicked will make them move again.
can anyone be patient & kind to guide me along? thanks much.
ps. the alightment might be slightly altered due to the textbox.
I actually had to do this program before, but I used objectdraw rather than swing.
The trick is that the action performed doesn't need to use "if...else..." as you implemented it.
The solution that I would use is create two booleans "moveXRight" and "moveYUp" or something to those effects.
What you do then is IF x == WIDTH-IMAGE_SIZE THEN moveXRight = false. You also need another one IF x==0 THEN moveXRight = true.
//checks if it reaches a side
//if it has reached a side, it changes direction
//otherwise it keeps going in its direction
if((moveXRight == false && moveX>0)||(moveXRight == true && moveX<0))
moveX*=-1;
Then you do the same thing with moveY.
In my program, I made the ball move randomly in the X direction and randomly in the Y direction (though the random number was between 0 and 1 so I had control over the direction ).
You would have to implement this in the actionPerformed method.
Goodluck!
thanks for replying! i'll try that soon.
[glowpurple]First you must decide. Then you must follow through.\" - Lacus Clyne[/glowpurple]
Forum Rules | http://www.antionline.com/showthread.php?272368-reboundpanel.java-help!&p=899471&viewfull=1 | CC-MAIN-2017-17 | en | refinedweb |
Suddenly, The Password Is `Value'Jeffrey M. Laderman
Some 18 months ago, Robert Martorelli watched in amazement as recession-wary mutual-fund managers flocked to supergrowth stocks such as Amgen, The Gap, and Home Depot that could prosper in a sick economy. "We saw incredible values as people threw away stocks that didn't have earnings momentum," says Martorelli, who runs the $240 million Merrill Lynch Phoenix Fund, which invests in unloved and unwanted companies. So, he selected investments "for the upturn"--and waited. The fund logged a respectable 37% total return in 1991. But that was far behind funds that had loaded up with high-octane growth stocks.
Now, with the economic recovery in hand, Martorelli's patience is paying off. His fund was up 18.69% for the first quarter (through Mar. 27), the best growth fund and fifth-best of some 1,200 equity funds tracked by Morningstar Inc. Now, it's Martorelli and his unglamorous stocks, such as Anacomp, National Semiconductor, and Navistar International, that are looking snazzy.
The eclipse of growth stocks by economically sensitive or "value" stocks was the most dramatic shift in a market that, on the surface, looked placid. The Dow was up about 2%, the Standard & Poor's 500-stock index down 2.8%. The average U.S. diversified equity fund neither made nor lost money. That may disappoint those who piled a record $14.2 billion into equity funds in the first two months--a figure that could easily reach $20 billion when March sales are tallied. Investors tend to buy last year's winners, and those who picked 1991's hot growth funds were more disappointed.
The move away from high-growth stocks was evident in the largest funds: Twentieth Century Select Investors, a growth-stock fund, slid 7.29% during the quarter. By contrast, the Windsor Fund, which makes big bets on cyclical companies, delivered a 4.52% return (table). Even more graphic evidence: The quarter's top-performing fund specialized in one of the U.S.'s most cyclical industries. Fidelity Select Automotive Fund (table) jumped nearly 25% on the rally in auto stocks. The fund's assets under management exploded, too, going from $2.4 million at yearend to $82 million by the end of March.
ILL HEALTH. Health care funds, previously regarded as the prescription for investment success, took the worst drubbing--an average loss of 10.77% for the quarter. Oppenheimer Global Bio-Tech, which soared 121.1% last year to become the best-performing fund of all, dropped 13.82%. Fidelity's Biotechnology, Health Care, and Medical Delivery sector funds, all among last year's top 20, have taken ill, too. They're taking up the rear along with the long-suffering Japanese and precious-metals funds.
Compared with the health care funds, the diversified growth-stock funds that led the charge last year just have the sniffles. Of 1991's top 10 growth funds, six are in the red so far this year. Still, the worst of the lot, the Janus Twenty Fund, was down just 7.94% in 1992--hardly a serious stumble after last year's 63.9% climb.
Not all of last year's leaders were dethroned. Financial specialty funds, for instance, are still riding high. In 1991, financial-services companies rallied mightily as interest rates dropped dramatically. Although interest rates are creeping up this year, the financial funds are still eking out gains. That's because investors now figure that banks and thrifts, heavily represented in these funds, have the worst of their losses behind them. Strength in the financial sector is also bolstering more diversified funds with major holdings in financial companies. "Finance stocks are important for us," says Heiko Thieme, manager of the American Heritage Fund, one of the few 1991 leaders that is still leading. His fund reaped about a third of its 16.67% return from financial stocks.
Small-company funds, whirlwinds in 1991, are still making gains. But among funds that invest in small stocks, there was a changing of the guard, too. Again, high-growth has been giving way to value issues with rock-solid fundamentals.
A typical example: Last year's red-hot Montgomery Small Cap Fund, which built a stellar 98.7% return with shrewd investments in high-growth emerging companies, is off 5%. Now the leading small-company fund is the more sober Heartland Value Fund, up 19.74%. Like Merrill Lynch Phoenix, Heartland kept pace with its peer group last year, but it really broke away from the pack in January. Like Phoenix, it invests in companies with good fundamentals that are out of favor with investors. They include companies in prosaic businesses, such as auto parts and small-town banking, which are cheap by most investment yardsticks. Says Heartland portfolio manager William Nasgovitz: "We never buy a stock with a p-e greater than 10."
ILLIQUID. Not surprisingly, other top-performing funds--Pioneer Capital Growth, Babson Enterprise, and Skyline Special Equities--also practice small-cap value strategies. Even more telling is that two top funds, Colonial Small Stock Index, up 16.09%, and the DFA U.S. 9-10 Small Company Fund, up 13.89%, are index funds that buy the smallest-capitalization stocks. Last year, they underperformed the average small-company fund; this year, they're beating all but two. The reason is that most small-cap managers shoot for fast-growing, leading-edge companies. The indexes, on the other hand, include the hundreds of mundane small companies that are more dependent on the economy for growth. It is those stocks, longtime laggards, that are now on the make.
While managers who buy Philip Morris Cos. and Exxon Corp. can deploy dollars easily, it's harder for those who invest in small-company stocks. Information about the companies is hard to find, and the stocks are often illiquid. That's why the Fidelity Low-Priced Stock Fund, which went from $200 million in assets to $800 million in just seven weeks, shut its doors on Mar. 9. "We need time to put that money to work," said Neal Litvack, senior vice-president at Fidelity. Other small-company funds that closed during the quarter include Montgomery Small Cap and Babson Enterprise.
Although the first-quarter performance derby was clearly won by the cyclical, or value-stock, players, the growth-stock portfolio managers have not cried "uncle." The case for health care stocks, for instance, is based on an aging population and new medical technologies, not on the economy. Should the recovery prove weak, investors could dump the economically sensitive stocks and return to reliable growth stocks--and the growth funds that soared in recent years will resume their flight.
Investors should get an idea of which way the winds are blowing when companies report first-quarter profits in coming weeks. If the cyclicals are still not up to speed, the value funds' newfound celebrity status may be short-lived. | https://www.bloomberg.com/news/articles/1992-04-12/suddenly-the-password-is-value | CC-MAIN-2017-17 | en | refinedweb |
cexp man page
Prolog
This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
cexp, cexpf, cexpl — complex exponential functions
Synopsis
#include <complex.h> double complex cexp(double complex z); float complex cexpf(float complex z); long double complex cexpl exponent of z, defined as ez.
Return Value
These functions shall return the complex exponential value of z.
Errors
No errors are defined.
The following sections are informative.
Examples
None.
Application Usage
None.
Rationale
None.
Future Directions
None.
See Also
clog()
The Base Definitions volume of POSIX.1‐2008, <complex . | https://www.mankier.com/3p/cexp | CC-MAIN-2017-17 | en | refinedweb |
Hi,
I was making a simple game in C++ and OpenGL with what I learned from a bunch of pretty old tutorials (which I discovered later), and now I'm in the process of updating everything and I've got some questions about the VBO implementation.
I had this code:
class Vertex { public: float posX, posY, posZ; }; class Face { public: Vertex** vertexes; //bunch of functions to get and set the vertexes and their values }; class Object3D : public Object { public: Face* faces; Vertex* vertexes; //bunch of functions to initialize the vertexes and faces };
So my Object3D had an array of all vertexes informations, each with their X, Y and Z, and another array for Faces, which gave me the addresses of 3 Vertexes that composed 1 Face of the object.
It worked fine since I was calling:
void Game::Draw(Object3D* object) { for(int i = 0; i < object->totalFaces; i++) { glVertex3f(object->faces[i].GetVertex[0]->posX, object->faces[i].GetVertex[0]->posY, object->faces[i].GetVertex[0]->posZ); glVertex3f(object->faces[i].GetVertex[1]->posX, object->faces[i].GetVertex[1]->posY, object->faces[i].GetVertex[1]->posZ); glVertex3f(object->faces[i].GetVertex[2]->posX, object->faces[i].GetVertex[2]->posY, object->faces[i].GetVertex[2]->posZ); } }
But now that I'm going to turn everything into VBOs, I need a single array with the sequential float values of each of the object's faces, so it means I'll even have to repeat some vertex's values sometime when they share the same point.
This is where I'm at, I'm trying to figure what would be the best way to do this.
My animation code (unfinished) moved the vertexes according to the bone's movement and weight, and all I had to do was to change the values in my "vertexes[]" array of the Object3D, and I didn't had to worry about it's faces.
Now, I will have to change the new vertex data array I'll be buffering as VBO, and I'd like to get some ideas on how.
I have no experience releasing games, and I never seen a professional/released engine code before, so I've got literally no idea what's the common approach to this.
For now I'm thinking in getting something like this:
class Object3D : public class Object { public: float* vertexData; // = new float[totalVertexes]; - this will be what I'll send/map to the VBO as data //same as before, vertex and faces arrays };
And everytime there's a change in the model, I'll change the vertexes array as usual, and then update the values in "vertexData" and finally update the VBO.
This seems a bad idea as I'll be doing this for every animated object in the screen... and I'd be using twice as much memory for every model since I have two variables with the same values.
Isn't there a way to send the VBO data in a different manner? If it searched by index, I think I could create a class and override the brackets operator to send the address that I want, but since it's function asks for the size, I'm guessing it moves by memory size...
Is there any good approaches to this, or what's the best way to do this? (I'd like to totally scrap the vertexes array and only work with the vertexData I've sent/mapped to the VBO) | http://www.gamedev.net/topic/640083-performance-vbos-and-objects/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024 | CC-MAIN-2014-52 | en | refinedweb |
Hello World - Writing, Compiling and Running a C++ ProgramEdit
Below is an example of a simple C++ program:
// 'Hello World!' program #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; }
When you write a program you use a development environment. Your development environment can be a basic text editor or a feature rich C++ integrated development environment (IDE). You should not use a word processor like Microsoft Word, because it adds formatting codes to the text.
If a compiler is not already available to you, see the Where to get a compiler Section of the book.
Open your development environment and type the program shown (or copy and paste it) and save it as hello.cc.
Now compile it using the C++ compiler:
COMMAND_PROMPT> g++ hello.cc -o hello
The example uses GCC, the GNU Compiler Collection ( ) but you could use any other compiler, or use an IDE to compile it. The above command would produce an executable called hello or hello.exe. Invoke the executable to run your first C++ program:
Unix:
COMMAND_PROMPT> ./hello Hello World! COMMAND_PROMPT>
Microsoft Windows:
COMMAND_PROMPT> hello Hello World! COMMAND_PROMPT>
Text that is italicized is typed by you and the bold text is output by the program. If you use an IDE, it might automatically color the code for you based on the syntax.
TroubleshootingEdit
- g++
- command not found
You don't have the GNU C++ compiler installed. If you have a different compiler, check it's documentation for the correct compilation command.
- Wrong Compiler Command
Lot of weird errors, mentioning many times:
undefined reference to `std::basic_ostream' [..]
Usually ending with:
collect2: ld returned 1 exit status
To use g++ to compile your hello.cc use:
g++ hello.cc -o hello
For gcc use:
gcc hello.cc -o hello -lstdc++
- hello
- command not found
You did not type the full path, try:
./hello
Is there a hello program in this directory? Can you see it when you type ls? If not, your compilation (g++ hello.cc -o hello) failed or you have changed to a wrong directory.
If you do not specify -o hello, g++ names the output file a.out (assembler output) for historical reasons. In such a case, type:
./a.out
to execute the program.
Your First C++ Program ExplainedEdit
The preprocessing directiveEdit
Some features of C++ are part of the language and some others are part of a standard library. The standard library is a body of code that is available with every C++ compiler that is standards compliant. When the C++ compiler compiles your program it usually also links it with the standard C++ library.
When you use features from the library, C++ requires you to declare the features you will be using. The first line in the program is a preprocessing directive. In our example it is shown bold and italicized:
- The preprocessing Directive for IOStreams
#include <iostream>
This line causes the C++ declarations which are in the iostream header to be included for use in your program. Usually the compiler inserts the contents of a header file called iostream into the program. Where it puts it depends on the system. The location of such files may be described in your compiler's documentation. A list of standard C++ header files is in the standard headers reference tables.
The iostream header contains various declarations for input/output (I/O). It uses an abstraction of I/O mechanisms called streams. For example there is an output stream object called std::cout which is used to output text to the standard output. Usually, this displays the text on the computer screen.
The preprocessor is a part of the compiler which does some transformations to your code before the actual compiler sees it. For example, on encountering a #include <iostream> directive, it replaces the directive with the contents of the iostream header file.
main FunctionEdit
int main() { // ... }
The lines above represent a block of C++ code, given the name main. Such a named block of code is called a function in C++ parlance. The contents of the block are called the body of the function.
The word int is shown in bold because it is a keyword. C++ keywords have some special meaning and are also reserved words, i.e., cannot be used for any purpose other than what they are meant for. On the other hand main is not a keyword and you can use it in many places where a keyword cannot be used (though that is not recommended, as confusion could result).
Every (standards-compliant) C++ program must define a function called main. This is where the execution of the program begins. As we shall see later, main may call other functions which may call yet other functions. The compiler arranges for main function to be called when the program begins executing. (Although this is generally true, it is not always true. There is an exception to main's being executed at the very beginning that we will see later.)
Now let us look at the code inside the main function.
Printing Hello World!Edit
The first line in main uses the std::cout object to print the string (sequence of characters) Hello World! and end the line:
std::cout << "Hello World!\n";
This line is a C++ statement. C++ statements are terminated by a semicolon (;). Within the statement <<, called the insertion operator is used to output the string using the std::cout stream. C++ strings are enclosed within double quotes ("). The quotes themselves are not part of the string and hence not printed. The sequence \n is used within a string to indicate the end of the current line. Though the sequence is represented by two characters, it takes up only one character's worth of memory space. Hence the sequence \n is called the newline character. The actual procedure to start a new line is system-dependent but that is handled by the C++ standard library transparent to you.
Modifications to the Above ProgramEdit
Here is the same program with minor modifications:
// This program justs displays a string and exits #include <iostream> int main() { std::cout << "Hello World!"; std::cout << std::endl; return 0; }
The line added at the beginning:
// This program justs displays a string and exits
is a comment that tries to explain what the code does. Comments are essential to any non-trivial program so a person who is reading the code can understand what it is expected to do. There is no restriction to what is contained between the comment delimiters. The compiler just ignores all that is there in the comment. Comments are shown italicized in our examples. C++ supports two forms of comments:
- Single line comments start with a // and extend upto the end of the line. These can also be used to the right of statements to explain what that statement does.
- Multi-line comments start with a /* sequence and end with a */ sequence. These can be used for comments spanning multiple lines. These are also known as C-style comments as this is the only type of comments available in C. e.g.:
/* This program displays a string and then it exits */
Comments are also used at times to enclose code that we temporarily want the compiler to ignore, but intend to use later. This is useful in debugging, the process of finding out bugs, or errors in the program. If a program does not give the intended result, by "commenting out" code, it might be possible to track which particular statement has a bug. As C-style comments can stop before the end of the line, these can be used to "comment out" a small portion of code within a line in the program.
Flushing the Output Stream BufferEdit
Whenever you write (i.e., send any output) to an output stream, it does not immediately get written. It is first stored in memory and may actually get written any time in the future. This process is called buffering and the regions in memory used for storing temporary data like this are called buffers. It is at times desirable to flush the output stream buffers to ensure all data has been written. This is achieved by applying the insertion operator to an output stream and the object std::endl. This is what is done by the line:
std::cout << std::endl;
Before flushing the buffer, std:endl also writes a newline character (which explains its name, end line). Hence the newline is omitted in the string printed in the previous line.
Returning Success CodeEdit
In most operating systems, every program is allowed to communicate to the invoker whether it finished execution successfully using a value called the exit status. As a convention, an exit status of 0 stands for success and any other value indicates failure. Different values for the exit status could be used to indicate different types of failures. In our simple program, we would like to exit with status 0.
C++ allows the main function to return an integer value, which is passed to the operating system as the exit status of the program. The statement:
return 0;
makes main to return the value 0. Since the main function is required to return an integer, the keyword int is used to begin the function definition. This statement is optional since the compiler automatically generates code to return 0 for the main function for the cases where control falls off without a return statement. This is why the first program worked without any return statements. Note that this is only a special case that applies only to the main function. For other functions you must return a value if they are declared to return anything.
Common Programming Error 1 Though the return statement is optional, main should not be declared to return void (a function declared as void is a function which does not return anything) as in some other languages like Java. Some C++ compilers may not complain about this, but it is wrong. Doing this could be equivalent to returning just about any random number that happened to be stored in a particular memory location or register, depending on the platform. This practice can also be potentially damaging to some operating systems, which rely on the return code to determine how to handle a crash or other abnormal exit.
Whitespace and IndentationEdit
Spaces, tabs and newlines (line breaks) are usually called whitespace. These are ignored by the compiler except within quotes, apart from the rule that preprocessing directives and C++-style comments end at a newline. So the above program could as well be written as follows:
// This program justs displays a string and exits, variation 1 #include <iostream> int main() { std::cout<<"Hello World!"; std::cout<<std::endl; return 0; }
Note, however, that spaces are required to separate adjacent words and numbers. To make the program more readable, whitespace must be used appropriately.
The conventions followed when using whitespace to improve the readability of code constitute an Indent style. For example with alternate indent styles the program could be written like this:
// This program justs displays a string and exits, variation 2 #include <iostream> int main() { std::cout << "Hello World!"; std::cout << std::endl; return 0; }
or like this:
// This program justs displays a string and exits #include <iostream> int main() { std::cout << "Hello World!"; std::cout << std::endl; return 0; } | http://en.m.wikibooks.org/wiki/C%2B%2B_Programming/Examples/Hello_world | CC-MAIN-2014-52 | en | refinedweb |
So the method would be to add the argument:
- Code: Select all
{"__builtins__":None}
but then you guys say that is not enough. although all i could think of right now is __import__() and open() are pretty nasty.
So what if you just removed the ability to use packages names, builtins, and keywords. At that point would it be a back door still?
I wouldnt think there is anything left:
- Code: Select all
import sys
import pkgutil
import keyword
pkg_names = []
for i in pkgutil.iter_modules():
pkg_names.append(i[1])
forbidden = pkg_names + dir(__builtins__) + keyword.kwlist
while True:
ok = True
s = input(': ')
for word in forbidden:
if word in s:
print('{} is not allowed'.format(word))
ok = False
if s and ok:
try:
print(eval(s))
except:
print(sys.exc_info())
and my example outputs:
: __import__('subprocess').Popen('ls')
imp is not allowed
subprocess is not allowed
__import__ is not allowed
open is not allowed
import is not allowed
or is not allowed
:
: 1/0
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero',), <traceback object at 0x7fa1f78e6ab8>)
: 1+1
2
: 1+1+1*10
12
: 2*2(2)
(<class 'TypeError'>, TypeError("'int' object is not callable",), <traceback object at 0x7fa1f78e6a28>)
: a + 1
(<class 'NameError'>, NameError("name 'a' is not defined",), <traceback object at 0x7fa1f78c5ef0>)
: a = 1
(<class 'SyntaxError'>, SyntaxError('invalid syntax', ('<string>', 1, 3, 'a = 1')), <traceback object at 0x7fa1f78c5ef0>)
: a + 1
(<class 'NameError'>, NameError("name 'a' is not defined",), <traceback object at 0x7fa1f78e6a28>)
: class Test:;self.a=0
as is not allowed
class is not allowed
: open('test.txt,'w').write('hello')
test is not allowed
open is not allowed
: open('test.txt).read()
test is not allowed
re is not allowed
open is not allowed
: open('test.txt').read()
test is not allowed
re is not allowed
open is not allowed
well 'test' being in there because i have a module name test in home directory. | http://python-forum.org/viewtopic.php?p=5441 | CC-MAIN-2014-52 | en | refinedweb |
25 February 2010 19:20 [Source: ICIS news]
(adds paragraphs 7 to 16)
TORONTO (ICIS news)--Chemical shipments on US railroads rose 13.7% last week from the same time last year, marking their 15th increase in a row and the seventh this year, an industry association said on Thursday.
Chemical railcar loadings for the week ended on 20 February were 29,004, up 3,497 car loads from 25,507 in the same week last year, according to data released by the Association of American Railroads (AAR).
The increase for the week comes after a 5.4% year-over-year increase in the previous week ended on 13 1.6% year-over-year decline in overall weekly railcar shipments for the 19 commodity categories tracked by the ?xml:namespace>
Year-to-date to 20 February,
The AAR also provided comparable chemical railcar shipment data for
Canadian chemical railcar traffic for the week ended on 20 February rose 24.3% to 14,370 from 11,557 in the same week last year.
For the year-to-date period, Canadian shipments were up 19.8% to 102,920 from 85,892 in the same period in 2009.
Mexican weekly chemical rail traffic rose 16.3% to 1,266 from 1,089 in the same week a year earlier.
For the year-to-date period, Mexican shipments were up 12.3% to 7,943 from 7,073 in the same period last year.
For all of
For the year-to-date period to 20 February, overall North American chemical railcar traffic was up 14.6% to 309,060 from 269,651 in the year-earlier period.
Overall, the
From the same week last year, total US weekly railcar traffic for the 19 carload commodity categories fell 1.6% to 273,999 and was down also by 1.6% to 1,856,400 year to date.
For all of North America, total railcar traffic rose 1.3% to 358,553 as increases in Canadian and Mexican shipments offset the decline in | http://www.icis.com/Articles/2010/02/25/9338106/us-weekly-chemical-railcar-traffic-jumps-13.7-year-over-year.html | CC-MAIN-2014-52 | en | refinedweb |
To view parent comment, click here.
To read all comments associated with this story, please click here.
:: I agree with you that the Freecell Solver coverage is a weak point of the essay.
Very weak indeed, first you go talking about portability... and the first thing one finds when downloading the source is autoconf... you dismiss you own point.
And then, autoconf is not enough... for instance it does not build out of the tarball on MacOS. Very simple to fix but still weakens even more the portability argument. Why does not it build? Simple enough, while claiming that C code is portable because there exists the ANSI C spec... you go and do:
# include <malloc.h>
Which is not part of ANSI C. Dear sir, malloc's() prototype is part of <stdlib.h>.
Not only that but all you header files are guarded by macros that start with a double underscore... but all such identifiers are reserved and should not be used by programs (see section 7.1.3 of the spec.) Another portability problem since those identifiers belong to the compiler, not to you.
Member since:
2005-10-10
I agree with you that the Freecell Solver coverage is a weak point of the essay. However, as I note in my site's containing page ( ), I could not convey the fact that as far as Freecell Solver is concerned, not only will writing it in a different language than C will be much slower, but it will also feel wrong. (and it will).
The reason I gave Freecell solver as an example is because it's a project I headed (and thus am very familiar with it and can testify for it), and because I think C is the ideal language for its problem domain. I daresay I was not very successful. | http://www.osnews.com/thread?42794 | CC-MAIN-2014-52 | en | refinedweb |
Scout/Tutorial/3.8/Modular Application
Contents
Introduction
Scout applications can be built as a set of application modules extending a common core application. New modules normally consist of three additional plugins (client, shared, server). In these plugins, new functionality and GUI-components may be added to extend an existing application.
In this tutorial, a new Scout module is added to an existing Scout application. The new module provides an additional outline "Extension".
Setup
We'll start from scratch with a core Scout application and will add a Scout module to it.
Create core application
[Scout View] Create a new Scout project with name
org.example.myapp and postfix
core. This will create bundles with names
org.example.myapp.[client|shared|server].core
Create extension bundles
[Java View] Manually create three bundles (plug-in projects) with names
org.example.myapp.[client|shared|server].extension. The naming pattern is important (the postfix extension should reflect the name of your module, though).
Set-up bundle dependencies
[Java View] Open the manifest editor for all three bundles and define bundle dependencies:
org.example.myapp.client.extension depends on
org.eclipse.scout.rt.client and
org.example.myapp.shared.extension.
org.example.myapp.shared.extension depends on
org.eclipse.scout.rt.shared. Re-export this dependency!
org.example.myapp.server.extension depends on
org.eclipse.scout.rt.server and
org.example.myapp.shared.extension.
Make your bundles Scout bundles
[Scout View] Use menu "Import Plugin..." on the "Scout Projects" folder and import all three extension bundles. Restart Eclipse.
Adding an Extension
Create a desktop extension
[Java View] Create a new class in the
org.example.myapp.client.extension bundle:
org.example.myapp.client.extension.ui.desktop.DesktopExtension which inherits from
org.eclipse.scout.rt.client.ui.desktop.AbstractDesktopExtension.
The class can really look as simple as the following:
package org.example.myapp.client.extension.ui.desktop; import org.eclipse.scout.rt.client.ui.desktop.AbstractDesktopExtension; public class DesktopExtension extends AbstractDesktopExtension { }
Building the extension
[Scout View] The Scout SDK now displays three extension bundles as a separate Scout module. The orange client node also contains a "Desktop-Extension" node. You can now use the Scout SDK to build your module as you would with a normal Scout application. Well, almost. There are a few further caveats: You also need to create a separate
TextProviderService for your extension module (do this in the corresponding folder in the shared bundle). Also, when adding a new outline to the desktop extension, the generated Java code does not compile. You need to fix this manually: In the constructor of the generated
OutlineViewButton change
Desktop.this to
getCoreDesktop() and you should be fine.
Integrate with the core application
We now have a desktop extension class which we will integrate to the core application.
[Java View] Open the manifest editor for the client extension bundle. Export the package containing the desktop extension class (
org.example.myapp.client.extension.ui.desktop). Open the manifest editor for the client core bundle. Import the above package from the client extension bundle.
Adapt the product files for both the client and server products. Add the extension bundles to the dependencies (client and shared bundles in the client product, server and shared in the server product).
In the
Desktop class of the client core bundle, override the method
injectDesktopExtensions() and add an instance of the desktop extension class to the list of extensions.
@Override protected void injectDesktopExtensions(List<IDesktopExtension> desktopExtensions) { DesktopExtension extension = new DesktopExtension(); extension.setCoreDesktop(this); desktopExtensions.add(extension); }
Scout SDK with a Scout module:
Simple demo with an extension outline: | http://wiki.eclipse.org/index.php?title=Scout/Tutorial/3.8/Modular_Application&oldid=333352 | CC-MAIN-2014-52 | en | refinedweb |
Perl.
Tips, Tricks, and Suggestions
If you've worked your way through writing tests for the three examples, here are the approaches I would take. They're not the only ways to test these examples, but they do work. First, here is some background information on what's happening.
Reloading
To test
import() properly, you must understand its
implications. When Perl encounters a
use module;
statement, it executes a two-step process immediately:
BEGIN { require module; module->import(); }
You can subvert both of these processes. To force Perl to reload a
module, you can delete its entry from
%INC. Note that all of
the keys of this special hash represent pathnames in Unix format. For
example, even if you use Windows or VMS or Mac OS 9 or earlier, loading
Filter::Simple successfully should result in
%INC containing a
true value for the key of
Filter/Simple.pm. (You may also want
to use the
delete_package() function of the Symbol module to
clear out the namespace, though beware of the caveats there.) Now you can
require the module again.
Re-importing
Next, you'll have to call
import() manually. It's a normal
class method call, however, so you can provide all of the arguments as you
would to a function or method call.
You can also switch packages, though make sure that you qualify any calls to Test::* module functions appropriately:
package Some::Other::Package; module->import( @args ); main::ok( 1, 'some test label' ); # or ::ok( 1, 'some test label' );
Testing Exports
There are at least two techniques for checking the import of functions.
One is the use of the
defined keyword and the other is through
the
can() class method. For example, tests for Example #1
might be:
use_ok( 'Basic::Exports' ); ok( defined &foo, 'module should export foo()' ) ok( __PACKAGE__->can( 'bar' ), '... and should export bar()' );
To test that these are the right functions, call them as normal and check their return values.
By the way, the presence of the
__PACKAGE__ symbol there
allows this test to take place in other namespaces. If you haven't imported
the
ok() test function into this namespace, remember to
qualify it, import it manually, or alias it so that the test program will
itself run. (It may fail, which is fine, but errors in your tests are
difficult and embarrassing to fix.)
Testing Non-Exports
It's difficult to prove a negative conclusively, but if you reverse the condition of a test, you can have good confidence that the module hasn't provided anything unwanted.
use_ok( 'Optional::Exports' ); ok( ! __PACKAGE__->can( 'foo' ), 'module should not export foo() by default' );
The only tricky part of the tests here is in trying to import functions
again. Call
import() explicitly as a class method of the
module. Switching packages within the test can make this easier; you don't
have to unload the module if you do this.
Testing Weird Exports
The easist way to test an
import() function that relies on
command-line invocation or produces weird side effects that you may not want to
handle in your current program is to launch it as a separate program. There are
plenty of options for this, from
system to
fork and
exec to tricks with pipes and shell redirection. IPC::Open3 is one good
approach, if you want to use it in your test suite:
#! perl use strict; use warnings; use blib; use IPC::Open3; use Test::More tests => 3; use_ok( 'Export::Weird' ); my $pid = open3( undef, my $reader, undef, $^X, '-Mblib', '-MExport::Weird', '-e', '1' ); my @out = <$reader>; is( @out, 1, 'cli invocation should print one line' ); is( $out[0], "Invoked from command-line\n", '... with the right message' );
$^X represents the path to the Perl binary currently
executing this program. The
-Mblib switch loads the
blib module to set
@INC in the program
appropriately. Depending on how you've set up your directories and invoke
this program, you may have to change this. The other commands follow the
invocation scheme given in Example #3.
Conclusion
You should now have several ideas on how to test
import()
methods of various kinds. For more details, read the tests of Pod::ToDemo or Test::Builder, which play
strange games to achieve good test coverage.
If you've found a differently workable approach, I'd like to hear from you. Also, if you have suggestions for another kata (or would like to write one), please let me know.
chromatic is the author of Modern Perl. In his spare time, he has been working on helping novices understand stocks and investing. | http://www.perl.com/pub/2004/12/16/import_kata.html | CC-MAIN-2014-52 | en | refinedweb |
insertion sort
insertion sort write a program in java using insertion sort
bubble sort
bubble sort write a program in java using bubble sort
Extra Storage Merge Sort in Java
Extra Storage Merge Sort in Java
...]
Where n must be even number.
Steps of Merge Sort:
Say...
In this example we are going to sort integer values of an array using
EVEN NUMBERS - Java Interview Questions
EVEN NUMBERS i want program of even numbers?i want source code plz reply? Hi Friend,
Try the following code:
class EvenNumbers... counter = 0;
System.out.println("Even Numbers are:" );
for (int i
bubble sort - Java Beginners
bubble sort how to write program
The bubble-sort algorithm in double... Hi friend,
Bubble Sort program :
public class...[] = {10,5,3,89,110,120,1,8,2,12};
System.out.println("Values Before the sort:\n
even more circles - Java Beginners
even more circles Write an application that compares two circle objects.
? You need to include a new method equals(Circle c) in Circle class. The method compares the radiuses.
? The program reads two radiuses from the user
Selection Sort In Java
Selection Sort In Java
... are going to sort the values of an array using
selection sort.In selection sorting.... Sort the
remaining values by using same steps. Selection sort
Post your Comment | http://www.roseindia.net/discussion/18537-Odd-Even-Transposition-Sort-In-Java.html | CC-MAIN-2014-52 | en | refinedweb |
[ ]
Paulex Yang commented on HARMONY-479:
-------------------------------------
looks fine, thank you, George.
> java.io.FileInputStream and FileOutputStream might cause Finalizer thread suspending
> ------------------------------------------------------------------------------------
>
> Key: HARMONY-479
> URL:
> Project: Harmony
> Type: Bug
> Components: Classlib
> Reporter: Paulex Yang
> Assignee: George Harley
> Attachments: Harmony-479.diff
>
> If one FileInputStream instance is not constructed properly, say, the given file doesn't
exist, the constructor will throw exception but the FileInputStream instance is still necessary
to be garbage collected, and the spec of FileInputStream's finalize() method requires that
close() must be invoked, but the current implementation of FileInputStream.close()(as below)
will causes NullPointerException in Finalizer thread because channel field has not been initialized
yet.
> public void close() throws IOException {
> synchronized (channel) {
> synchronized (this) {
> if (channel.isOpen() && fd.descriptor >= 0) {
> channel.close();
> }
> fd.descriptor = -1;
> }
> }
> }
> This issue applies to FileOutputStream, too. Test case below can reproduce this issue
only in debugger, because it is not easy to get the handle of Finalizer thread. Debugging
the test case to the statement following the System.gc(), the debugger will show that the
Finalizer thread is suspended due to NullPointerException.
> public class FileInputStreamTest {
> public static void main(String[] args) throws Exception{
> FileInputStream is = null;
> try{
> is = new FileInputStream(new File("nonexist"));
> }catch(Exception e){
> System.gc();
> e.printStackTrace();
> }
> }
> }
--
This message is automatically generated by JIRA.
-
If you think it was sent incorrectly contact one of the administrators:
-
For more information on JIRA, see: | http://mail-archives.apache.org/mod_mbox/harmony-commits/200605.mbox/%3C21420440.1148283390148.JavaMail.jira@brutus%3E | CC-MAIN-2014-52 | en | refinedweb |
09 March 2009 15:01 [Source: ICIS news]
LONDON (ICIS news)--Polyethylene (PE) producers have cut back output to such an extent that they are able to push through heavy price increases, in spite of the current weak global economic outlook, sources said on Monday.
“We have been offered increases up to €120/tonne ($152/tonne) by all our suppliers and it doesn’t look as though we will be able to avoid a big part of it at least,” said one buyer.
The sentiment was echoed throughout ?xml:namespace>
“We will have to pay more, that’s clear. But these increases come at a time when our demand is down and the future is very uncertain,” said another buyer.
Sources estimated that PE production rates were running at 70-80%.
PE producers had cut back capacity in a move to secure margin in the polymer business. They had also exported big volumes in January and February, when arbitrage opportunities were high.
“Stocks are at an all-time low,” said a PE producer. “It’s true, some sectors of the market are showing no signs of recovery, but product is tight. The output of ethylene across
Ethylene contract monomer prices had risen by €85/tonne in March, improving ethylene producers’ margins. This increase upstream had exerted more pressure to downstream PE players, however.
Some PE buyers questioned the validity of the new higher monomer price in March.
“I don’t see how they can justify this increase, said one puzzled European PE buyer. “How is this ethylene price settled? Who decides it? Oil has been stable for some weeks now, and there’s been no big change in naphtha between February and March.”
Demand for PE was weaker than in early 2008, but selling sources reported surprisingly good volumes in March.
One producer was even considering further increases in April, in spite of fundamentally poor demand and the start-up of new capacities, mainly in the Middle East, which would inevitably affect
“Even if we get €120/tonne for March, that won’t be enough to get us back to profitability” said the producer.
“We have to cut back further so we don’t end up making non-profitable business in April and May. We will have a tight supply/demand balance and crazily weak demand.”
Buyers were looking for salvation in the new capacities which were now coming on stream, but they had been long in coming, and they were still not offered huge volumes of imported material.
The success of April hikes would depend much on the demand pull from Asia, and continued cutbacks in
New capacities in the Middle East had been planned with
PE producers in
( | http://www.icis.com/Articles/2009/03/09/9198660/europe-pe-producer-cutbacks-curb-availability-to-regain-margin.html | CC-MAIN-2014-52 | en | refinedweb |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.