text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91
values | source stringclasses 1
value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
In particular, I've recently gotten a comment back on my DBI::Pretty module that suggests going beyond this. What I have currently is that the user inputs the SQL using a straightword hash, a keyword and the SQL as key and value, respectively. However, the comment suggested an number of other ways to enter this data, such as from a file, from XML, or other ways. These are certainly not unreasonable in terms of their usability for the intended use of the class, however, I'm concerned with the fact that 1) these will increase the size of the class and 2) the user can 'easily' preparse the needed hash from these items themselves.
Now, I'm thinking that it might be possible to create subModules (DBI::Pretty::ModNameHere), which are only loaded if what the user passes it is anything but a hash but meets the needed requirements, eg:
if ( $arg is a FILEHANDLE ) {
use DBI::Pretty::File;
%hash = read_stuff_from_file( $arg );
} elsif ( $arg is a XML datastream ) {
use DBI::Pretty::XML;
...
} etc.
[download]
use will not work that way, because it is evaluated at compile time and the if at run time. However, you can do the same thing as use by calling require followed by import. For object-oriented modules, the import may not be needed anyway.
Now, as to the scope: If you don't call import at all and it works OK, then you have no issues. The module remains loaded so objets of that class continue to work, and you can refer to DBI::Pretty::File as a class name or scope name subsequently and it's still there. Subsequent require's are harmless, so you could make sure it's in at each point you name it directly.
If the module's import routine "does something", there are two things it can do: it can manipulate the current block scope like use warnings; does. It does this by modifying certain magic variables that are like local in that they pop back to their old value when the user's scope is done.
Normally, non-pragmatic modules "do things" in the import by modifying the symbol table of the caller. That is, add symbols to the caller's package. This will alter your namespace and is totally insensitive to block scope.
I hope that helps,
—John
It seems like what you're trying to do violates modularity in a way that'll cause problems. That is, somebody who wants to extend this to a new format should ideally be able to just whip up a DBI::Pretty::Foo and start using it in scripts. But with this design, any such developer also has to muck with the DBI::Pretty.pm as well, adding an elsif to that bit of (pseudo-)code. This is really undesirable, potentially making it difficult to maintain and use your module.
As an alternative, how about this:
If you do
want the module to be flexible enough to handle a few alternative situations by default without requiring subclasses, just place that if/elsif you've got inside the default parse_input(), but rather than calling alternative use statements, each condition should just invoke different parse_foo_input() methods. Doing it like this -- in parse_input(), not in new() -- shouldn't interfere with the ability for other people to roll their own subclasses.
But the simplest/best thing is probably to just require that anyone using the module must themselves pick the subclass(es) that they want. You can then provide a few basic alternative subclasses along with the main module.
-- Frag.
if ($arg is a FILEHANDLE) {
require DBI::Pretty::File;
%hash = DBI::Pretty::File::read_stuff_from_file ($arg);
}
elsif ($arg is a XML datastream) {
require DBI::Pretty::XML;
%hash = DBI::Pretty::XML::read_stuff_from_xml ($arg);
}
[download]
I do get the feeling you are mixing OOP with procedurial coding
and getting the worst of two worlds. I would either make $arg
an object so I could do $arg -> read_stuff, or I'd make
a function, possible in a separate file (and module), so that I could
do %hash = read_stuff ($arg) and put all the reading stuff
from DBI::Pretty::File and DBI::Pretty::XML
and other modules in there.
-- Abigail
My savings account
My retirement account
My investments
Social Security
Winning the lottery
A Post-scarcity economy
Retirement?! You'll have to pull the keyboard from my cold, dead hands
I'm independently wealthy
Other
Results (75 votes),
past polls | http://www.perlmonks.org/index.pl?node_id=94652 | CC-MAIN-2014-42 | refinedweb | 742 | 55.78 |
/* malloc with out of memory checking. Copyright (C) 2001-2004 /* Defined in xmalloc.c. */ /* Allocate SIZE bytes of memory dynamically, with error checking. */ extern void *xmalloc (size_t size); /* Allocate memory for NMEMB elements of SIZE bytes, with error checking. */ extern void *xcalloc (size_t nmemb, size_t size); /* Change the size of an allocated block of memory PTR to SIZE bytes, with error checking. If PTR is NULL, run xmalloc. */ extern void *xrealloc (void *ptr, size_t size); /* This function is always triggered when memory is exhausted. It is in charge of honoring the three previous items. This is the function to call when one wants the program to die because of a memory allocation failure. */ extern void xalloc_die (void) #if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5)) && !__STRICT_ANSI__ __attribute__ ((__noreturn__)) #endif ; /* Defined in xstrdup.c. */ /* Return a newly allocated copy of STRING. */ extern char *xstrdup (const char *string); /* */ | http://opensource.apple.com/source/libiconv/libiconv-30/libiconv/srclib/xalloc.h | CC-MAIN-2015-48 | refinedweb | 145 | 68.87 |
Hey,
I'm having problems with a DFS Namespace that does not connect to a correct DFS Target. The following setup I have:
When an Houston User try to access the DFS Namespace it always connect to the DFS target in Bruxelles. Anyone knowns what this problem could be? Even when I configure the DFS Target folder to “Exclude
targets outside of the client's site.” . If I check the properties of a folder in DFS Namespace and go to the tab DFS I only see the Bruxelles target folder and not the Houston target folder.
Is this because there is no domain controller in Houston and no DNS server available?
Hi,
I believe, Yes, reason being, there are no DNS/DC available at your Houston site. Your client is already authenticating with DC from Bruxelles,hence it would re-direct there itself.
If you are replicating the data via replication schedules or any 3rd party replication s/w, you can keep them in synch rite, if it is a small site, you can ask users to target the respective servers directly.. Just a suggestion..
Regards, Server Engineer - Server Support
Sorry for the late response.
According to the DFS Referral rules it should stay in the lower costs which is the Houston Site itself. But if the requirements are that there must be a DC and DNS at the Houston Site to make the target folder able to work then I probably geing to built
a Read Only DC and a DNS server.
Using an unc path directly to the target folder in Houston works of course but we have created some scripts that directs to the DFS namespace. Probably removing the links will resolve the problem as well.
If someone else still have a suggestion please tell
Thanks!
Microsoft is conducting an online survey to understand your opinion of the Technet Web site. If you choose to participate, the online survey will be presented to you when you leave the Technet Web site.
Would you like to participate? | http://social.technet.microsoft.com/Forums/windowsserver/en-US/deb78872-d123-4ee3-925d-1bbfe367a08f/dfs-wrong-active-target?forum=winserverfiles | CC-MAIN-2014-35 | refinedweb | 339 | 70.63 |
- Code: Select all
#!/usr/bin/env python
#DONT LOOK AT MY FUCKING SOURCE CODE!!!
print ("This is a calculator.")
print ("The possible functions are as follows:")
print ("1: add, 2: subtract, 3: multiply, 4: divide, 5: exponent")
#For all intentive purposes 'poop' is now an object which is the root of all mathmatical operations.
class poop:
amount_of_corn = 0
viscosity = 0
yaw = 0
shades_of_brown = 0
quality_of_service = 0
density = 0
consistancy = 0
boyancy = 0
girth = 0
stank = 0
steam = 0
def choice(self):
turd= int(input("Enter what function you would like: "))
if turd == (add):
corn= int(input("Enter the first number")
visc= int(input("Enter the second number")
timmy.poop = amount_of_corn = corn
dong.poop = viscosity = visc
print (b + c)
As you can see this is not the standard way to program a calculator but i would like to ease my way into oop. Although after the inevidable wiseass comments i would appreciate if someone could offer input that would assist this to function. corn and visc are strings. | http://www.python-forum.org/viewtopic.php?p=1035 | CC-MAIN-2015-06 | refinedweb | 167 | 62.38 |
Qt Mac error
hii,
I am making a Qt application for MAC OSX 10.6.2(Snow Leopard). My problem is, as soon as I run the application,I gets the following warnings..can anyone help me for this..
Thanks in advance..
“2011-08-24 12:00:39.295 MyApp[379:80f] *** __NSAutoreleaseNoPool(): Object 0×6a89090 of class NSCFArray autoreleased with no pool in place – just leaking”
“QCocoaView handleTabletEvent: This tablet device is unknown (received no proximity event for it). Discarding event.”
The first one is a "known bug": but should have been fixed in a new version of Qt.
The second one seems to indicate that you have a tablet device connected by can't be recognized. What machine do you run your OS in? What Qt version do you use?
- paladin_knight
I never know that you can develop Apple Application using Qt with Cocoa Framework. How to do that?
You can't. The two error messages above came from usual Qt applications.
I am using Mac OS X 10.6.2 on virtual box and I am using Qt 4.7.4.
Using VMWare? Then this is also a known problem. See "this link.":
In the link you had given, there they had mention about a file named qapplication_mac.mm, in that I have to do some changes.But i could not find that file in my MAC, where is it located? do you know anything about it?
and also do you know anything about the following error,
@1. “2011-08-24 12:00:39.295 MyApp[379:80f] *** __NSAutoreleaseNoPool(): Object 0×6a89090 of class NSCFArray autoreleased with no pool in place – just leaking”@
qapplication_mac.mm should be in the source of Qt. By changing the lines, you need to download the source code of Qt, modify the file mentioned above, and compile/install the Qt libraries by yourself. Not exactly an easy thing to do if you don't have some experience.
I don't have a VM running Mac OS X, so there's little else I can provide on this one, but the workaround mentioned by Alessandro Wilner in the bug report might be worth a try.
Also I would recommend you try to reveal this problem to VMWare, and let them fix this problem.
The "leaking" problem should have been fixed after 4.6.2, so if it's coming back again, you can just "submit another bug report on this issue":.
[quote author="paladin_knight" date="1316019039"]I never know that you can develop Apple Application using Qt with Cocoa Framework. How to do that?[/quote]
@
#qt_cocoa.pro****
QT += core gui
TARGET = qt_cocoa
TEMPLATE = app
SOURCES += main.cpp
dialog.mm
HEADERS += dialog.h
LIBS += -framework Cocoa
@
@
//dialog.h****
#ifndef DIALOG_H
#define DIALOG_H
#include <QtGui/QDialog>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
};
#endif // DIALOG_H
@
@
//dialog.mm*****
#include "dialog.h"
#import <Cocoa/Cocoa.h>
Dialog::Dialog(QWidget *parent)
: QDialog(parent)
{
NSLog(@"aaaaa");
NSRunAlertPanel(@"Fido", @"Rover is %d", @"Rex", @"Spot", nil, 8);
}
Dialog::~Dialog()
{
}
@
@
//main.cpp**
#include <QtGui/QApplication>
#include "dialog.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}
@
I actually tried to use Qt Widgets in an NSApplication after reading @paladin_knight's post. But I couldn't get it work after like 30 minutes, and I gave up. =p Didn't thought about doing it the other way around like you did.
Yep! Same question: Qt under cocoa? And QML under IOS ??? Is there a reliable way without spend days to setup a decent dev env?
[quote author="Alicemirror" date="1316595981"]And QML under IOS ???[/quote]
QML is Qt, so this has been discussed "here": and "here":
@Volker: in theory it is true, but as I have read (and not experimented yet) I know that the Qt porting for Android is Qt but doesn't include the QML declarative while under IOS I had notice of some portings of QML UI and not Qt at all.
That discussion should be left to a new thread then, as I can see no relation to the NSAutoreleaseNoPool problem?!?
True, I am not Moderator of this forum, only Italian / Spanish and Mobile and embedded. If you can, please move it. Thanks.
I'm reluctant to split off an answer that is at least partially related to the original topic, so better just start a new thread.
If is possible to duplicate some posts, else if you want to split I think that the best point is after the answer of @uranusjr...
I'm hoping someone can verify that this "suggested code change": does in fact fix the "tablet device is unknown" error; I'd prefer to be sure before I go to the hassle of recompiling the libraries. Alternatively is there some way to implement Alessandro Wilner's (same page, under "comments") USB mouse workaround in VirtualBox, as opposed to VMware? | https://forum.qt.io/topic/8885/qt-mac-error | CC-MAIN-2018-09 | refinedweb | 817 | 66.54 |
Introduction
Which algorithm do you use for object detection tasks? I have tried out quite a few of them in my quest to build the most precise model in the least amount of time. And this journey, spanning multiple hackathons and real-world datasets, has usually always led me to the R-CNN family of algorithms.
It has been an incredible useful framework for me, and that’s why I decided to pen down my learnings in the form of a series of articles. The aim behind this series is to showcase how useful the different types of R-CNN algorithms are. The first part received an overwhelmingly positive response from our community, and I’m thrilled to present part two!
In this article, we will first briefly summarize what we learned in part 1, and then deep dive into the implementation of the fastest member of the R-CNN family – Faster R-CNN. I highly recommend going through this article if you need to refresh your object detection concepts first: A Step-by-Step Introduction to the Basic Object Detection Algorithms (Part 1).
Part 3 of this series is published now and you can check it out here: A Practical Guide to Object Detection using the Popular YOLO Framework – Part III (with Python codes)
We will work on a very interesting dataset here, so let’s dive right in!
Table of Contents
- A Brief Overview of the Different R-CNN Algorithms for Object Detection
- Understanding the Problem Statement
- Setting up the System
- Data Exploration
- Implementing Faster R-CNN
A Brief Overview of the Different R-CNN Algorithms for Object Detection
Let’s quickly summarize the different algorithms in the R-CNN family (R-CNN, Fast R-CNN, and Faster R-CNN) that we saw in the first article. This will help lay the ground for our implementation part later when we will predict the bounding boxes present in previously unseen images (new data).
R-CNN extracts a bunch of regions from the given image using selective search, and then checks if any of these boxes contains an object. We first extract these regions, and for each region, CNN is used to extract specific features. Finally, these features are then used to detect objects. Unfortunately, R-CNN becomes rather slow due to these multiple steps involved in the process.
R-CNN
Fast R-CNN, on the other hand, passes the entire image to ConvNet which generates regions of interest (instead of passing the extracted regions from the image). Also, instead of using three different models (as we saw in R-CNN), it uses a single model which extracts features from the regions, classifies them into different classes, and returns the bounding boxes.
All these steps are done simultaneously, thus making it execute faster as compared to R-CNN. Fast R-CNN is, however, not fast enough when applied on a large dataset as it also uses selective search for extracting the regions.
Fast R-CNN
Faster R-CNN fixes the problem of selective search by replacing it with Region Proposal Network (RPN). We first extract feature maps from the input image using ConvNet and then pass those maps through a RPN which returns object proposals. Finally, these maps are classified and the bounding boxes are predicted.
Faster R-CNN
I have summarized below the steps followed by a Faster R-CNN algorithm to detect objects in an image:
- Take an input image and pass it to the ConvNet which returns feature maps for the image
- Apply Region Proposal Network (RPN) on these feature maps and get object proposals
- Apply ROI pooling layer to bring down all the proposals to the same size
- Finally, pass these proposals to a fully connected layer in order to classify any predict the bounding boxes for the image
What better way to compare these different algorithms than in a tabular format? So here you go!
Now that we have a grasp on this topic, it’s time to jump from the theory into the practical part of our article. Let’s implement Faster R-CNN using a really cool (and rather useful) dataset with potential real-life applications!
Understanding the Problem Statement
We will be working on a healthcare related dataset and the aim here is to solve a Blood Cell Detection problem. Our task is to detect all the Red Blood Cells (RBCs), White Blood Cells (WBCs), and Platelets in each image taken via microscopic image readings. Below is a sample of what our final predictions should look like:
The reason for choosing this dataset is that the density of RBCs, WBCs and Platelets in our blood stream provides a lot of information about the immune system and hemoglobin. This can help us potentially identify whether a person is healthy or not, and if any discrepancy is found in their blood, actions can be taken quickly to diagnose that.
Manually looking at the sample via a microscope is a tedious process. And this is where Deep Learning models play such a vital role. They can classify and detect the blood cells from microscopic images with impressive precision.
The full blood cell detection dataset for our challenge can be downloaded from here. I have modified the data a tiny bit for the scope of this article:
- The bounding boxes have been converted from the given .xml format to a .csv format
- I have also created the training and test set split on the entire dataset by randomly picking images for the split
Note that we will be using the popular Keras framework with a TensorFlow backend in Python to train and build our model.
Setting up the System
Before we actually get into the model building phase, we need to ensure that the right libraries and frameworks have been installed. The below libraries are required to run this project:
- pandas
- matplotlib
- tensorflow
- keras – 2.0.3
- numpy
- opencv-python
- sklearn
- h5py
Most of the above mentioned libraries will already be present on your machine if you have Anaconda and Jupyter Notebooks installed. Additionally, I recommend downloading the requirement.txt file from this link and use that to install the remaining libraries. Type the following command in the terminal to do this:
pip install -r requirement.txt
Alright, our system is now set and we can move on to working with the data!
Data Exploration
It’s always a good idea (and frankly, a mandatory step) to first explore the data we have. This helps us not only unearth hidden patterns, but gain a valuable overall insight into what we are working with. The three files I have created out of the entire dataset are:
-.
Let’s read the .csv file (you can create your own .csv file from the original dataset if you feel like experimenting) and print out the first few rows. We’ll need to first import the below libraries for this:
# importing required libraries import pandas as pd import matplotlib.pyplot as plt %matplotlib inline from matplotlib import patches
# read the csv file using read_csv function of pandas train = pd.read_csv(‘train.csv’) train.head()
There are 6 columns in the train file. Let’s understand what each column represents:
- image_names: contains the name of the image
- cell_type: denotes the type of the cell
- xmin: x-coordinate of the bottom left part of the image
- xmax: x-coordinate of the top right part of the image
- ymin: y-coordinate of the bottom left part of the image
- ymax: y-coordinate of the top right part of the image
Let’s now print an image to visualize what we’re working with:
# reading single image using imread function of matplotlib image = plt.imread('images/1.jpg') plt.imshow(image)
This is what a blood cell image looks like. Here, the blue part represents the WBCs, and the slightly red parts represent the RBCs. Let’s look at how many images, and the different type of classes, there are in our training set.
# Number of unique training images train['image_names'].nunique()
So, we have 254 training images.
# Number of classes train['cell_type'].value_counts()
We have three different classes of cells, i.e., RBC, WBC and Platelets. Finally, let’s look at how an image with detected objects will look like:
fig = plt.figure() #add axes to the image ax = fig.add_axes([0,0,1,1]) # read and plot the image image = plt.imread('images/1.jpg') plt.imshow(image) # iterating over the image for different objects for _,row in train[train.image_names == "1.jpg"].iterrows(): xmin = row.xmin xmax = row.xmax ymin = row.ymin ymax = row.ymax width = xmax - xmin height = ymax - ymin # assign different color to different classes of objects if row.cell_type == 'RBC': edgecolor = 'r' ax.annotate('RBC', xy=(xmax-40,ymin+20)) elif row.cell_type == 'WBC': edgecolor = 'b' ax.annotate('WBC', xy=(xmax-40,ymin+20)) elif row.cell_type == 'Platelets': edgecolor = 'g' ax.annotate('Platelets', xy=(xmax-40,ymin+20)) # add bounding boxes to the image rect = patches.Rectangle((xmin,ymin), width, height, edgecolor = edgecolor, facecolor = 'none') ax.add_patch(rect)
This is what a training example looks like. We have the different classes and their corresponding bounding boxes. Let’s now train our model on these images. We will be using the keras_frcnn library to train our model as well as to get predictions on the test images.
Implementing Faster R-CNN
For implementing the Faster R-CNN algorithm, we will be following the steps mentioned in this Github repository. So as the first step, make sure you clone this repository. Open a new terminal window and type the following to do this:
git clone
Move the train_images and test_images folder, as well as the train.csv file, to the cloned repository. In order to train the model on a new dataset, the format of the input should be:
filepath,x1,y1,x2,y2,class_name
where,
-
We need to convert the .csv format into a .txt file which will have the same format as described above. Make a new dataframe, fill all the values as per the format into that dataframe, and then save it as a .txt file.
data = pd.DataFrame() data['format'] = train['image_names'] # as the images are in train_images folder, add train_images before the image name for i in range(data.shape[0]): data['format'][i] = 'train_images/' + data['format'][i] # add xmin, ymin, xmax, ymax and class as per the format required for i in range(data.shape[0]): data['format'][i] = data['format'][i] + ',' + str(train['xmin'][i]) + ',' + str(train['ymin'][i]) + ',' + str(train['xmax'][i]) + ',' + str(train['ymax'][i]) + ',' + train['cell_type'][i] data.to_csv('annotate.txt', header=None, index=None, sep=' ')
What’s next?
Train our model! We will be using the train_frcnn.py file to train the model.
cd keras-frcnn python train_frcnn.py -o simple -p annotate.txt
It will take a while to train the model due to the size of the data. If possible, you can use a GPU to make the training phase faster. You can also try to reduce the number of epochs as an alternate option. To change the number of epochs, go to the train_frcnn.py file in the cloned repository and change the num_epochs parameter accordingly.
Every time the model sees an improvement, the weights of that particular epoch will be saved in the same directory as “model_frcnn.hdf5”. These weights will be used when we make predictions on the test set.
It might take a lot of time to train the model and get the weights, depending on the configuration of your machine. I suggest using the weights I’ve got after training the model for around 500 epochs. You can download these weights from here. Ensure you save these weights in the cloned repository.
So our model has been trained and the weights are set. It’s prediction time! Keras_frcnn makes the predictions for the new images and saves them in a new folder. We just have to make two changes in the test_frcnn.py file to save the images:
- Remove the comment from the last line of this file:
cv2.imwrite(‘./results_imgs/{}.png’.format(idx),img)
- Add comments on the second last and third last line of this file:
# cv2.imshow(‘img’, img)
# cv2.waitKey(0)
Let’s make the predictions for the new images:
python test_frcnn.py -p test_images
Finally, the images with the detected objects will be saved in the “results_imgs” folder. Below are a few examples of the predictions I got after implementing Faster R-CNN:
Result 1
Result 2
Result 3
Result 4
End Notes
R-CNN algorithms have truly been a game-changer for object detection tasks. There has suddenly been a spike in recent years in the amount of computer vision applications being created, and R-CNN is at the heart of most of them.
Keras_frcnn proved to be an excellent library for object detection, and in the next article of this series, we will focus on more advanced techniques like YOLO, SSD, etc.
If you have any query or suggestions regarding what we covered here, feel free to post them in the comments section below and I will be happy to connect with you!
139 Comments
Thanks for article.
Most of object detection algorithms fail if size of object to be detected is very small and with varying size. For example detection of small cracks on metal surface. What is your view on this? Any advice and best possible approach?
Hi,
I believe Faster RCNN works good enough for small objects as well. Currently, I am working on YOLO and SSD and will share my learnings on how they deal with small objects.
hi pulkit ,
i have trained my data but while predicting i am getting images with no bounding boxex, can you tell me the reason??
Hi Manoj,
Which dataset are you using to train the model? Are the annotations and classes correctly defined? And what is the number of epochs that you have used? Also please share the dataset so that I can look into it and help you in a better way.
Hi, Pulkit.. i have 4 images for training, each one consisting of many objects of same class. Then i have 3 images for testing, containing some number of objects of all 4 classes. I want to build this classifier and thought to train Faster RCNN, but facing trouble in preparing Training.csv file and training model further. can you help me with it.
Hi Arvind,
Since you have only 4 images for training, the model might not be able to learn the features and it will not perform well. Also, can you specify what is the trouble that you are facing in creating the training.csv file?
Hey Pulkit,
I am a Freshman at UIUC studying CS and one of my projects is in the same domain. Would it be possible to connect with you and talk more about this?
Hi Vishnu,
You can ask any query related to this project here. I will try my best to respond to them.
Hi, Pulkit,
Thanks for this wonderful tutorial !
I have downloaded the BCCD dataset, but there is no train_images and test_images folder, as well as the train.csv file in it, shall I generate them by myself?
Thank you!
Hi,
Yes, you have to create the training set, testing set and csv file by yourself. You can divide the images into training and testing set in any ratio.
Thank you for your prompt reply!
Best regards.
The dataset that you have provided, it doesn’t correspond with your example. Can you provide the right source?
Hi Toni,
The original dataset is available on GitHub, link for the same is provided in the article. I have made some changes in that dataset and have mentioned the changes as well. You just have to convert the dataset in csv format.
Can you please provide the code to do that? Thank you
Hi,
I have shared the code in the previous comments. Please check.
I am having issues reading the data which is in .rec format
Hi Saurabh,
You can convert the coordinates to csv format and then read it in python.
Been able to follow your blog so far. Now stuck at preparing input data. Need more help to convert data as in github to familiar csv formats.
Without it not able to proceed with the notebook
Hi Sanjoy,
I have used the below given code to convert the bounding boxes into csv file:
%pylab inline
import os, sys, random
import xml.etree.ElementTree as ET
from glob import glob
import pandas as pd
from shutil import copyfile
annotations = glob('BCCD/Annotations/*.xml')
df = []
cnt = 0
for file in annotations:
prev_filename = file.split('/')[-1].split('.')[0] + '.jpg'
filename = str(cnt) + '.jpg'
row = []
parsedXML = ET.parse(file)
for node in parsedXML.getroot().iter('object'):
blood_cells = node.find('name').text
xmin = int(node.find('bndbox/xmin').text)
xmax = int(node.find('bndbox/xmax').text)
ymin = int(node.find('bndbox/ymin').text)
ymax = int(node.find('bndbox/ymax').text)
row = [prev_filename, filename, blood_cells, xmin, xmax,
ymin, ymax]
df.append(row)
cnt += 1
data = pd.DataFrame(df, columns=['prev_filename', 'filename', 'cell_type',
'xmin', 'xmax', 'ymin', 'ymax'])
data[['filename', 'cell_type', 'xmin', 'xmax', 'ymin', 'ymax']].to_csv('blood_cell_detection.csv', index=False)
Dear Pulkit,
Thanks a ton for the code. Ran it. But it is not populating the variable based on
‘annotations = glob(…..)’.
Leading to:
len(annotations) = 0.
Hence the blood_cell_detection.csv it is creating is with only the header. No data is coming in.
I must be doing some silly mistake. But not able to catch it. Got stuck again. What am I doing wrong?
Sorry for bothering you again.
Regards
Sanjoy.
Hi Sanjoy,
Make sure to give the correct location of .xml files inside glob(). Replace ‘BCCD/Annotations/*.xml’ with the location where your .xml files are saved.
Thank you Pulkit for prompt response again.
Problem is elsewhere now. In short, do not have the xml and jpeg files yet at local folder.
Have downloaded train.rec and val.rec. Not been able to extract .xml and .jpeg files out of them.
So problem is stated as:
1. How to extract xml and jpeg files from .rec files?
2. Or, is there a way to download files directly from respective github folders? Been searching stackoverflow. But not found a way
It appears from other posts, solution will help a few others like me too.
Thank you in advance
Sanjoy
Hi Sanjoy,
You can clone this GitHub repository which contains the JPEG Images and annotations inside the BCCD folder.
Hello PULKIT SHARMA,
Thank you for great post. Just making a note here you have typo in above code.
xmin = int(node.find(‘bndbox/ymin’).text) should be
ymin = int(node.find(‘bndbox/ymin’).text). and same for all four.
I don’t know is there any purpose of this or just a typo.
But yeah thank you so much for a great post.
Hi Mihir,
Thanks for pointing it out. That’s a good catch and I have updated the code.
Thank you, Pulkit, for your most excellent and informative post. I’ve been having troubles getting your XML to CSV code to ouput correctly and I was hoping you might edit the code to include the correct indentations as well as an addition line that writes the parsed data to file.
Hi Chris,
Can you please tell me what is the error that you are getting?
Hi Pulkit,
The output does not appear to be correct (I get 8 fields rather than 6 among other apparent output problems):
prev_filename filename cell_type xmin xmax ymin ymax
0 BloodImage_00000.jpg 0.jpg WBC 260 491 177 376
1 BloodImage_00000.jpg 0.jpg RBC 78 184 336 435
2 BloodImage_00000.jpg 0.jpg RBC 63 169 237 336
3 BloodImage_00000.jpg 0.jpg RBC 214 320 362 461
4 BloodImage_00000.jpg 0.jpg RBC 414 506 352 445
5 BloodImage_00000.jpg 0.jpg RBC 555 640 356 455
6 BloodImage_00000.jpg 0.jpg RBC 469 567 412 480
7 BloodImage_00000.jpg 0.jpg RBC 1 87 333 437
8 BloodImage_00000.jpg 0.jpg RBC 4 95 406 480
9 BloodImage_00000.jpg 0.jpg RBC 155 247 74 174
10 BloodImage_00000.jpg 0.jpg RBC 11 104 84 162
11 BloodImage_00000.jpg 0.jpg RBC 534 639 39 139
12 BloodImage_00000.jpg 0.jpg RBC 547 640 195 295
13 BloodImage_00000.jpg 0.jpg RBC 388 481 11 111
14 BloodImage_00000.jpg 0.jpg RBC 171 264 175 275
15 BloodImage_00000.jpg 0.jpg RBC 260 374 1 83
16 BloodImage_00000.jpg 0.jpg RBC 229 343 91 174
17 BloodImage_00000.jpg 0.jpg RBC 69 184 144 235
18 BloodImage_00000.jpg 0.jpg RBC 482 594 131 230
19 BloodImage_00000.jpg 0.jpg RBC 368 464 89 176
20 BloodImage_00001.jpg 20.jpg WBC 68 286 315 480
21 BloodImage_00001.jpg 20.jpg RBC 346 446 361 454
22 BloodImage_00001.jpg 20.jpg RBC 53 146 179 299
23 BloodImage_00001.jpg 20.jpg RBC 449 536 400 480
24 BloodImage_00001.jpg 20.jpg RBC 461 548 132 212
25 BloodImage_00001.jpg 20.jpg RBC 454 541 295 375
26 BloodImage_00001.jpg 20.jpg RBC 417 508 283 383
27 BloodImage_00001.jpg 20.jpg RBC 278 369 342 451
28 BloodImage_00001.jpg 20.jpg RBC 545 636 62 159
29 BloodImage_00001.jpg 20.jpg RBC 485 576 91 188
… … … … … … … …
4858 BloodImage_00409.jpg 4851.jpg RBC 169 261 79 170
4859 BloodImage_00409.jpg 4851.jpg RBC 2 93 1 83
Hi Chris,
You can remove the column named ‘prev_filename’.
Hi,
Thanks for this tutorial !
Do you have installed the last package of tensorflow here ?
Thanks
Laurent cESARO
Hi,
Yes, I have the latest version of Tensorflow. You can install the latest version too.
Very well documented all your learnings, thanks for sharing. Keep it going, all the best.
Thank You!
Hi,
I’m wondering if it’s possible to load existing weights from a pre-trained model such as Imagenet?
Also how does the faster RCNN model compare to the Mask-RCNN model?
Cheers
Michael
Hi Michael,
We can use weights from any of the model which is trained for object detection.
Faster RCNN predicts the bounding box coordinates whereas, Mask RCNN is used for pixel-wise predictions. So, it totally depends on the type of problem that you want to solve. In my opinion, both of these algorithms are good and can be used depending on the type of problem in hand.
Hi Pulkit,
Can you please also share the config file generated after training the model? Test_frcnn is looking for config file as well.
Hi Shilpa,
You can download the config file from this link.
Thanks for the article. I am a beginner in ML / DS field.
Can I use this code to detect the Region of Interest (ROI) from Glaucoma images?
Hi Sonal,
Yes, you can use this for your own dataset as well. You just have to make a .txt file in the same format as I have used.
Thank you Pulkit. It is working finally. Thanks for all your help.
Hi ,
Thanks for the article.
I am not able to train model on tensorflow-gpu. I get error
“ValueError: Shape must be rank 1 but is rank 0 for ‘bn_conv1_7/Reshape_4’ (op: ‘Reshape’) with input shapes: [1,1,1,64], [].”
Keras version on server : 2.2.4
Tensorflow version on server: 1.11.0
The training works fine without any issues on cpu machine.
Please help.
Hi Hareesh,
I have used the following version of Keras and Tensorflow:
Keras – 2.2.0
Tensorflow – 1.8.0
And the codes run smoothly without any error.
I met the same problem as yours.
After I use Keras – 2.2.0 and Tensorflow – 1.8.0, the problem is fixed.
Bug in Keras 2.2.4, this works until Keras 2.2.2 it seems
Hi Hareesh,
Did you manage to get it to run on Keras 2.2.4 ? I am facing the same issue. I have Keras 2.2.4 and Tensorflow 1.13. I can downgrade Keras to 2.2.0, but I am unable to compile Tensorflow 1.8.0 from the source code. So backtracking is not possible for me.
How did you solve the issue ?
How do we know when to stop training? For very small object detections any parameters to tune? Any anchor sizes, RPN to change? Thanks
Hi,
You can make a validation set from the training data and if the validation accuracy stops to increase or if it starts to decrease, you can say that the model is overfitting and you can stop the training at that point.
Regarding the hyperparameter tuning, you can always try different set of hyperparameters to check whether they improve the model performance. There is no clear-cut answer to what hyperparameters should be used. You always have to try a range of hyperparameters and select the one which gives highest performance. Same goes with anchor sizes and RPN.
Thanks !!
Hi ,
Can you tell us how did you arrive at the img_channel_mean, classifier_regr_std values and whats is the need of it?
# image channel-wise mean to subtract
self.img_channel_mean = [103.939, 116.779, 123.68]
# scaling the stdev
Similarly for self.classifier_regr_std = [8.0, 8.0, 4.0, 4.0]
Hi Hareesh,
These are the pre-processing steps which make the training faster. These are used to normalize the data. The values are taken by the people who have created the keras_frcnn library. They must have done experiments using different values and found this set as the best. You can try to change these values as well.
>>.
>>>
Even tough you have provided the code to convert xml to csv, I’m not sure if I have reliably run it and I have a valid data. Can you please provide the exact data set with the exact train/test ratio so I can get results results identical to yours?
Hi Asad,
Once you have the complete csv file, you can divide it randomly in a ratio of say 70:30 (train:test) or 80:20 or any other ratio you want. Then you will have two different csv files, say train.csv and test.csv. Finally, for the images in train.csv, put them in train folder and images in test.csv file should be copied to test folder. Then you can run the model.
Hi Pulkit,
Can you please upload all the data files which you have exactly used for this and share?
I am facing issues with splitting the datasets to train/test dataset. Thanks !
Hi Pankaj,
Can you please tell me what is the issue that you facing in splitting the data? Once you have the csv file (which you will get after running the code provided in the previous comments) you can randomly pick few images for the training and rest for the test. Please let me know what is the issue that you are facing so that I can help you to overcome it.). then, we divide them into train and test.
Hi saadiq,
In real life scenarios, we do not have the true labels for the images. Test set is similar to that. We train our model and then predict on test images. You can split the train set given to you into training and validation set. First train your model on training set, get predictions for the validation set, and if you are satisfied with the results, use that model for predicting labels for test images.
import os, sys, random
import xml.etree.ElementTree as ET
from glob import glob
import pandas as pd
from shutil import copyfile
import pandas as pd
annotations = glob(‘*.xml’)
df = pd.DataFrame(columns=[‘prev_filename’, ‘filename’, ‘cell_type’,’xmin’, ‘xmax’, ‘ymin’, ‘ymax’])
cnt = 0
for file in annotations:
prev_filename = file.split(‘/’)[-1].split(‘.’)[0] + ‘.jpg’
filename = str(cnt) + ‘.jpg’
row = []
parsedXML = ET.parse(file)
for node in parsedXML.getroot().iter(‘object’):
blood_cells = node.find(‘name’).text
xmin = int(node.find(‘bndbox/xmin’).text)
xmax = int(node.find(‘bndbox/xmax’).text)
ymin = int(node.find(‘bndbox/ymin’).text)
ymax = int(node.find(‘bndbox/ymax’).text)
row = [prev_filename, filename, blood_cells, xmin, xmax,ymin, ymax]
df=df.append({‘prev_filename’:prev_filename,’filename’:filename,’cell_type’:blood_cells,’xmin’:xmin, ‘xmax’:xmax, ‘ymin’:ymin, ‘ymax’:ymax},ignore_index=True)
cnt += 1
#data = pd.DataFrame(df, columns=[‘prev_filename’, ‘filename’, ‘cell_type’,
#’xmin’, ‘xmax’, ‘ymin’, ‘ymax’])
#data[[‘filename’, ‘cell_type’, ‘xmin’, ‘xmax’, ‘ymin’, ‘ymax’]].to_csv(‘blood_cell_detection.csv’, index=False)
df.to_csv(‘blood_cell_detection.csv’, index=False)
Hi Pulkit,
The command ran : python test_frcnn.py -p test_images successfully , but did not detect any bounding boxes in the image. Can you please suggest what is wrong ?
Thanks,
Pankaj
Hi Pankaj,
Make sure you have used the weights provided in the article. Or else you can train your model again and then make predictions for test_images.
Hi!
Great article!
About weights that you make available, you know what the loss, the accuracy, time of the treining and you hardware that you used ?
Thank you !
Hi Otavio,
The overall loss when I trained the model was around 2.3 The model was trained for more than 2 hours for 1000 epochs and I was using a GPU with 12 cores and 16 GB RAM
I don’t understand, I am using a 2 GPU’s (Titan X 12G and Geforce GTX 1080 ti) and I took around 4 hours for 20 epochs.
Did you change anything in files like config.py or train_frccn,py?
I don’t know where I am going wrong
I would like to ask, if you can post the complete codes that you used for train this model in github or in other plataform, because I’m not knowing how train the model very well
Thank you!
Hi,
Thanks for this article it is great !
As I use the model on big images (4000×3000), the training is very long. I am using one Tesla K80 GPU, but I could find a way to train on multiple GPUs. Is there a way to do that ? How should the code be changed ?
I have an other question about validation set. A validation set is created in train_frcnn but never I can not see where it is used after in the code. Am I wrong or is there a problem with that part ?
Regards
Hi,
I am not yet aware of how to use multiple GPUs for training the model. I will look for it and will let you know how to do that.
Regarding the validation set, they have passed the test images into the validation set as they have true labels and bounding boxes for test images. Whereas, in our case we do not have true labels for test images so we have not passed it in validation set.
Thanks ! I tried with keras multi_gpu library but didi not get good results.
Hi!
Great Article!
How I load your weights for training more epochs?
Thanks
Hi Otavio,
I think you have to retrain the model from the beginning. I am not aware of how to use the model weights and then start training on top of them. I will search for it and will let you know if any solution is found.
When I am running the code:
python3 train_frcnn.py -o simple -p annotate3.txt;
following error is coming:
Using TensorFlow backend.
Traceback (most recent call last):
File “train_frcnn.py”, line 15, in
from keras_frcnn import config, data_generators
ModuleNotFoundError: No module named ‘keras_frcnn’
Also showing ‘keras_frcnn’ is not available when trying to install/import it explicitly.
Hi Tanuj,
You are getting this error because it might be possible that you have not cloned the keras_frcnn GitHub repository. You have to clone this repository before running the script.
Hi sir, thank you for this article, pleas can i apply this code on facial component detection?
Hi,
Yes! You can apply this algorithm for facial component detection. For that you first have to train your model on facial components. Weights used in this model will not help in detecting facial components as this model is trained on different dataset. So, first train your model on facial components and then you can use those weights to detect facial components in new set of images.
Hi Pulkit – thanks for this – great article. I wanted to understand if the training set can be extended. I wanted to train some of the classes from the “Luminoth” library – would that be possible – where can I add the extra class labels?
Thanks.
Hi Jyoti,
You can make changes in the csv file. You can add classes in them and then pass those labels while training the model.
Hey pulkit,
I ran this for epoch length=100 and epoch =5 still i am not getting any output at least some wrong output should be there. dont know the reason why?
Hi Aaditya,
Make sure you are giving the correct bounding box coordinates for their corresponding images while training the model. If you give incorrect coordinates, you will not get results. So, I would suggest before passing the coordinates and images for training, first plot some images with their corresponding bounding boxes and check whether the data is in correct form.
Hi and thanks for the tutorial.
I have a problem with bounding box detection in python. I use this tutorial on Stanford cars dataset.
I provide train_annotate.txt and it runs successfully on a few epochs with loss value of 2.
it’s natural because of the small number of epochs.
but when I run test_frcnn.py on the test_images folder it saves pictures with no bounding box.
I expected at least a wrong bounding box appear on pictures.
would you please help me? thank you.
and my other question is, how can i evaluate the accuracy of the trained model on test set?
here is the test log for 5 test picture:
physical GPU (device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0, compute capability: 6.1)
000001.jpg
Elapsed time = 6.0193772315979
[]
000146.jpg
Elapsed time = 1.3050158023834229
[]
000150.jpg
Elapsed time = 1.2876217365264893
[]
000160.jpg
Elapsed time = 0.6831655502319336
[]
000162.jpg
Elapsed time = 0.76279616355896
[]
Hi Sajjad,
Make sure that the training and testing images have similar shape, also you have done similar pre-processing on these images. If the distribution of train and test images is different, you will not get fair results. Also, try to run the model for more number of epochs so that it can learn the patterns and can become better.
Regarding your other question, you can evaluate the performance of model on test images only if you have the true labels for the test images, i.e. the class of the objects and their actual bounding boxes. If you do not have these values, you will not be able to evaluate the model on test images.
Hi Pulkit,
I have two questions to ask
1. During training, we are only training on one image at a time if I understood the code correctly right. So if I have to say train on 2500 training images then to complete one epoch in one go, then I have to set `epoch_length=2500`.
2. Could you please explain the outputs losses `rpn_cls` and `rpn_reg`? I know they are related to RPN output predictions. What I got from the code that we are generating ground truth for RPN using numpy operations and comparing RPN network output and training. But why is it actually required?
3. What exactly is metric bounding box accuracy? Could you explain in more detail.
4. Also for me all the 4 losses are not going down simultaneously, all of them are like really fluctuating. I am using VGG-16, Any suggestions on that
Hi Shivangi,
1. 1 epoch is when we have gone through all the images once. So, epoch_length has nothing to do with the training images.
2. The overall loss is calculated based on these losses. Here, one loss is for classification and other for regression. rpn_cls will tell us how accurately we have classified the correct class for the identified object and rpn_reg will tell how accurate our bounding boxes are.
3. It is similar to rmse, not exactly same but conveys the similar message. It tells us how accurate our predicted bounding boxes are.
4. The losses can fluctuate. Ideally they all should be synced but practically when we implement things, there can be fluctuations.
Hope this helps!!
Hi Pulkit,
1. I know what epoch is, but if you look at the code you have used variable `epoch_length`. So my question is different. I want to know if I have to train on 2500 training images then to complete one epoch in one go, then I have to set `epoch_length=2500` because we are only training on one image at a time.
2. If `rpn_clas` and `rpn_reg` are related to classification (say WBC, RBC etc) the what is classifier outputs `detector_cls` and `detector_regr` related to? I think they rpns are not related to classifier output, they are something else. Correct me if I am wrong
3. Still, I can’t really make out what it is . Could you explain it a bit more?
Hi Shivangi,
1. I checked the codes and all the images are used in every epoch. Can you please tell in which part of the code you are having doubts?
2. For detail on various losses, please refer to the losses.py which is inside the keras_frcnn folder of the github repository. Link for the repository is given in the article.
3. I checked the codes and found out that this is the accuracy of classes and not the bounding boxes. It can be seen in this code: print(‘Classifier accuracy for bounding boxes from RPN: {}’.format(class_acc))
1. Let me frame it differently, what is variable `epoch_length` doing in the code?
2. Yes, `rpn_clas` and `rpn_reg` are NOT related to classification (WBC, RBC). They are related to object presence or not.
3. Got it
Hi Shivangi,
1. If you look at this line of code:
if iter_num == epoch_length:
loss_rpn_cls = np.mean(losses[:, 0])
loss_rpn_regr = np.mean(losses[:, 1])
loss_class_cls = np.mean(losses[:, 2])
loss_class_regr = np.mean(losses[:, 3])
class_acc = np.mean(losses[:, 4])
Suppose you define epoch_number as 1000, so after every 1000 iterations, all the losses will be calculated and the weights will be updated accordingly. In single epoch, we can have multiple iterations. This is also known as Mini Batch Gradient Descent. So, instead of taking single image for training and updating the weights, we take batches of images and train the model on them and update the weights accordingly. Once the model has seen all the images once, one epoch is complete.
Could you please un-delete the comment which you deleted about the follow ups on your reply.
Hey, Pulkit, thanks for your article. Can you guide me on how to annotate the images with bounding box?? I am confused with this part?? plzz help me..
Thanks
Hi,
You have to manually annotate the images if you are using a new dataset. Or else, you can look for open source datasets which have their corresponding bounding boxes.
Thanks.I want to know how to set GPU config.
Hi,
Refer to this link.
Hello !
First of all, thanks you for this amazing tuto.
I am having just a little problem :
Using the weights you provided ( my PC is way too slow for getting good ones myself) as well as the option file, when i use test_frcnn.py the labels on WBC and RBC are inverted. The cells themselfs are very-well recognised, it is just that every single WBC is labelled as RBC and every single RBC is labelled as WBC … Any idea of what may have caused than ?
Hi Martin,
Can you please share the screenshot of some of the results that you are getting? That would help me to clarify your doubt in a better way.
Please can you teach me how to use use VOC pascal dataset? i have downloaded the dataset but its not in path/x1,y1,x2,y2,class_name format.
Hi saadiq,
You have to convert the format of the data to use this library. You can do some coding or search online how to convert the VOC pascal dataset. Or else share the format of your data and I will look for solution.
train_frcnn.py -o simple -p annotate.txt
File “”, line 1
train_frcnn.py -o simple -p annotate.txt
^
SyntaxError: invalid syntax
Im running it through IPython console, I dont understand why it isnt working
Hi Karl,
You have to use the following code:
python train_frcnn.py -o simple -p annotate.txt
Go to the directory where the train_frcnn.py file is and run the above line of code.
Hello,
I am landing up to this error, i have my train_images folder and train.csv file inside keras-frcnn folder and i am trying to use %run from Jupyter, could you please help on this.
Parsing annotation files
—————————————————————————
AttributeError Traceback (most recent call last)
~\Image_Processing\Object_Detection\keras-frcnn\train_frcnn.py in ()
77 C.base_net_weights = nn.get_weight_path()
78
—> 79 all_imgs, classes_count, class_mapping = get_data(options.train_path)
80
81 if ‘bg’ not in classes_count:
~\Image_Processing\Object_Detection\keras-frcnn\keras_frcnn\simple_parser.py in get_data(input_path)
35
36 img = cv2.imread(filename)
—> 37 (rows,cols) = img.shape[:2]
38 all_imgs[filename][‘filepath’] = filename
39 all_imgs[filename][‘width’] = cols
AttributeError: ‘NoneType’ object has no attribute ‘shape’
Hi Sayak,
Open the train_frcnn.py and check the filename that you are giving. Currently it is not able to go to the images folder. Try to edit the filename, i.e. the path of the images.
Yes it is solved now by adding full path inside annotation.txt. Thanks.
But I am getting this error, please suggest
—————————————————————————
InvalidArgumentError Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _create_c_op(graph, node_def, inputs, control_inputs)
1627 try:
-> 1628 c_op = c_api.TF_FinishOperation(op_desc)
1629 except errors.InvalidArgumentError as e:
InvalidArgumentError: Shape must be rank 1 but is rank 0 for ‘bn_conv1/Reshape_4’ (op: ‘Reshape’) with input shapes: [1,1,1,64], [].
Hi Sayak,
You can refer this link and see if you find something helpful.
I had this same error. I seem to have gotten the program to start learning by editing the keras source. In file keras/backend/tensorflow_backend.py I found 4 reshape functions near each other, one of which was involved in the error. I changed the second argument of each of these from (-1) to [(-1)]. This allowed the program to run. Unfortunately, this is a dangerous change since I don’t actually know everything that will be affected.
When I got this error it ended up being an issue with the file path being incorrect relative to where you were running the script from. Go into your txt file that has all the file paths and x/y values and make sure the relative path is correct.
Do you have the config.pickle of your model trained? It is needed for testing.
Hi Leonardo,
You can download the config.pickle file from this link.
Can we use the same algorithm for detecting text in images? Do you have any resources on end-to-end text recognition from images?
Hi Ravi,
I have not yet worked on text recognition project. If I find any relevant resource, I will share it with you.
Hi pulkit,
First of all thanks for you blog post on object detection, i trained 40 images (my own dataset) on 100 epochs , but when i passed test images it doesn’t recognize any of given images means it didn’t recognize bounding boxes around images at least wrong prediction is expected but no bounding boxes are detected, i have resized test images in same manner as i did for train images.
I have no clue what is happening, so can you please check what is the problem?
Hi Abhijit,
It might be possible that the training dataset is small that’s why the model is not able to understand the signals. Also, make sure you are providing the correct bounding boxes while training. Try to plot few images with their corresponding bounding boxes to make sure that the notations are correct.
Hi Pulkit,
i agree that dataset is small but i am expecting wrong prediction at least and i tried by plotting train image where bounding boxes are present with correct notion. Do you want me to share image dataset.
Hi Pulkit,
i agree that dataset is small but i am expecting wrong prediction at least and i tried by plotting train image where bounding boxes are present with correct notion. Do you want me to share image dataset.
test_images prediction
111:mpn:0a0f6d7b3a9f0093d6ce022b6d67f02a.jpeg
Elapsed time = 12.53669023513794
[]
111:mpn:0a11ac3820dc5591d2f7353eb0e5a966.jpeg
Elapsed time = 9.79170274734497
[]
111:mpn:0a30eb770fcd3fcb8c590b078825ea50.jpeg
Elapsed time = 8.541940212249756
[]
111:mpn:0a4a85bd72695d975893fd9f072c127d.jpeg
Elapsed time = 7.845632553100586
[]
111:mpn:0a4b198321cf36d751b61db66caaba5e.jpeg
Elapsed time = 6.625025272369385
[]
111:mpn:0a5b89b59272586ff617d915b490ba18.jpeg
Elapsed time = 8.454639434814453
[]
111:mpn:0a64fc71a5b9de382c964eb929ee0b13.jpeg
Elapsed time = 7.680825710296631
[]
111:mpn:0a8690b6afc68e32fa59aca5403f0ebd.jpeg
Elapsed time = 8.591627359390259
[]
why [] is present in prediction?
Hi Abhijit,
Please share the files that you are using to train the model, as well as few test images.
Hi pulkit,
please provide your email id so i can share files.
the approach used here is it yolo v1,v2 ?
Hi Omkar,
I have implemented Faster R-CNN in this article.
Can we train different object with the same code
Hi Sidharth,
Yes! you can train this model for different objects as well. You just have to change the annotation file.
How can we check the accuracy of the model at last ?
kindly guide me the where is train.xml files….??
i cant find them
i have train.idx file
train.rec file but cant find train.xml file
kindly help me
Hi Rabiya,
The xml files are in the BCCD – Annotations folder of this repository.
Hey pulkit,
I trained my own model using the codes for thermal images.I am getting the output but false predictions are also coming.How to resolve it? can you please help me with it
Hi Rishabh,
You can try to increase the number of epochs and let the model learn more features. This might help to improve the model performance.
Thanks Pulkit,
And also i want to ask about the performance metrics,how to calculate mAP?can you share the code here please.
Also i trained the model for only 30 epochs as i don’t have GPU.so i ill try training it on a better hardware specifications.
kindly guide me
in the demo code i cant show any image in the last
its giving this error
Image data cannot be converted to float
what show i do??
kindly reply on my 4email
hey pulkit,
I wanted to ask about what is getting saved in config.pickle file and where are the parameters such a learning rate in the code?
Hey Pulkit,
When i am running the code of measure_map.py -o simple -p measure.txt.
measure.txt is my annotation file for testing images but it is showing error resolve it?
Hey pulkit,
I am getting eerror when i am running measure_map.py with it
Hi Pulkit ! Thanks for your sharing !
I copy your code and run.
But I have a problem that when the “training” starts , it tells me the ETA is 28 HOURS ! .It too long ,when the epoch is 2000 , the training time is a VERY HUGE number.(I use the Tesla T4 GPU).I dont know how long is your training time?
Is my setting is wrong ? Or I need to use more faster GPU ?
Please tell me what should I do to short the training time.
Or could you share the training result to me?
Thank you so much!🙏
Hi,
You can try to reduce the number of epochs to reduce the training time or you can try a faster version of GPU to train your model. Also, if you want to use the pre-trained weights of the models that I have trained, you can download them (link for these weights have been provided in the article). I got those weights after training the model for 500 epochs.
Hi Pulkit,
Can we train the above model for tumor detection using bounding boxes? But in a tumor image, we have one or two patches of tumor which is to be detected. The color of tumor varies in each image. How can we do that?
Hi,
You can use this for detecting tumor. For that you will require the labeled images first. Once you have the labeled images, i.e. you know the bounding boxes for all the tumor, you can train the model.
Once the model is trained, you can use that trained model and make predictions for new images.
Thanks Pulkit
Thank s for the wonderful article! I tried it and it worked well
Now could you please guide me how to run this on AMD GPUs (is it possible to run the same code or some modifications should be needed)?
Thanks in Advance!
Hi,
Glad you found it helpful.
These codes are written to run on both GPU and CPU. I myself trained the model on GPU. So, you can go ahead and train the model on GPU. You won’t have to change anything in the codes.
Would this object detection algorithm work if the images has objects with a resolution of about 6×6 or 10×10 pixels?
Hi,
Generally, Faster R-CNN works well enough while dealing with even small objects. But I can not confirm whether it will work well or not as I have not tried it myself for detecting small objects. So, I would suggest that you try it on images having smaller objects and share your insights here which will be helpful for the community.
Hi Pulkit ,
when I run the model in epoch 36/100 I receive the following exception error:
“Exception: a must be non-empty”.
i’ve run this model on eight pictures (in TIF). the model ran for up to 35/1000 and then started throwing this exception.
while, the other day i ran the same model with only 4 pictures (in PNG) and no exceptions where thrown.
How is this possible, and would anyone have an idea what the reason would be.
Thank you in advance for your help.
Hi Elie,
The error that you are getting might be due to memory issues. These are some heavy codes and will require high RAM and GPU power.
Hi sir,
I cant find the training set, test set, train,csv folders here.
Can u give the source to find those folders.
Thank you
Hi Abisha,
The dataset is provided here. | https://www.analyticsvidhya.com/blog/2018/11/implementation-faster-r-cnn-python-object-detection/ | CC-MAIN-2020-24 | refinedweb | 8,501 | 75.81 |
I've been receiving an intermittent crash in d3d_shutdown when my program exits. Why would it crash on the line _al_d3d->Release() unless _al_d3d was an invalid pointer? My window sets up fine and I don't believe I am double freeing anything.
I'm using MinGW 4.5.0 on Vista with latest Allegro from Git.
Any ideas why this is happening?
I think it has something to do with my reworked timer class but I don't know what. I've got a thread that runs TimerProcess and communicates with an Allegro5Timer through means of an ALLEGRO_EVENT_QUEUE. States between the TimerProcess and the Allegro5Timer are synchronized using the allegro event queues. When the timer sends a message to the timer process, it waits for a matching return message so that the states are synchronized. I don't destroy anything twice, I'm sure, and I destroy every ALLEGRO_THREAD, ALLEGRO_TIMER and ALLEGRO_EVENT_QUEUE that I create.
Here's the code for Allegro5Timer.cpp if it helps.
And here's my main function :
int ThreadingTestMain(int argc , char** argv) {
(void)argc;
(void)argv;
Allegro5System sys;
sys.InitializeSystem();
return 0;
}
The sys constructor just initializes everything to zero, and here's the code for InitializeSystem :
So, my system creates a system timer, calls Create on it to create it, and then it gets destroyed by the destructor. Just simple code to test things right now.
I don't see what I'm doing to cause a crash in d3d_shutdown.'s EagleThread? Are maybe using an Allegro function on a thread not created by it?
--"Either help out or stop whining" - Evert
EagleThread is just a small wrapper around an ALLEGRO_THREAD. Allegro5Timer::Create new's an Allegro5Thread (the wrapper class) and calls Create on it to create a new thread. If it is successful, the thread is started and synchronized by message. The ALLEGRO_THREAD is destroyed in the destructor of Allegro5Thread, which is called by Allegro5Timer::Destroy after the thread has been joined.
Are maybe using an Allegro function on a thread not created by it?
No, all I use are ALLEGRO_THREADS at this point. If I write a driver for a different backend I might have to use pthreads, I don't know.
I don't understand, because all I do is initialize allegro and all the addons, then create a timer which uses an ALLEGRO_THREAD to monitor the ALLEGRO_EVENT_QUEUE that has subscribed to my ALLEGRO_TIMER. I initialize some resources, and then I shut down.
Where do you think the crash is coming from? A double free? On my part? On Allegro's part?
Does it also happen if you use a separate allegro.DLL instead of linking it in?
And just guessing at causes here...
I'm currently linking dynamically to allegro, and to my library and to my backend. I built the static debug versions of them and tried it, and results were exactly the same.
Back in 5.0.0RC1 there was a crash in d3d_shutdown that was similar but I don't know if it was ever solved :
I varied my code according to some ideas in that thread, and it still crashes in the same place.
Funny thing is, it doesn't crash during the manual call to al_uninstall_system but it does crash in al_uninstall_system when the exit routines run.
Program received signal SIGSEGV, Segmentation fault.
0x693df8b7 in d3d_shutdown () at C:\mingw\LIBS\A5GIT\allegro\src\win\d3d_disp.cpp:2604
2604 _al_d3d->Release();
(gdb) bt
#0 0x693df8b7 in d3d_shutdown () at C:\mingw\LIBS\A5GIT\allegro\src\win\d3d_disp.cpp:2604
#1 0x693cfa88 in win_shutdown () at C:\mingw\LIBS\A5GIT\allegro\src\win\wsystem.c:197
#2 0x6936fcd1 in shutdown_system_driver () at C:\mingw\LIBS\A5GIT\allegro\src\system.c:77
#3 0x69363fe1 in _al_run_exit_funcs () at C:\mingw\LIBS\A5GIT\allegro\src\exitfunc.c:92
#4 0x69370015 in al_uninstall_system () at C:\mingw\LIBS\A5GIT\allegro\src\system.c:302
#5 0x6ab41086 in __dll_exit () from c:\ctwoplus\progcode\eagle5gui\cbbuild\bin\eagle_a5d.dll
#6 0x6ab4110a in DllMainCRTStartup@12 () from c:\ctwoplus\progcode\eagle5gui\cbbuild\bin\eagle_a5d.dll
#7 0x77aaded4 in ntdll!RtlDefaultNpAcl () from C:\Windows\system32\ntdll.dll
#8 0x77a9a959 in ntdll!RtlExtendMemoryBlockLookaside () from C:\Windows\system32\ntdll.dll
#9 0x77a9a8db in ntdll!RtlExtendMemoryBlockLookaside () from C:\Windows\system32\ntdll.dll
#10 0x76933d77 in KERNEL32!ExitThread () from C:\Windows\system32\kernel32.dll
#11 0x00000000 in ?? ()
(gdb)
Edit
This does not crash :
Allegro5System* sys = new Allegro5System();
delete sys;
This crashes :
Allegro5System* sys = new Allegro5System();
sys->InitializeSystem();
delete sys;
This does not crash :
Allegro5System* sys = new Allegro5System();
sys->InitializeSystem();
delete sys;
al_uninstall_system();
And now, this does not crash anymore when it did before :
Allegro5System* sys = new Allegro5System();
sys->InitializeSystem();
delete sys;
al_uninstall_system();
Sleep(3000);
Anyone have any ideas how I should go about debugging this? I've already been down into every single code branch that InitializeSystem goes into, and I haven't seen anything wrong.
I'm really hesitant to say anything here, because I don't know what's wrong and don't have much time to give any REAL help... but the first thing that comes to mind is unfreed D3D resources like shaders or VBOs or... anything like that?
The only D3D or DX I'm using is whatever Allegro is using behind the scenes.
Why is D3D running when I haven't even opened a display yet?
I just tried ripping the guts out of EagleSystem::InitializeSystem and putting them in main and I can't reproduce the crash, even while executing pretty much the same code.
Probably not related (different platform for one), but a problem I ran into recently was that my program would crash when the main display was destroyed. This turned out to be due to destroying the parent bitmap, but not all of the child bitmaps. When the display was destroyed at the end of the program Allegro would try to turn these into memory bitmaps - and crash because the parent bitmap had already been destroyed.
Took me a while to find that one, so check if you might have a similar issue. Also, if you haven't already, try the OpenGL driver. If that works fine it may be a hint with the D3D driver, otherwise it's either something in your code, or at a higher level but within Allegro itself.
On Linux I find Valgrind a great help in situations like this, but I guess it isn't available for Windows?
EDIT: although, if the crash also happens with the OpenGL driver it may be reproducible on Linux...
I wasn't even creating a display though. All I was calling was al_init(). Then create some allegro stuff and then destroy it all and shutdown allegro.
I could try changing the order I destroy things in and see if that helps. I thought all event sources unsubscribed themselves upon destruction, but maybe they don't. Well no al_destroy_event_queue says it auto de-registers. So I don't know why that would be it. Maybe my thread is still running but I join it in the destructor so it shouldn't be.
I really don't have any other idea what it might be.
It's either a really strange bug in allegro and/or windows or some kind of memory bug in your own code (this is usually the cause of strange crash bugs like this). Potentially a double free, or something is being corrupted.
-- still didn't tell us if the problem persists when you use opengl.Anyway, you might actually have heap corruption, as Thomas pointed out. Try using crt heap checking functions.
I said, I don't even create a display. I can't choose al_init(OPEN_GL). Do you mean you want me to create a display with OPEN_GL?
Heap corruption? I can look again I suppose. What are these crt heap checking functions you are talking about?
I think you can still change the "new" display driver.
I do find it odd that its trying to call any d3d "disp" code at all without any displays being created.
That is probably not the most efficient way to check for heap corruption, however, I do the follwing.First, you need to do this in the beginning of your program, better yet in the precompiled header:
#define CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
Then you place somewhere this line:
assert(_CrtCheckMemory());
If your heap is already corrupted at this point, it should break there. If it doesn't break at this assert, then put it further down your program. If it breaks at this assert, place your assert closer to the beginning of your program, and so on until you find the offending line.
Sorry, but MinGW 4.5.0 doesn't come with crtdbg.h or any other header with _CrtCheckMemory in it. Otherwise I would do it. They are specific to MSVC++, which I have installed, but I have never used it, and it would take me a long time to get my libraries set up with a solution. Also, MSVC++ wants me to register, and when I go to obtain a registration code, I am greeted with a Microsoft login. Yet another account to create.
Also, MSVC++ wants me to register, and when I go to obtain a registration code, I am greeted with a Microsoft login. Yet another account to create.
I googled for a code without the intrusiveness.
see why it's impossible to use crt function in gcc, since they are all part of msvcrt.dll which every windows user should have (with proper linking and headers). Anyway, I never used mingw, but there should be something specific to gcc/mingw or whatever, which can check if the heap is corrupted.Maybe this question on stackoverflow can help you:: However, memory leaks which most of them seem to be talking about is not the same as heap corruption.I still think that on windows you should somehow use windows crt functions and not linux-specific stuff which might actually never work on windows.Ypu can also try to detect the offending code by shortening your program. Create the shortest possible example of your program which causes your problem. Like, try to replace your own timer with the standard allegro one, etc.
I don't think it would be that easy to link the Microsoft C Runtime DLL to a GCC-compiled program since GCC provides it's own C runtime....no?
Anyway Edgar, I don't have anythig REALLY useful here to say, but maybe are you able to reprodice the crash w/o Eagle related code?
Otherwise I'd definitely triple-check your Initialise System routines, particularly the Input and Event Handler (which sources are you registering there?)
It is unlikely that Google shares your distaste for capitalism. - DerezoIf one had the eternity of time, one would do things later. - Johan Halmén
Nope. MingW's entire purpose is to be a GCC that uses msvcrt.dll. Otherwise you get stuck with Cygwin and all of its nonsense.
Ah of course that makes sense....so is it possible to import _CrtCheckMemory()?
It probably is. You'd probably need to find the MSVC declaration and copy it into a gcc compatible format.
Cool, should look into it.
If you can post a complete program that shows the problem I can try compiling it in Linux and run it through valgrind. If there is something in your code it may show up there.
Cross platform develpmnt is a great way to find bugs.
Well, here is exactly what EagleSystem::InitializeSystem does :
and that doesn't crash at all. :/
Create the shortest possible example of your program which causes your problem. Like, try to replace your own timer with the standard allegro one, etc.
Created separately none of my objects have problems. The code above is exactly what the line sys->InitializeSystem(); does.
but maybe are you able to reprodice the crash w/o Eagle related code?
No, I haven't been able to.
Otherwise I'd definitely triple-check your Initialise System routines, particularly the Input and Event Handler (which sources are you registering there?)
I have and I don't see anything wrong. No double frees, no leaks. I register the timer output with the event queue.
If you can post a complete program that shows the problem I can try compiling it in Linux and run it through valgrind. If there is something in your code it may show up there.
Thanks, but you would have to build my library and my allegro 5 backend to do so. I think I will migrate to building in my OpenSUSE VM so I can look for problems. And then I will create some CodeBlocks projects to build on Linux.
Cross platform development is a great way to find bugs.
I will try it out. | https://www.allegro.cc/forums/thread/613372/991328 | CC-MAIN-2018-30 | refinedweb | 2,140 | 66.84 |
In part 1, we created a simple application that made use of string resource bundles in JSF and in part 2 we extended it by using CDI to inject the resource provider into beans so we can re-use our code for accessing locale specific string based resources.
One benefit of using CDI to inject your beans instead of just creating them manually is the ability to utilize the event mechanism within those beans. In this example, we are going to fire an event when we discover a resource is missing.
- Start by creating a
MissingResourceInfoclass that stores the info regarding the missing resource (key and locale). This will be passed along with the event so the observer has all the info when it receives the event.
public class MissingResourceInfo { private final String key; private final String locale; public MissingResourceInfo(String key, Locale locale) { this(key, locale.getDisplayName()); } public MissingResourceInfo(String key, String locale) { super(); this.key = key; this.locale = locale; } public String getKey() { return key; } public String getLocale() { return locale; } }
- We fire an event when we discover a resource key is missing from the locale specific properties file being used. In the
MessageProviderclass from part 2, we inject the
Eventinstance in to a field and modify the
getValuemethod to fire off the event when a key is missing.
@RequestScoped public class MessageProvider { @Inject private Event<MissingResourceInfo> event; .... .... public String getValue(String key) { String result = null; try { result = getBundle().getString(key); } catch (MissingResourceException e) { result = "???" + key + "??? not found"; event.fire(new MissingResourceInfo(key, getBundle().getLocale())); } return result; } }
- Finally, we want to add an observer for that event that handles it when it is fired. To do this, we will add a new class for this purpose.
public class MissingResourceObserver { public void observeMissingResources(@Observes MissingResourceInfo info) { String template = "Oh noes! %s key is missing in locale %s"; String msg = String.format(template, info.getKey(), info.getLocale()); System.out.println(msg); } }
- Finally, to see it in action, we need to add bean getter to fetch a non-existing value from the bundle.
@Named @RequestScoped public class AnotherBean { public String getMissingResource() { return provider.getValue("ImNotHere"); } }
- We can see this in action by adding to our JSF page a call to this property
#{anotherBean.missingResource}
Results in the following being displayed in the console :
Oh noes! 'ImNotHere' key is missing from locale English (United States)
Remember, you can have as many event observers as you want so you can have one that just logs it to the console or one that emails if missing text strings are urgent (i.e. production). You could have it write the missing values to the database so during development cycles, the missing strings can be exported and put into the properties files. This is especially useful if you have third parties handling the translation where you can send them a list of missing items to translate in one big batch.
What about EL?
This works great when we are accessing resource bundles from Java, but what about when we are using EL expressions to access the values. JSF channels those expressions straight to the resource bundle without the ability to intercept them. One way to fix this would be to write our own EL expression resolver and see if the root of the expression maps to a resource bundle and if so try to obtain the value from the bundle and fire the event if the item is not found. This would work, but it seems overkill since every EL expression would end up going through the resolver.
Remember that the syntax for accessing resource strings in EL is
#{bundlename.key}, and Java
Map classes can also be accessed using the same syntax. What we can do is create a named bean that (barely) implements the map interface and in the
get method, it gets the value from the injected resource bundle. This means EL expressions will use our Map bean and we can delegate the call to the Message provider which will handle missing expressions.
- Start by creating a new bean that implements the
Mapinterface. Most of the methods will throw exceptions that they are not implemented, we only really care about the method to get values.
@Named("messages") @RequestScoped public class ResourceMap implements Map<String, String> { @Inject private MessageProvider provider; @Override public int size() { return 0; } @Override public boolean isEmpty() { return false; } @Override public boolean containsKey(Object key) { return provider.getBundle().containsKey((String) key); } @Override public boolean containsValue(Object value) { throw new RuntimeException("Not implemented"); } @Override public String get(Object key) { return provider.getValue((String) key); } @Override public String put(String key, String value) { throw new RuntimeException("Not implemented"); } @Override public String remove(Object key) { throw new RuntimeException("Not implemented"); } .... .... .... }
If the interface method isn’t listed, assume it throws a “not implemented” exception. We inject the
MessageProviderinstance so we can re-use our message provider bean to fetch messages and fire the events.
- We gave the bean the name
messagesso if we go to our web page and add the following to our page :
First name from map = #{messages.firstName}<br/> Missing name from map = #{messages.missingValue}<br/>
When we run our application and refresh the page, we get the value displayed for
messages.firstName, and a missing value for
messages.missingValue. In our server log we get
Oh noes! missingValue key is missing in locale English (United States)
Since we re-used the
MessageProviderbean, it fires the event when it cannot find a key value so even though we called it from the JSF page, it ended up being routed through to our message provider and the event being fired.
How you use this is up to you, but since the syntax is the same whether you use the Map or the JSF resource variable, you can switch between the two depending on whether it is a development or production environment. You may also use different event handlers depending on the deployment environment. Alternatively, you may be worried about performance in production, or the fact that you lose autocompletion if you use the map in development.
To switch implementations, just give either the JSF resource variable, in
faces-config or the
MessageProvider bean the name used for your resource string component. You can switch components without having to change either your code or your JSF pages.
Download the Maven source code for this project and run it locally by typing unzipping it and running
mvn clean jetty:run in the command line, and going to.
Hi. I have two questions:
1. How can I track events connected with session (session context) with CDI (i.e. session start)
2. How can I instantiate selected class at the beggining of selected context (something like @Startup in seam 2)
Paul
In a nutshell, you can’t. You can observe some application level event of the BeanManager (post bean validation or something like that), but that is more of an internal event handler, you can’t actually use your own beans or get them injected at that point.
Here’s a link on the discussion of startup beans in the Weld extensions. | http://www.andygibson.net/blog/article/handling-missing-resources-with-cdi-events/ | CC-MAIN-2019-13 | refinedweb | 1,184 | 52.39 |
Cooper Base Library (cooper.jar)
The Cooper Base Library (contained in
cooper.jar) is a small library that can be optionally used in Elements projects for the Java and Android platform. It provides some of the core types, classes and functions that are needed for more advanced language features of Oxygene, C# and Swift, such as Future Types, Await support, advanced delegate support, LINQ, and more.
Source Code
The Cooper Base Library is open source and implemented fully in Oxygene. You can find the source code on GitHub, and contributions and pull requests are more than welcome.
Note that you will usually need the very latest compiler to rebuild
cooper.jar yourself, and in some cases, the git repository might even contain code that requires a later compiler than is available. Refer to the commit messages for details on this, and check out an older revision, if necessary.
Namespaces
The Cooper Base Library is divided into these namespaces:
- com.remobjects.elements
- com.remobjects.elements.linq
- com.remobjects.elements.system
- RemObjects.Elements.System
See Also
Version Notes
cooper.jar was called
com.remobjects.elements.rtl.jar in Elements 8.2 and below. Projects will automatically be migrated to use the
cooper.jar reference when opened in Fire, Water or Visual Studio. | https://docs.elementscompiler.com/API/CooperBaseLibrary/ | CC-MAIN-2018-51 | refinedweb | 210 | 50.94 |
GETIFADDRS(3) BSD Programmer's Manual GETIFADDRS(3)
getifaddrs - get interface addresses
#include <sys/types.h> #include <sys/socket.h> #include <ifaddrs.h> int getifaddrs(struct ifaddrs **ifap); void freeifaddrs(struct ifaddrs *ifap); en- tries: */ ifa_next Contains a pointer to the next structure on the list. This field is set to NULL in interfaces, references the broadcast address associated with ifa_addr, if one exists, otherwise it is NULL. ifa_dstaddr References the destination address on a P2P interface, if one exists, otherwise it is NULL. ifa_data References address family specific data. For AF_LINK ad- dresses.
Upon successful completion, a value of 0 is returned. Otherwise, a value of -1 is returned and errno is set to indicate the error.
The getifaddrs() may fail and set errno for any of the errors specified for the library routines ioctl(2), socket(2), malloc(3), or sysctl(3).
ioctl(2), socket(2), sysctl(3), networking(4), ifconfig(8)
The getifaddrs() function first appeared in BSDI BSD/OS. The function has been available on OpenBSD since OpenBSD 2.7.
If both <net/if.h> and <ifaddrs.h> are being included, <net/if.h> must be included before <ifaddrs.h>. MirOS BSD #10-current October 12,. | http://mirbsd.mirsolutions.de/htman/i386/man3/getifaddrs.htm | crawl-003 | refinedweb | 200 | 53.27 |
Last modified on 28 August 2008, at 11:15
See original RRSAgent log and preview nicely formatted version.
Please justify/explain all edits to this page, in your "edit summary" text.
00:00:00 <scribenick> PRESENT: IanH, Ivan, bmotik (muted), m_schnei (muted), Sandro, Zhe (muted), MarkusK, uli, bcuencagrau (muted), pfps, baojie, JeffP, Achille, bparsia, msmith, bcuencagrau, JeffP, ewallace, Carsten, bmotik 00:00:00 <scribenick> REGRETS: Rinke, Elisa 00:00:00 <scribenick> CHAIR: IanH 17:00:34 <RRSAgent> RRSAgent has joined #owl 17:00:34 <RRSAgent> logging to 17:00:45 <Zakim> +Sandro 17:08:24 <bparsia> Topic: Admin -- Roll call and agenda amendments 17:08:31 <bparsia> No amendments 17:08:43 <bparsia> Topic: Minutes approval 17:09:08 <IanH> PROPOSED: accept 13th August minutes 17:09:11 <IanH> +1 17:09:11 <uli> +1 17:09:12 <msmith> +1 17:09:13 <baojie> +1 17:09:13 <bparsia> +1 17:09:18 <bcuencagrau> +1 17:09:23 <Zakim> +Evan_Wallace 17:09:23 <uli> zakim, mute me 17:09:24 <Zakim> uli should now be muted 17:09:26 <IanH> RESOLVED: accept 13th August minutes 17:09:44 <bparsia> PROPOSED: accept 20th August minutes 17:10:09 <IanH> +1 17:10:10 <bparsia> +1 17:10:11 <uli> +1 17:10:12 <Carsten> Zakim UK gives me a busy signal after entering the passcode, and Zakim France says that the key is not valid (both do that repeatedly) sigh. 17:10:14 <sandro> +1 17:10:31 <bparsia> RESOLVED: accept 20th August minutes 17:10:40 <bparsia> Topic: Action Item status 17:10:44 <sandro> Carsten, can you try to US number, or is that not practical? 17:11:05 <Zakim> +??P0 17:11:11 <Carsten> zakim, p0 is me 17:11:11 <Zakim> sorry, Carsten, I do not recognize a party named 'p0' 17:11:15 <bparsia> IanH: Long list of pending review action. I've reviewd. Let's accept them. 17:11:17 <Carsten> zakim, ??p0 is me 17:11:17 <Zakim> +Carsten; got it 17:11:23 <Carsten> aaaaahhhh 17:11:25 <bparsia> IanH: They are done. 17:11:29 <Carsten> zakim, mute me 17:11:29 <Zakim> Carsten should now be muted 17:11:38 <bparsia> zakim, unmute me 17:11:38 <Zakim> bparsia should no longer be muted 17:12:14 <bparsia> ACTION 168: postponed for 2 weeks 17:12:14 <trackbot> Sorry, couldn't find user - 168 17:13:06 <bparsia> Bijan: actiosn 168, 170, and 174 postpone for 2, 1, and 1 weeks respectively 17:13:32 <bparsia> JieBao: 150 needs another week 17:13:41 <bmotik> Shouldn't we close ACTION-150? After all, the discussion with RIF has been initiated. 17:14:24 <bparsia> IanH: Action 192 is a bit stalled due to Italian hols. Postponed a week. 17:14:35 <m_schnei> zakim, unmute me 17:14:35 <Zakim> m_schnei should no longer be muted 17:14:59 <bparsia> IanH: 181 was delayed to due Michael illness, but seems done now? 17:15:19 <bparsia> m_schnei: I think I can finish tomorrow. Will send email. 17:15:44 <bparsia> IanH: Peter said he wouldn't be able to review in a timely manner due to vacation...Peter? 17:16:10 <bparsia> pfps: I can two it in two weeks from today if its ready by the end of this week 17:16:20 <m_schnei> zakim, mute me 17:16:20 <Zakim> m_schnei should now be muted 17:16:59 <bparsia> IanH: all core documents (except Profiles) are in good shape and I sent notification to the reviewerss 17:17:08 <msmith> I'm able to meet schedule 17:17:08 <bparsia> ...Are reviewers able to meet the schedule. 17:17:11 <bparsia> I'm fine 17:17:11 <uli> sure 17:17:17 <Achille> sure 17:17:19 <MarkusK> sure 17:17:55 <bparsia> IanH: Reviewing seems in good shape. 17:18:09 <bparsia> IanH: 202 postponed 17:18:15 <bparsia> Topic: Issues 17:18:28 <bparsia> Topic: Proposal to Resolve 17:18:39 <bmotik> ZAkim, unmute me 17:18:39 <Zakim> bmotik should no longer be muted 17:18:42 <bparsia> Topic: Proposal to resolve Issue 118 17:19:07 <bparsia> bmotik: We align bnodes exactly with RDF and impose syntactic restrictions (i.e., tree like patterns only) 17:19:10 <bmotik> Zakim, mute me 17:19:10 <Zakim> bmotik should now be muted 17:19:23 <bparsia> q+ 17:19:31 <IanH> q? 17:19:35 <IanH> ack bparsia 17:19:42 <bmotik> bparsia: I accept it is a workable solution, I don't think it is the best one 17:19:46 <ivan> bijan: I accept it as a workable, I am not sure it is best solution, let us see what comes from last call 17:20:11 <ivan> q+ 17:20:16 <IanH> q? 17:20:19 <IanH> ack ivan 17:21:30 <bparsia> PROPOSED: resolve Issue 118 (anonymous individual semantics), per 17:21:35 <ivan> +1 17:21:36 <bmotik> +1 17:21:38 <IanH> +1 17:21:40 <ewallace> +1 17:21:41 <bcuencagrau> +1 17:21:41 <MarkusK> +1 17:21:42 <Zhe> +1 17:21:42 <bparsia> +0.1 17:21:42 <uli> +1 17:21:46 <baojie> +1 17:21:50 <msmith> +1 17:21:50 <Carsten> +1 17:22:08 <bparsia> RESOLVED: resolve Issue 118 (anonymous individual semantics), per 17:22:25 <bmotik> ACTION to bmotik: Implement ISSUE-118 17:22:25 <trackbot> Sorry, couldn't find user - to 17:22:33 <bmotik> ACTION bmotik: to Implement ISSUE-118 17:22:33 <trackbot> Sorry, couldn't find user - bmotik 17:22:37 <bmotik> ACTION bmotik2: to Implement ISSUE-118 17:22:38 <trackbot> Created ACTION-203 - Implement ISSUE-118 [on Boris Motik - due 2008-09-03]. 17:23:06 <bparsia> Topic: Proposal to resolve Issue 139 17:23:22 <bparsia> q+ 17:23:34 <IanH> q? 17:24:36 <ivan> q+ 17:24:41 <ivan> ack bparsia 17:24:43 <sandro> to get it off the issue list 17:24:45 <uli> perhaps the benefit would be for the authors to know that they are not working in vain? 17:25:13 <bparsia> bparsia: Why do a predecision when we won't be publish it as a note until after the core language is done 17:25:20 <sandro> q+ 17:25:29 <ivan> ack ivan 17:25:43 <bparsia> ivan: We need to do some wg level publication but it's just a working draft, not saying anything about its terminal status 17:25:45 <IanH> ack sandro 17:26:10 <bparsia> sandro: People reviewing a working draft deserve to know whether something is rec track or not 17:27:33 <IanH> q? 17:29:08 <bparsia> sandro: I don't care if we say that it *is not* a rec track or it's not clear, but we should be indicate 17:29:10 <IanH> q? 17:30:11 <bparsia> [some discussion involving the scribe, but mostly scribe confusion so not critical] 17:30:15 <sandro> PROPOSED: Authors are encouraged are prepare a WD on Manchester Syntax, which the WG expects to publish. At some point in the future we will figure out if this is REC-track or not. 17:30:23 <bparsia> +1 17:30:28 <ivan> +1 17:30:28 <IanH> +1 17:30:29 <uli> +1 17:30:31 <baojie> +1 17:30:31 <sandro> +1 17:30:33 <msmith> +1 17:30:33 <MarkusK> +1 17:30:34 <Zhe> +1 17:30:39 <uli> ivan, sure! 17:30:41 <ewallace> +1 17:30:50 <Carsten> +1 17:30:50 <bcuencagrau> +1 17:30:55 <bparsia> RESOLVED: Authors are encouraged are prepare a WD on Manchester Syntax, which the WG expects to publish. At some point in the future we will figure out if this is REC-track or not (issue-139). 17:31:13 <sandro> that closes issue-139 17:31:51 <bparsia> Topic: Other Issue discussion 17:31:52 <ewallace> flights can't be reflexive? 17:32:30 <bparsia> IanH: 130 and 131 deal with the profile document 17:32:42 <Zakim> -Peter 17:32:43 <bparsia> Topic: 130 and 131 17:33:15 <IanH> q? 17:33:17 <bparsia> IanH: Alan and Sandro and I decided to produce a draft of profile and conformance as a basis of discussion for unification 17:33:31 <IanH> q? 17:33:41 <IanH> q? 17:33:41 <bparsia> I have and I think it's a good move. 17:33:46 <ivan> q+ 17:33:47 <Zhe> zakim, unmute me 17:33:47 <Zakim> Zhe should no longer be muted 17:33:49 <Zhe> q+ 17:33:50 <uli> yes, me too 17:34:03 <m_schnei> I did not find the time yet to read the new texts 17:34:05 <IanH> ack ivan 17:34:42 <uli> ...this is not possible? 17:35:09 <bparsia> ivan: Checking my understanding --- what happens when you get a graph that doesn't match the syntax but the rules are happy to run with them and michael's example 17:35:32 <bparsia> ...the conformance are silent on both these cases? 17:36:46 <bparsia> IanH: no, for Case 1 it certainly does. If you have a graph outside the syntactic subset, if the rule set finds an entailment then it's valid, but if it doesn't, you don't know if it's a non-entailment. If a system generates all the entailments the rule system does then it is conforment 17:36:52 <IanH> q? 17:37:46 <bparsia> ivan: Editorial point -- [[which the scribe didn't catch]] Is it possible to give a more precise description of what the rules do. 17:37:58 <bparsia> ...e.g., document everything the rules do and do not do. 17:38:24 <sandro> Test Cases! 17:38:28 <bparsia> IanH: I'm not sure what you want....you mean examples? But I don't see how useful that is. 17:38:32 <uli> good idea, Sandro 17:38:36 <IanH> q? 17:38:42 <IanH> ack Zhe 17:39:29 <bparsia> Zhe: I read the conformance carefully and update profiles. I think Ian has done a great job. Conformance is defined in such a way so a vendor using the rule set can claim conformance. Yay! And they can add additional rules! Double yay! Ian is my oxfordian hero! 17:39:39 <sandro> q+ to make minor editorial suggestion re "An OWL 2 RL entailment checker MAY report a warning unless..." 17:39:48 <bparsia> ...that's everything oracle wants. 17:40:09 <bparsia> IanH: so you're happy with the unification as described 17:40:22 <IanH> q? 17:40:28 <bparsia> Zhe: yes. 17:40:34 <bparsia> IanH: boris helped a lot too. 17:40:38 <msmith> +100 to Sandro 17:40:47 <bparsia> Zhe: Then I deeply admire his Oxfordian grace as well. 17:41:11 <Zhe> :) 17:41:22 <ivan> q+ 17:41:26 <sandro> ack sandro 17:41:26 <Zakim> sandro, you wanted to make minor editorial suggestion re "An OWL 2 RL entailment checker MAY report a warning unless..." 17:41:28 <ivan> ack sandro 17:41:52 <IanH> q? 17:42:01 <IanH> ack ivan 17:42:21 <bparsia> ivan: I'm very happy with what you guys did. Unification now. Unification tomorrow. Unification FOREVER! 17:42:30 <sandro> sandro: change to something like "An OWL 2 RL entailment checker MAY warn the user about any of these situations: (1) ... (2) .... (3) .... " 17:42:41 <sandro> Isn't there some big meeting in Denver about unification? 17:42:43 <m_schnei> not yet, yes! 17:43:18 <JeffP> OK 17:43:27 <bparsia> IanH: If everyone is happy, we can propose a resolution for next time...how do people feel 17:43:30 <bparsia> I love it! 17:43:35 <bparsia> Super love it! 17:44:14 <IanH> q? 17:44:19 <bparsia> sandro: Has RPI had a chance to look at it? Jie? 17:44:48 <bparsia> Jie: not sure 17:44:57 <bparsia> sandro: we're curious about Jim. 17:45:05 <bparsia> Jie: I'll talk with jim to clarify. 17:45:29 <IanH> q? 17:45:33 <msmith> I will look at aligning the test doc to this 17:45:35 <bparsia> ivan: More editorialness 17:45:44 <bparsia> ...which document will have the conformance 17:45:55 <bparsia> IanH: In the test document as with OWL 1. 17:46:24 <bparsia> ivan: That's not such a great idea. Test document isn't a very public place. Let's make it more public and acceptable. But where, I don't know. 17:46:28 <sandro> +1 ivan Conformance is kind of misplaced being in Test Cases 17:46:33 <bparsia> q+ 17:46:36 <ewallace> I used the test document from OWL 1 and I'm not an implementer 17:46:54 <m_schnei> but the testcases document looks the "least wrong" document to me 17:46:59 <bparsia> IanH: It's not clear where to put it without splitting nup 17:47:03 <IanH> q? 17:47:04 <ivan> q+ 17:47:10 <sandro> Sandro: what about in Profiles? 17:47:14 <IanH> ack bparsia 17:47:37 <MarkusK> +1 to bijan's proposal 17:47:38 <sandro> Bijan: How about calling the document "OWL 2 Conformance" which includes this stuff plus test cases 17:47:42 <ewallace> +1 to calling test, conformance 17:47:45 <IanH> q? 17:47:49 <IanH> ack ivan 17:48:15 <bparsia> ivan: I like Bijan's proposal. he's great! But I also want to put it in the semantics document? 17:48:23 <bparsia> IanH: But *which* semantics document 17:48:28 <bparsia> ivan: You win 17:48:43 <IanH> q? 17:49:36 <IanH> q? 17:50:01 <sandro> Sandro: It might make sense to keep the test cases out of any printable document. 17:50:38 <bparsia> Topic: 116 Axiomatic triples 17:50:39 <IanH> q? 17:50:44 <bparsia> Kill them! 17:50:56 <bparsia> q+ 17:51:03 <Zhe> q+ 17:51:08 <IanH> q? 17:51:14 <IanH> ack bparsia 17:51:34 <sandro> Ian: You don't have to have them to be conformant, but you can add them if you want and still be conformant. 17:51:58 <sandro> Bijan: So far, people have had to sort through to figure out which rules make sense to have, in practice. 17:52:09 <IanH> q? 17:52:32 <ivan> q+ 17:52:37 <ivan> ack Zhe 17:53:14 <bparsia> Zhe: Now that conformance rocks, I agree with Bijan. We have all the rules, even the dumb ones, in RDFS, but we tell users to turn them off! 17:53:15 <IanH> q? 17:53:19 <m_schnei> q+ 17:53:36 <IanH> q? 17:53:39 <bparsia> IanH: If we include them, then you *have* add them to be conformant! 17:53:43 <ivan> ack ivan 17:54:07 <m_schnei> and one for Simple Entailment 17:54:12 <m_schnei> and one for D entailment 17:54:17 <IanH> q? 17:54:18 <bparsia> ivan: The issue (as I've raised it) is imprecise, because we have two RDF rulesets (one for RDF and one for RDFS and one for Simple Entailment) 17:54:59 <bparsia> ...So I'm inclined to agree with Zhe [and BIJAN!] that these should be optional. Editorially, we should say something about these extra ones e.g., in the Primer. 17:55:21 <m_schnei> zakim, unmute me 17:55:21 <Zakim> m_schnei should no longer be muted 17:55:21 <bparsia> IanH: It'd be better to have opt-in rather than opt-out 17:55:22 <IanH> q? 17:55:30 <IanH> ack m_schnei 17:55:56 <bparsia> q+ 17:56:10 <bparsia> m_schnei: I agree we shouldn't make them part of the spec (for the above reasons) but there may be people who want this. 17:56:13 <ivan> informational annex? 17:56:19 <bparsia> ...And we should tell them. 17:56:41 <IanH> q? 17:56:50 <ivan> ack bparsia 17:56:59 <m_schnei> zakim, mute me 17:56:59 <Zakim> m_schnei should now be muted 17:58:05 <ivan> q+ 17:58:07 <bparsia> bparsia: I'm against a note, but some discussion is ok 17:58:15 <ivan> ack ivan 17:58:17 <IanH> ack ivan 17:58:26 <bparsia> IanH: but it'd be ok to have a little discussion including implementation costs. 17:58:28 <sandro> Ian: It would be okay to have a statement like "here are some extra rules you might want, but they have drawbacks", right? 17:58:36 <IanH> q? 17:58:39 <Zhe> +1 to ivan 17:58:42 <bparsia> ivan: Don't even include the rules. Just point them to the RDF sematntics document 17:59:05 <IanH> q? 17:59:29 <sandro> +1 to having these extra rules in an appendix or something 17:59:32 <bparsia> "Please note, the current rule set do not include *all* the rules necessary for RDF, or RDFS enatilment (see RDF semantics). The rules not included generally are not very useful and complicate the implementation unduely." 18:00:15 <m_schnei> please no suggestions in the technical documents 18:00:46 <IanH> q? 18:01:41 <bparsia> ivan: we should wait until the rest of the document finalized first. 18:01:46 <uli> +1 to Ian 18:01:49 <msmith> it seems very odd to make a note to ourselves but not put that note in the document 18:02:05 <sandro> uli, not that when you do that as you did, with "/me" your nice words don't end up in the minutes. 18:02:07 <bparsia> IanH: isn't this orthogonal to the unification? Shouldn't we proceed. 18:02:10 <sandro> s/not/Note/ 18:02:24 <bmotik> The Profiles document is not that far away from being finished 18:02:30 <uli> thanks, Sandro 18:02:45 <bmotik> We could easily add this remark at the end of the rules section 18:03:07 <bparsia> I prefer concrete examples 18:03:11 <bmotik> I can send an e-mail proposing resolution and then we can vote next week 18:03:44 <bmotik> Zakim, unmute me 18:03:44 <Zakim> bmotik should no longer be muted 18:04:30 <IanH> q? 18:04:32 <bmotik> Zakim, mute me 18:04:32 <Zakim> bmotik should now be muted 18:04:41 <bparsia> IanH: We'll make changes to the draft and then discuss and resolve the issues at once. 18:05:15 <bmotik> ACTION bmotik2: to Insert some text into the Profiles document regarding axiomatic triples 18:05:16 <trackbot> Created ACTION-204 - Insert some text into the Profiles document regarding axiomatic triples [on Boris Motik - due 2008-09-03]. 18:05:32 <IanH> q? 18:05:34 <bparsia> Topic: 141 Rogue Literals 18:06:21 <m_schnei> +1 to generalized RDF graphs 18:06:22 <sandro> +1 it's okay since these are just instances of t/3 predicate 18:06:22 <IanH> q? 18:06:25 <ivan> q+ 18:06:25 <bparsia> IanH: Peter says that it's not a problem since we need a slight generaliation of triples 18:06:33 <bparsia> ...appears in the rif document 18:06:38 <bparsia> and the SPARQL document. 18:06:41 <Zhe> q+ 18:06:49 <IanH> q? 18:06:51 <Carsten> Have to leave, sorry. 18:06:59 <ivan> ack ivan 18:07:03 <Zakim> -Carsten 18:07:04 <bparsia> ivan: RIF says that they act on generalize graphs/triples 18:07:18 <bparsia> IanH: Yeah, that's basically what the T predicate does. 18:07:19 <IanH> ack Zhe 18:07:39 <bparsia> Zhe: Does this mean that implementors must filter out illegal triples. 18:07:59 <bparsia> q+ to talk about sparql 18:08:09 <IanH> q? 18:08:21 <bparsia> IanH: conformance only talks about ground triples so the rogue ones never get in 18:08:33 <bmotik> No 18:08:35 <bmotik> q+ 18:08:37 <bparsia> ...If they return the rogue triples they might be unsound for owl full? 18:08:51 <ivan> ack bparsia 18:08:51 <Zakim> bparsia, you wanted to talk about sparql 18:09:38 <ivan> q+ 18:10:26 <bmotik> Zakim, unmute me 18:10:26 <Zakim> bmotik should no longer be muted 18:10:52 <bparsia> bparsia: You might have to filter (or might not) to conform with SPARQL...further investigation further. 18:11:27 <bparsia> bmotik: I don't think you'd *want* to filter them. They aren't unsound, but the question is how to *represent* the consequence in RDF, but they are *definitely* consequences. 18:11:38 <IanH> q? 18:11:41 <bmotik> Zakim, mute me 18:11:41 <Zakim> bmotik should now be muted 18:11:43 <ivan> ack bmotik 18:11:53 <bparsia> more from bparsia: The problem is construct vs. select, potentially 18:11:55 <bmotik> Zakim, mute me 18:11:55 <Zakim> bmotik should now be muted 18:12:15 <bparsia> IanH: My conclusion is that this isn't a problem with our spec. 18:12:25 <IanH> q? 18:12:28 <IanH> ack ivan 18:12:58 <bparsia> ivan: To muddy the water: There's another illegal triple: blank node as properties, can those come up? 18:13:45 <bparsia> IanH: Even that isn't an issue for our spec since we don't say what to return. 18:14:00 <bparsia> q+ 18:14:20 <IanH> q? 18:14:23 <ivan> ack bparsia 18:14:56 <m_schnei> _:p inverse q . x q y --> y _:p x 18:15:35 <IanH> q? 18:15:40 <bmotik> Note that our spec doesn't say anything about what triples you should return to answers of queries 18:15:55 <uli> sounds fine to me 18:16:01 <bparsia> bparsia: I yield to IanH awesomeness 18:16:19 <IanH> q? 18:16:36 <bparsia> IanH: Everyone comfy? ivan? 18:16:41 <bparsia> ivan: Yes. 18:16:51 <bparsia> IanH: We'll aim for a resolution in the next week or so. 18:16:58 <bparsia> Topic: 109 namespaces 18:17:01 <bparsia> q+ 18:17:13 <IanH> ack bparsia 18:17:49 <sandro> Bijan: There are local names common to the XML syntax and the RDF serialization. I forget which ones. So there would be qnames where if you concat'd both parts you'd get something else with the same URI. 18:18:12 <IanH> q? 18:18:14 <ivan> q+ 18:18:18 <IanH> q? 18:18:19 <ivan> ack ivan 18:18:22 <IanH> ack ivan 18:18:34 <bparsia> ivan: I disagree but I have no new evidence. 18:18:35 <m_schnei> there was no discussion on this at F2F§ 18:18:49 <m_schnei> s/F2F§/F2F3/ 18:19:03 <bparsia> ...It'd be repeating the mistake of RDF. 18:19:15 <IanH> q? 18:19:42 <IanH> q? 18:21:48 <bparsia> Sandro: I'm with Ivan on borderline objecting 18:21:59 <bparsia> bparsia: bparsia: I'd probably object 18:22:25 <bparsia> IanH: Could you (sandro) check with the w3c. 18:22:35 <IanH> q? 18:23:54 <IanH> q? 18:24:11 <bparsia> bparsia: Do actual users matter more? 18:24:27 <bparsia> sandro: There is a tag finding saying it's ok and I'd have trouble objecting in light of that. 18:24:58 <IanH> q? 18:24:59 <ivan> q+ 18:25:05 <bparsia> sandro: And I get Bijan's point that the users of the XML syntax are critical here. 18:25:11 <IanH> ack ivan 18:25:50 <bparsia> ivan: I don't fully agree with sandro, but I am extrapolating from the RDF/XML experience when people have had confusion. 18:26:06 <bparsia> q+ 18:26:12 <IanH> q? 18:26:20 <ivan> ack bparsia 18:26:24 <m_schnei> rdf:ID, rdf:about, ... 18:27:10 <sandro> Bijan: Ivan, in my experience, that's not a prevalent error -- most people understand the situation okay. Is it big in your judgement? 18:27:31 <IanH> q? 18:27:39 <bparsia> ivan: I see it as a problem for learning. 18:27:42 <sandro> ivan: I have seen it a lot. It's a learning problem. They do understand it eventually. 18:28:03 <sandro> Bijan: So it's ease-of-learning vs ease-of-use. 18:28:25 <m_schnei> funny is "rdf:resource" and "rdfs:Resource" :-) 18:28:32 <uli> throw a dice? 18:29:02 <sandro> 18:29:11 <uli> can we have Bijan and Ivan discuss during this week and then report back? 18:29:17 <Zakim> -Evan_Wallace 18:29:21 <JeffP> thanks, bye 18:29:22 <Zakim> -msmith 18:29:22 <Zhe> bye 18:29:23 <Zakim> -bcuencagrau 18:29:23 <Zakim> -Ivan 18:29:24 <MarkusK> bye 18:29:25 <Zakim> -bmotik 18:29:25 <Zakim> -Achille 18:29:28 <uli> bye 18:29:29 <Zakim> -JeffP 18:29:30 <Zakim> -Zhe 18:29:32 <bparsia> How about uli and sandro :)_ 18:29:32 <Zakim> -MarkusK 18:29:36 <sandro> :-) 18:29:39 <Zakim> -uli 18:29:43 <Zakim> -Sandro 18:29:44 <Zakim> -m_schnei 18:29:45 <Zakim> -bparsia 18:29:46 <Zakim> -IanH 18:29:47 <sandro> flip-coin.com said "same ns". 18:29:56 <bparsia> YAY! 18:30:14 <sandro> (but I should still check with some of my co-workers. :-( ) | https://www.w3.org/2007/OWL/wiki/index.php?title=Chatlog_2008-08-27&mobileaction=toggle_view_mobile | CC-MAIN-2015-11 | refinedweb | 4,287 | 70.43 |
The CSV importer provides a powerful and flexible way to import data from a comma-separated file, which is a format supported by
most applications (e.g. Microsoft Excel).
Importing from a CSV file is a three step process. First, you need to prepare and verify your CSV file. Next,
create a mapping file by running the CSV import wizard. (The mapping file is a plain text properties
file that you can also manually edit. It will map your CSV fields to fields in JIRA.)
Finally, to perform the import, simply enter the location of your import file and your configuration file.
Note: Before you begin, please backup your JIRA data.
The first thing you need to do is to ensure that your CSV is a valid CSV format. A good way to check is to import
your file into a spreadsheet (e.g. Microsoft Excel, Open Office) and see if the data is as expected. This is also a
good opportunity to do any massaging of the data, if you wish.
If you have values that signify a blank value (e.g. <blank> or None), it's best if you simply remove them in this step.
For built-in JIRA fields (e.g. Fix-for version, Affects version, Component),
if you wish to set more then one value for an issue, you will need to have a value per column in your CSV, with each column given
a distinct name. For example:
IssueType,Summary,FixVersion_1,FixVersion_2
bug,"First issue",v1,
bug,"Second issue",v2,
bug,"third issue",v1,v2
In this example, the third imported issue will have its Fix-for version set to multiple values.
For custom fields the situation is different, and multiple values are comma-separated. See below for details.
The CSV importer assumes a Microsoft Excel styled CSV file. Fields are separated by commas, and enclosed in quotes
if they contain commas or quotes. Embedded quotes are doubled.
There are two requirements of the CSV, in addition to being well-formed in general:
You can also have multi-lined CSV. For example, here is a valid file with a single record:
Summary,Description,Status
Login fails,"This is on
a new line",Open
JIRA will read the CSV file using the system encoding, which can be seen in Administration
-> System Info. Make sure that you either save the CSV file with this encoding, or set -Dfile.encoding on startup to force the system encoding to be what
you're using (utf8 is best).
If a row contains more columns than there are header columns, then the excess columns will be
added as comments (though see JRA-7672.
The next step of the import process is to run the import configuration wizard to determine how the CSV data can be
mapped to JIRA fields.
Bring up the administration page by clicking either the 'Administration' link on the top bar or the title of the
Administration box on the dashboard:
The 'CSV Import Wizard: Setup' page will be displayed:
You can optionally specify the delimiter your CSV file used. Leave the field blank if you wish to use the (default) comma delimiter.
Please note that the delimiter can only be one character long.
The first step is to choose which project the issues will be imported into. You can import into a new project or an existing project.
If certain project details (e.g. name and key) match an existing project, then the issues will be
imported into an existing project. Note that if you are creating a new project, no validations are performed at this time — invalid
data will result in a failure later, at import time.
If you want to import into multiple projects, you must map project information from the CSV file itself. That means that all rows must have the
project information in them.
The recommended import method is a single project per CSV file, imported into an existing project.
The second step is to decide which CSV fields you want to import. The screen shows all the columns that are found in your CSV file,
and a sample data row. On this screen you can map each column of your CSV file to system fields in JIRA, or leave as None to
not import. You can optionally create new custom fields on the fly or import into an existing custom field.
You can select multiple fields to be combined into Version and Component fields. For example, you can
import from 'Raised Version' and 'Found in Version' into the 'Affects Versions'
field. For Versions and Components, the importer will detect if the version exists in JIRA for the project . If it doesn't exist,
then it will automatically created.
User fields (Assignee and Reporter) are assumed to be in a 'FirstName LastName' format. New users
will be created with the username as 'FirstNameLastName'; spaces, apostrophes and brackets are stripped out. If the name only
has one word, that one word will be used as the username.
In most cases when importing system fields values like Priority, >Issue Type, Status
and Resolution, you will need to map the field values. The
mapping needs to be done even if the imported CSV file has the values set to 'valid' names, e.g. Issue Type set to
'Bug' or 'New Feature'. The only alternative to mapping the values is to change the CSV file such that
it contains the exact IDs of JIRA's priorities, issue types, statuses and
resolutions instead of their names. This requires you to determine the correct IDs and then
update the whole CSV file, so it is easier to map the values during the import.
As of JIRA 3.7 you can now import into the 'Original Estimate', 'Remaining Estimate', and 'Time Spent' fields.
For these fields to be available you must have enabled time tracking within JIRA. The importer expects the
estimate or time spent to be expressed in seconds. A value that is not able to be converted to a numeric value
will be ignored and not imported.
The portion of the importer that converts the raw string to a java.lang.Long which represents number of
seconds is customizable. If you are trying to import data that needs to more intelligently process the
value (more than just converting the string to a numeric value) you can write your own java class. It
needs to implement the com.atlassian.jira.imports.csv.mapper.TimeEstimateConverter interface and you can
direct the importer to use your class by specifying in the csv.properties configuration file the
'settings.advanced.mapper.time.estimate.converter' property (i.e.
settings.advanced.mapper.time.estimate.converter=com.atlassian.jira.imports.csv.mappers.SimpleTimeEstimateConverter=
com.atlassian.jira.imports.csv.mappers.SimpleTimeEstimateConverter)
You can also map a column to an existing custom field or create a new
custom field on the fly. Currently you can only create certain custom fields on
the fly. All custom fields created this way will be globally scoped. Moreover,
if the name matches an existing custom field, that existing custom field will
be used instead. If you are worried about how this works exactly, we recommend
that you create your custom fields first before importing them.
If you map to a select list custom field, all unique values will be created as options at import time. If you map to a multiple select field,
its values should be separated by a comma. If the field values have commas in them, the commas should be escaped with a backslash. Thus the field:
"Wally\, I,Wally\, II"
would be translated into one field with multiple values:
Once again, no data validations are done at configuration time, so you should ensure that the data you are trying to import is of a compatible type.
You may wish to map certain values in your CSV file to a different value. For example, you might map the field 'Severity' to
JIRA's 'Priority' field. JIRA expects the ID of priorities that exist in JIRA. Thus for this field, you'll need to check
the Map field value check-box. This will affect the next screen that you will come to.
Value mappings determine how values from your CSV importer will be 'translated' to match the values expected by JIRA. This is
usually required for fields such as 'Issue Type', 'Resolution', 'Priority' and
'Status', but can also apply to other fields. On this screen, all unique values for each field you selected
to be mapped have been displayed. You can now map any of these values to their values in JIRA. Leave the field blank if you
wish to import the value as-is. If you want to clear a field, enter the keyword <<blank>>.
On the 'Field Mappings' screen, each field has a checkbox under the heading 'Map values'.
If you check these boxes you will be able to map the values of these fields when you progress to the next page.
For fields mapping to Resolution, Priority and Issue Type, you
will get a select list with the available values in JIRA. In addition you can quickly create values that do not
exist in JIRA by clicking the green plus symbols. These will become issue constants that you can change at a
later time.
For fields mapping to Status, you will get the select list with JIRA's available values, but no
plus symbol for creating new status values.
For these fields, there are two special options in the select list in addition to JIRA's available values,
'Import as blank' and 'No mapping'. 'Import as blank' causes the JIRA value to
be blank for that field. 'No mapping'
blank option is selected.
You will be asked to enter some extra information on this screen, such as:
The final step of the Wizard allows you to save the configuration file on your server.
Saving the configuration file enables you to import more CSV files later without going through the
Configuration Wizard again.
Please ensure you enter a valid path. Alternatively, you can choose
to continue on with the import without saving the configuration in a file.
You can also see a preview of the mapping file that will be saved.
Once you have your configuration file, you can then import the CSV file
into JIRA.
The 'Settings' page gives you precise control over what will be imported
on each import run.
Once the import has begun you will be able to follow the progress of the
import, with the screen refreshing around every 10 seconds. You can change this
rate by updating the field at the bottom of the page. The importer also give
you statistics about what objects have been imported and time elapsed so you can
have an idea as approximately how long the import will take. You can also
choose to 'Abort' the import, which will cease importing after the current issue
is done.
The CSV Importer doesn't import all the objects available in JIRA at present. You can find
these limitations at issue JRA-5774.
Copyright © 2008 Atlassian Pty Ltd. All rights reserved. Your privacy is important to us. | http://www.atlassian.com/software/jira/docs/latest/csv_import.html | crawl-001 | refinedweb | 1,857 | 63.8 |
I've just returned from the second Jini Community Summit, where Ken Arnold and I led a birds-of-a-feather session on JavaSpaces. This encouraging meeting highlighted a number of interesting JavaSpaces applications, including Bill Olivier's JavaSpaces-based email system at the University of Wales. Also featured was the Department of Defense's explorations of battlefield management software, in which battlefield resources, such as tanks, are represented in a space.
In addition, there was significant interest in continuing to advance the JavaSpaces technology, and a number of areas were suggested for its improvement. One problem that the conference attendees wanted to confront was the painful process of setting up and running JavaSpaces (as well as Jini) for the first time -- probably the greatest barrier to using the technology. This problem is now being addressed in a new working group started by Ken Arnold, called Out of the Box (for more information, see the Resources section at the end of the article). Another area of community effort involves the development of helper or utility interfaces and classes that provide a valuable set of tools for new JavaSpaces developers. This article is based around one of those tools in particular: the compute server.
Basically, a compute server is an implementation of a powerful, all-purpose computing engine using a JavaSpace. Tasks are dropped into the space, picked up by processes, and then computed; the result is written back into the space and, at some point, retrieved. Beginning JavaSpaces programmers often ask how to implement such a system; in fact, the JavaSpaces Technology Kit ships with two sample compute servers, which perform computations for ray tracing and cryptography.
Compute servers are quite useful even for advanced programming. At the Jini Summit, it was decided that a common set of interfaces should be created to standardize JavaSpaces-based compute servers so that programmers could avoid reinventing the wheel every time they wanted to implement one. As a result, the community has created a working group whose goal is to build a specification and reference implementation of a compute-server architecture. One aim of this article is to kick off that work.
The compute server explained
A.
Compute server design
Let's start with a big picture of the compute server and its relation to JavaSpaces. The typical space-based compute server looks like the figure below. A master process generates a number of tasks and writes them into a space. When we say task in this context, we mean an entry that both describes the specifics of a task and contains methods that perform the necessary computations. One or more worker processes monitor the space; these workers take tasks as they become available, compute them, and then write their results back into the space. Results are entries that contain data from the computation's output. For instance, in a ray-tracing compute server, each task would contain the ray-tracing code along with a few parameters that tell the compute process which region of the ray-traced image to work on. The result entry would contain the bytes that make up the ray-traced region.
A space-based compute server
(Illustration by James P. Dustin, Dustin Design)
There are some nice properties the contribute to compute servers' ubiquity in space-based systems. First of all, they scale naturally; in general, the more worker processes there are, the faster tasks will be computed. You can add or remove workers at runtime, and the compute server will continue as long as there is at least one worker to compute tasks. Second, compute servers balance loads well -- if one worker is running on a slower CPU, it will compute its tasks more slowly and thus complete fewer tasks overall, while faster machines will have higher task throughput. This model avoids situations in which slow machines becoming overwhelmed while fast machines starve for work; instead, the load is balanced because the workers perform tasks when they can.
In addition, the masters and workers in this model are uncoupled; the workers don't have to know anything about the master or the specifics of the tasks -- they just grab tasks and compute them, returning the results to the space. Likewise, a given master doesn't need to worry about who computes its tasks or how, but just throws tasks into a space and waits. The space itself makes this very easy, as it provides a shared and persistent object store where objects can be looked up associatively (for more details on these aspects of spaces, please refer to November's column). In other words, the space allows a worker to simply request any task, and receive a task entry when one exists in the space. Similarly, the master can ask for the computational results of its (and only its) tasks -- without needing to know the specifics of where these results came from.
Finally, the space provides a feature that makes this all work seamlessly: the ability to ship around executable content in objects. This is feasible because Java (and Jini's underlying RMI transport) makes underlying class loading possible. How does this work? Basically, when a master (or any other process, for that matter) writes an object into a space, it is serialized and transferred to that space. The serialized form of the object includes a
codebase, which identifies the place where the class that created the object resides. When a process (in this case, a worker) takes a serialized object from the space, it then downloads the object from the appropriate
codebase, assuming that its JVM has not downloaded the class already. This is a very powerful feature, because it lets your applications ship around new behaviors and have those behaviors automatically installed in remote processes. This capability is a great improvement over previous space-based compute servers, which required you to precompile the task code into the workers.
Implementing the compute server
For masters and workers to exchange task objects, they must agree on a common interface for those objects. There aren't many requirements for the task object (at least in this simple implementation); all that is really needed is a method that instructs the task to start computing.
The well known Command pattern is used for this purpose. The interface for the Command pattern looks like this:
public interface Command { public void execute(); }
This pattern, which consists of a single method (typically called
execute), lets you decouple the object that invokes an operation from the object that can perform it. In this case, the object that will invoke the operation is a worker that has cycles to spare and time to compute a task. The object that knows how to perform the operation is the task itself. Different master processes are free to implement various execution methods, so that workers can perform a variety of computations for different masters. See Resources for pointers to information about Command and other patterns.
To make use of the Command interface in this compute server, you must augment it:
package javaworld.simplecompute;
import net.jini.core.entry.Entry;
public interface Command extends Entry { public Entry execute(); }
Note that I've added
extends Entry to the interface definition and imported the
Entry class from the
net.jini.core.entry package. You may recall from Part 1 of our series that, for an object to be written into a space, it must be instantiated from a class that implements the
Entry interface. I've also changed the return type of the
execute method to return an object of type
Entry. This provides a way for computations to place results back into the space. We'll discover how this is done as we take our next step: implementing the worker.
The worker
The worker is a straightforward concept: it continually looks for a task, takes it from the space, computes it, returns a result (if the task specifies that this is to be done), and then starts over. Here is the code:
package javaworld.simplecompute;
import jsbook.util.*;
import net.jini.core.entry.Entry; import net.jini.core.lease.Lease; import net.jini.space.JavaSpace;
public class Worker {"); } } } } | http://www.javaworld.com/article/2076892/embedded-java/make-room-for-javaspaces--part-2.html | CC-MAIN-2016-30 | refinedweb | 1,358 | 50.67 |
JBoss.orgCommunity Documentation
Version 5.3.0.Beta1
Abstract
This manual provides complete documentation for Guvnor.
This section introduces the.)).
Once you have at least one category and one package setup, you can author rules..
Chose the "Business rule (guided editor)" formats.
This will open a rule modeler, which is a guided editor. You can add and edit conditions and actions based on the model that is in use in the current package. Also, any DSL sentence templates setup for the package will be available. recored.
The above picture shows the package explorer. Clicking on an asset type will show a list of matches (for packages with thousands of rules, showing the list may take several seconds - hence the importance of using categories to help you find your way around).".
The package management feature allows you to see a list of packages, and then "expand" them, to show lists of each "type" of asset (there are many assets, so some of them are grouped together):
The asset types:
Business assets: this shows a list of all "business rule" types, which include decision tables, business rules etc. etc.
Technical assets: this is a list of items that would be considered technical (e.g. DRL rules, data enumerations and rule flows).
Functions: In the Guvnor you can also have functions defined (optionally of course).
DSL: Domain Specific Languages can also be stored as an asset. If they exist (generally there is only one), then they will be used in the appropriate editor GUIs.
Model: A package requires at least one model - for the rules.
WorkingSets: Working Sets let you create subsets of package's Fact Types and apply constraints to their fields.
From the package explorer you can create new rules, or new assets. Some assets you can only create from the package explorer. The above picture shows the icons which launch wizards for this purpose. If you hover the mouse over them, a tooltip will tell you what they do.
One of the most critical things you need to do is configure packages.
This is mostly importing the classes used by the rules, and globals
variables. Once you make a change, you need to save it, and that package is
then configured and ready to be built. For example, you may add a model
which has a class called
com.something.Hello, you would then
add
import com.something.Hello in your package configuration
and save the change.
Finally you would "build" a package. Any errors caught are then shown at this point. If the build was successful, then you will have the option to create a snapshot for deployment. You can also view the DRL that this package results in.
In cases of large numbers of rules, all these operations can take some time.
It is optional at this stage to enter the name of a "selector" - see the admin section for details on how to configure custom selectors for your system (if you need them - selectors allow you to filter down what you build into a package - if you don't know what they are for, you probably don't need to use them)..). correspondig guided decision table is split into two main sections:-
The upper section allows table columns to be defined representing rule attributes, meta-data, conditions and actions.
The lower section contains the actual table itself; where individual rows define seperate rules...
This section alows individual rules to be defined using the columns defined earlier.Field1' and 'dependentField2' are names of fields on the 'Fact' type - these are used to calculate the list of values which will be shown in a drop down if values for the "field".
The two main ways of viewing the repository are by using user-driven Categorization (tagging) as outlined above, and the package explorer view.
The category view provides a way to navigate your rules in a way that makes sense to your organization.
The above diagram shows categories in action. Generally under each category you should have no more then a few dozen rules, if possible.
The alternative and more technical view is to use the package explorer. This shows the rules (assets) closer to how they are actually stored in the database, and also separates rules into packages (name spaces) and their type (format, as rules can be in many different formats).
The above shows the alternate way of exploring - using packages..
Snapshots, URLS and binary packages:
URLs are central to how built packages are provided. The deployment snapshots view. On the left there is a list of packages. Clicking on a specific package will show you a list of snapshots for that package (if any). From there you can copy, remove or view an asset snapshot. Each snapshot is available for download or access via a URL for deployment..
Each asset (and also package) in Guvnor has a status flag set. The values of the status flag are set in the Administration section of the Guvnor. (you can add your own status names). Similar to Categories, Statuses do NOT effect the execution in any way, and are purely informational. Unlike categories, assets only have one status AT A TIME.
Using statuses is completely optional. You can use it to manage the lifecycle of assets (which you can alternatively do with categories if you like).
You can change the status of an individual asset (like in the diagram above). Its change takes effect immediately, no separate save is needed.
You can change the status of a whole package - this sets the status flag on the package itself, but it ALSO changes the statuses on ALL the assets that belong to this package in one hit (to be the same as what you set the package to)..
<change-set xmlns=''";
xmlns:xs=''
xs:
<add>
<resource source='' type='PKG' />
</add>
</change-set>" - uses as entry point the categories defined for each rule asset when it is created by the user in Guvnor
We are giving a list of example i-as-5.1.war for JBoss http//localhost:8080/guvnor/ or (if you haven't rename the war
file) at something like http//localhost:8080/guvnor-5.2.0-jboss-as-5.1/.
components.xml file in
the
WEB-INF directory. This is a JBoss Seam configuration file (Seam 2 is the
framework used) which allows various parts of the system to be customized. When you have located the
components.xml file, you should see something like the following:
>
...
</component>
Find the component with a name of
repository
components.xml you can
simply move the
repository.xml AND the repository directory to the new
location that you set in the
components configuraiton underlaying/components.xml file to switch over to ModeShape. Comment out the JackRabbit section and uncomment the ModeShape section:
>
-->
<!-- ModeShape
passwords for the background users (admin and mailman), these need to match the setting
you provided for JAAS (used by ModeShape only).
-->
<property name="properties">
<key>org.drools.repository.configurator</key>
<value>org.drools.repository.modeshape.ModeShapeRepositoryConfigurator</value>
<key>org.modeshape.jcr.URL</key>
<value>jndi:jcr/local?repositoryName=repository</value>
<key>org.drools.repository.secure.passwords</key>
<value>false</value>
<key>org.drools.repository.admin.password</key>
<value>admin</value>
<key>org.drools.repository.mailman.password</key>
<value>mailman</value>
</property>
</component>}"/>
-->
<!--
FOR EXAMPLE: the following one will use the jaas configuration called
"other" - which in jboss AS means you can use properties files for
users:
-->
<security:identity
<!--
as JAAS is used you can use container specific ones to link up to your
login services, eg LDAP/AD etc
-->
components.xml file in the war file. To customize
this, you will need to unzip the WAR file, and locate the
components
components.xml file, you should located a security configuration section like
the following:
<!-- SECURITY and.
components
components.
The blog post contains a video showing
a full example on how to use the JackrabbitMigrationAntTask for repository migration.
components.xml. Refer to the Seam
documentation, and the
components 11,. The JIRA link to use is. | http://docs.jboss.org/drools/release/5.3.0.Beta1/drools-guvnor-docs/html_single/index.html | CC-MAIN-2015-27 | refinedweb | 1,337 | 56.66 |
I am migrating a project from MRI Ruby and Rails 2.x to JRuby and Rails
3. The app is not very complex, but it does use two databases - one
Postgres database that is the main application database, and one SQL
Server database from which I bring in some extra information (I do not
write to this DB or do any migrations on it)
This worked well until the port. Accessing the SQL Server database now
gives this error:
undefined method `identity=’ for
#ActiveRecord::ConnectionAdapters::JdbcColumn:0x13d285f
Oddly enough, if I start “rails console” and use the AR model that is
connected to SQL Server, I can run queries just fine, including the one
that caused the error above.
I spent some time trying to find a minimal repro, and have attached a
ZIP file containing my minimal rails app that is a repro for this
problem. First, some general information. Gems referred to in my
Gemfile:
- rails 3.0.1
- activerecord-jdbcpostgresql-adapter 1.1.1
- activerecord-jdbcmssql-adapter 1.1.1
User is an AR class referencing the postgres database
Registration is an AR class referencing the SQL Server database.
The test controller that produces the problem:
class TestController < ApplicationController
def index
@cur_user = User.find_or_create_by_name(“bob”)
Registration.find_all_by_activation_id(:first)
render :text => “hi”
end
end
Commenting out the line starting with @cur_user causes the problem to
stop happening.
Any ideas what might be going on here? Is this a JRuby or JDBC issue?
Thanks
Andrew | https://www.ruby-forum.com/t/jruby-rails3-and-multiple-database-connections/202927 | CC-MAIN-2022-33 | refinedweb | 246 | 54.93 |
Greg KH wrote:>.Well. Maybe directories really are of no use, but mknod/symlink/unlink*are* useful. That same mdadm who needs to create /dev/mdX *before*that device is created? And socket for /dev/log...And oh, directories.. devpts? Stuff like cciss/... represented in sysfslike cciss!... ?I don't see anything wrong with allowing creating/removing files inthe filesystem (except of possible locking issues which can arise) --in-kernel support just does mknod/unlink on insert/remove, and ifthat fails (EEXIST/ENOENT), well, so be it...And since the whole namespace is now flat, another question comes in:is there any guarantee the names will not overlap? /dev/ttyS0 and/dev/usb/ttyS0 (I don't remember which one it was, but I *think* Isaw same names but in different dirs in /dev...)/mjt-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2005/6/24/168 | CC-MAIN-2015-48 | refinedweb | 163 | 60.01 |
Understanding ES6 Modules
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
This article explores ES6 modules, showing how they can be used today with the help of a transpiler.
Almost every language has a concept of modules — a way to include functionality declared in one file within another. Typically, a developer creates an encapsulated library of code responsible for handling related tasks. That library can be referenced by applications or other modules.
The benefits:
-.
- Module code (usually) helps eradicate naming conflicts. Function
x()in module1 cannot clash with function
x()in module2. Options such as namespacing are employed so calls become
module1.x()and
module2.x().
Where are Modules in JavaScript?
Anyone starting web development a few years ago would have been shocked to discover there was no concept of modules in JavaScript. It was impossible to directly reference or include one JavaScript file in another. Developers therefore resorted to alternative options.
Multiple HTML
<script> Tags
HTML can load any number JavaScript files using multiple
.
Script Concatenation
One solution to problems of multiple
<script> tags is to concatenate all JavaScript files into a single, large file. This solves some performance and dependency management issues, but it could incur a manual build and testing step.
Module Loaders
Systems such as RequireJS and SystemJS provide a library for loading and namespacing other JavaScript libraries at runtime. Modules are loaded using Ajax methods when required. The systems help, but could become complicated for larger code bases or sites adding standard
<script> tags into the mix.
Module Bundlers, Preprocessors and Transpilers
Bundlers introduce a compile step so JavaScript code is generated at build time. Code is processed to include dependencies and produce a single ES5 cross-browser compatible concatenated file. Popular options include Babel, Browserify, webpack and more general task runners such as Grunt and Gulp.
A JavaScript build process requires some effort, but there are benefits:
- Processing is automated so there’s less chance of human error.
- Further processing can lint code, remove debugging commands, minify the resulting file, etc.
- Transpiling allows you to use alternative syntaxes such as TypeScript or CoffeeScript.
ES6 Modules
The options above introduced a variety of competing module definition formats. Widely-adopted syntaxes included:
- CommonJS — the
module.exportsand
requiresyntax used in Node.js
- Asynchronous Module Definition (AMD)
- Universal Module Definition (UMD).
A single, native module standard was therefore proposed in ES6 (ES2015).
Everything inside an ES6 module is private by default, and runs in strict mode (there’s no need for
'use strict'). Public variables, functions and classes are exposed using
export. For example:
// lib.js export const PI = 3.1415926; export function sum(...args) { log('sum', args); return args.reduce((num, tot) => tot + num); } export function mult(...args) { log('mult', args); return args.reduce((num, tot) => tot * num); } // private function function log(...msg) { console.log(...msg); }
Alternatively, a single
export statement can be used.:
// main.js import { sum } from './lib.js'; console.log( sum(1,2,3,4) ); // 10
In this case,
lib.js is in the same folder as
main.js. Absolute file references (starting with
/), relative file references (starting
./ or
../) or full URLs can be used.
Multiple items can be imported at one time:
import { sum, mult } from './lib.js'; console.log( sum(1,2,3,4) ); // 10 console.log( mult(1,2,3,4) ); // 24
and imports can be aliased to resolve naming collisions:
import { sum as addAll, mult as multiplyAll } from './lib.js'; console.log( addAll(1,2,3,4) ); // 10 console.log( multiplyAll(1,2,3,4) ); // 24
Finally, all public items can be imported by providing a namespace:
import * as lib from './lib.js'; console.log( lib.PI ); // 3.1415926 console.log( lib.add(1,2,3,4) ); // 10 console.log( lib.mult(1,2,3,4) ); // 24
Using ES6 Modules in Browsers
At the time of writing, ES6 modules are supported in Chromium-based browsers (v63+), Safari 11+, and Edge 16+. Firefox support will arrive in version 60 (it’s behind an
about:config flag in v58+).
Scripts which use modules must be loaded by setting a
type="module" attribute in the
<script> tag. For example:
<script type="module" src="./main.js"></script>
or inline:
<script type="module"> import { something } from './somewhere.js'; // ... </script>
Modules are parsed once, regardless of how many times they’re referenced in the page or other modules.
Server Considerations
Modules must be served with the MIME type
application/javascript. Most servers will do this automatically, but be wary of dynamically generated scripts or
.mjs files (see the Node.js section below).
Regular
<script> tags can fetch scripts on other domains but modules are fetched using cross-origin resource sharing (CORS). Modules on different domains must therefore set an appropriate HTTP header, such as
Access-Control-Allow-Origin: *.
Finally, modules won’t send cookies or other header credentials unless a
crossorigin="use-credentials" attribute is added to the
<script> tag and the response contains the header
Access-Control-Allow-Credentials: true.
Module Execution is Deferred
The
<script defer> attribute delays script execution until the document has loaded and parsed. Modules — including inline scripts — defer by default. Example:
<!-- runs SECOND --> <script type="module"> // do something... </script> <!-- runs THIRD --> <script defer</script> <!-- runs FIRST --> <script src="a.js"></script> <!-- runs FOURTH --> <script type="module" src="b.js"></script>
Module Fallbacks
Browsers without module support won’t run
type="module" scripts. A fallback script can be provided with a
nomodule attribute which module-compatible browsers ignore. For example:
<script type="module" src="runs-if-module-supported.js"></script> <script nomodule</script>
Should You Use Modules in the Browser?
Browser support is growing, but it’s possibly a little premature to switch to ES6 modules. For the moment, it’s probably better to use a module bundler to create a script that works everywhere.
Using ES6 Modules in Node.js
When Node.js was released in 2009, it would have been inconceivable for any runtime not to provide modules. CommonJS was adopted, which meant the Node package manager, npm, could be developed. Usage grew exponentially from that point.
A CommonJS module can be coded in a similar way to an ES2015 module.
module.exports is used rather than
export:
// lib.js const PI = 3.1415926; function sum(...args) { log('sum', args); return args.reduce((num, tot) => tot + num); } function mult(...args) { log('mult', args); return args.reduce((num, tot) => tot * num); } // private function function log(...msg) { console.log(...msg); } module.exports = { PI, sum, mult };
require (rather than
import) is used to pull this module into another script or module:
const { sum, mult } = require('./lib.js'); console.log( sum(1,2,3,4) ); // 10 console.log( mult(1,2,3,4) ); // 24
require can also import all items:
const lib = require('./lib.js'); console.log( lib.PI ); // 3.1415926 console.log( lib.add(1,2,3,4) ); // 10 console.log( lib.mult(1,2,3,4) ); // 24
So ES6 modules were easy to implement in Node.js, right? Er, no.
ES6 modules are behind a flag in Node.js 9.8.0+ and will not be fully implemented until at least version 10. While CommonJS and ES6 modules share similar syntax, they work in fundamentally different ways:
- ES6 modules are pre-parsed in order to resolve further imports before code is executed.
- CommonJS modules load dependencies on demand while executing the code.
It would make no difference in the example above, but consider the following ES2015 module code:
// ES2015 modules // --------------------------------- // one.js console.log('running one.js'); import { hello } from './two.js'; console.log(hello); // --------------------------------- // two.js console.log('running two.js'); export const hello = 'Hello from two.js';
The output for ES2015:
running two.js running one.js hello from two.js
Similar code written using CommonJS:
// CommonJS modules // --------------------------------- // one.js console.log('running one.js'); const hello = require('./two.js'); console.log(hello); // --------------------------------- // two.js console.log('running two.js'); module.exports = 'Hello from two.js';
The output for CommonJS:
running one.js running two.js hello from two.js
Execution order could be critical in some applications, and what would happen if ES2015 and CommonJS modules were mixed in the same file? To resolve this problem, Node.js will only permit ES6 modules in files with the extension
.mjs. Files with a
.js extension will default to CommonJS. It’s a simple option which removes much of the complexity and should aid code editors and linters.
Should You Use ES6 Modules in Node.js?
ES6 modules are only practical from Node.js v10 onwards (released in April 2018). Converting an existing project is unlikely to result in any benefit, and would render an application incompatible with earlier versions of Node.js.
For new projects, ES6 modules provide an alternative to CommonJS. The syntax is identical to client-side coding, and may offer an easier route to isomorphic JavaScript, which can run in the either the browser or on a server.
Module Melee
A standardized JavaScript module system took many years to arrive, and even longer to implement, but the problems have been rectified. All mainstream browsers and Node.js from mid 2018 support ES6 modules, although a switch-over lag should be expected while everyone upgrades.
Learn ES6 modules today to benefit your JavaScript development tomorrow.
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS! | https://www.sitepoint.com/understanding-es6-modules/?aref=cbuckler | CC-MAIN-2021-10 | refinedweb | 1,559 | 52.26 |
[Essential .NET]
Essential MSBuild: A Build Engine Overview for .NET Tooling
By Mark Michaelis | January 2017
Those of you who have been following .NET Core over the past few years (has it been that long?) know all too well that the “build system” has experienced a significant amount of flux, whether it be dropping built-in support for gulp or the demise of Project.json. For me as a columnist, these changes have been challenging as I didn’t want you, my dear readers, to spend too much time learning about features and details that ultimately were only going to be around for a few months. This is why, for example, all my .NET Core-related articles were built on Visual Studio .NET 4.6-based *.CSPROJ files that referenced NuGet packages from .NET Core rather than actually compiled .NET Core projects.
This month, I’m pleased to report, the project file for .NET Core projects has stabilized into (would you believe) an MSBuild file. However, it’s not the same MSBuild file from earlier Visual Studio generations, but rather an improved—simplified—MSBuild file. It’s a file that (without getting into religious wars about curly vs. angle brackets) includes all the features of Project.json but with the accompanying tool support of the traditional MSBuild file we’ve come to know (and perhaps love?) since Visual Studio 2005. In summary, the features include open source, cross-platform compatibility, a simplified and human-editable format and, finally, full modern .NET tool support including wildcard file referencing.
Tooling Support
To be clear, features such as wild cards were always supported in MSBuild, but now the Visual Studio tooling works with them, as well. In other words, the most important news about MSBuild is that it’s tightly integrated as the build system foundation for all the new .NET Tooling—DotNet.exe, Visual Studio 2017, Visual Studio Code and Visual Studio for Mac—and with support for both .NET Core 1.0 and .NET Core 1.1 runtimes.
The big advantage of the strong coupling between .NET Tooling and MSBuild is that any MSBuild file you create is compatible with all the .NET Tooling and can be built from any platform.
The .NET Tooling for MSBuild integration is coupled via the MSBuild API, not just a command-line process. For example, executing the .NET CLI command Dotnet.exe Build doesn’t internally spawn the msbuild.exe process. However, it does call the MSBuild API in process to execute the work (both the MSBuild.dll and Microsoft.Build.* assemblies). Even so, the output—regardless of the tool—is similar across platforms because there’s a shared logging framework with which all the .NET Tools register.
*.CSPROJ/MSBuild File Structure
As I mentioned, the file format itself is simplified down to the bare minimum. It supports wildcards, project and NuGet package references, and multiple frameworks. Furthermore, the project-type GUIDs found in the Visual Studio-created project files of the past are gone.
Figure 1 shows a sample *.CSPROJ/MSBuild file.
<Project> <PropertyGroup> <TargetFramework>netcoreapp1.0</TargetFramework> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" /> <EmbeddedResource Include="**\*.resx" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.NETCore.App"> <Version>1.0.1</Version> </PackageReference> <PackageReference Include="Microsoft.NET.Sdk"> <Version>1.0.0-*</Version> <PrivateAssets>All</PrivateAssets> </PackageReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> </Project>
Let’s review the structure and capabilities in detail:
Simplified Header: To begin, notice that the root element is simply a Project element. Gone is the need for even the namespace and version attributes:
(Though, they’re still created in the release candidate version tooling.) Similarly, even the need for importing the common properties is merely optional:
Project References: From the project file, you can add entries to the item group elements:
- NuGet Packages:
- Project References:
- Assembly References:
A direct assembly reference should be the exception as a NuGet reference is generally preferred.
Wildcard Includes: Compiled code files and resource files can all be included via wildcards.
However, you can still select specific files to ignore using the remove attribute. (Note that support for wildcards is frequently referred to as globbing.)
Multi-Targeting: To identify which platform you’re targeting, along with the (optional) output type, you can use a property group with the TargetFramework elements:
Given these entries, the output for each target will be built into the bin\Debug or bin\Release directory (depending on which configuration you specify). If there’s more than one target, the build execution will place the output into a folder corresponding to the target framework name.
No Project Type GUIDs: Note that it’s no longer necessary to include a project-type GUID that identifies the type of project.
Visual Studio 2017 Integration
When it comes to Visual Studio 2017, Microsoft continues to provide a rich UI for editing the CSPROJ/MSBuild project file. Figure 2, for example, shows Visual Studio 2017 loaded with a CSPROJ file listing, slightly modified from Figure 1, that includes target framework elements for netcoreapp1.0 and net45, along with package references for Microsoft.Extensions.Configuration, Microsoft.NETCore.App, and Microsoft.NET.Sdk, plus an assembly reference to MSBuild, and a project reference to SampleLib.
Figure 2 Solution Explorer is a Rich UI on Top of a CSProj File
Notice how each dependency type—assembly, NuGet package or project reference—has a corresponding group node within the Dependencies tree in Solution Explorer.
Furthermore, Visual Studio 2017 supports dynamic reloading of the project and solution. For example, if a new file is added to the project directory—one that matches one of the globbing wild cards—Visual Studio 2017 automatically detects the changes and displays the files within the Solution Explorer. Similarly, if you exclude a file from a Visual Studio project (via the Visual Studio menu option or the Visual Studio properties window), Visual Studio will automatically update the project file accordingly. (For example, it will add a <Compile Remove="CommandLine.cs" /> element to exclude the CommandLine.cs file from compiling within the project.)
Furthermore, edits to the project file will be automatically detected and reloaded into Visual Studio 2017. In fact, the Visual Studio project node within Solution Explorer now supports a built-in Edit <Project File> menu option that opens the project file within the Visual Studio edit window without first requesting that you unload the project.
There’s built-in migration support within Visual Studio 2017 to convert projects to the new MSBuild format. If you accept its prompt, your project will automatically upgrade from a Project.json/*.XPROJ type to an MSBUILD/*.CSPROJ type. Note that such an upgrade will break backward compatibility with Visual Studio 2015 .NET Core projects, so you can’t have some of your team working on the same .NET Core project in Visual Studio 2017 while others use Visual Studio 2015.
MSBuild
I would be remiss to not point out that back in March 2016, Microsoft released MSBuild as open source on GitHub (github.com/Microsoft/msbuild) and contributed it to the .NET Foundation (dotnetfoundation.org). Establishing MSBuild as open source put it on track for platform portability to Mac and Linux—ultimately allowing it to become the underlying build engine for all the .NET Tooling.
Other than the CSPROJ\MSBuild file PackageReference element identified earlier, MSBuild version 15 doesn’t introduce many additional features beyond open source and cross platform. In fact, comparing the command-line help shows the options are identical. For those not already familiar with it, here’s a list of the most common options you should be familiar with from the general syntax MSBuild.exe [options] [project file]:
/target:<target>:Identifies the build target within the project file to execute along with any dependencies it might have (/t is the abbreviation).
/property:<n>=<v>: Sets or overrides any project properties (identified in the ProjectGroup element of a project file). For example, you can use the property to change the configuration or the output directory, as in /property:Configuration=Release;OutDir=bin\ (/p is the abbreviation).
/maxcpucount[:n]: Specifies the number of CPUs to use. By default, msbuild runs on a single CPU (single-threaded). If synchronization isn’t a problem you can increase that by specifying the level of concurrency. If you specify the /maxcpucount option without providing a value, msbuild will use the number of processors on the computer.
/preprocess[:file]: Generates an aggregated project file by inlining all the included targets. This can be helpful for debugging when there’s a problem.
@file: Provides one (or more) response files that contains options. Such files have each command-line option on a separate line (comments prefixed with “#”). By default, MSBuild will import a file named msbuild.rsp from the first project or solution built. The response file is useful for identifying different build properties and targets depending on which environment (Dev, Test, Production) you’re building, for example.
Dotnet.exe
The dotnet.exe command line for .NET was introduced about a year ago as a cross-platform mechanism for generating, building and running .NET Core-based projects. As already mentioned, it has been updated so that it now relies heavily on MSBuild as the internal engine for the bulk of its work where this makes sense.
Here’s an overview of the various commands:
dotnet new: Creates your initial project. Out of the box this project generator supports the Console, Web, Lib, MSTest and XUnitTest project types. However, in the future you can expect it to allow you to provide custom templates so you can generate your own project types. (As it happens, the new command doesn’t rely on MSBuild for generating the project.)
dotnet restore: Reads through the project dependencies specified in the project file and downloads any missing NuGet packages and tools identified there. The project file itself can either be specified as an argument or be implied from the current directory (if there’s more than one project file in the current directory, specifying which one to use is required). Note that because restore leverages the MSBuild engine for its work, the dotnet command allows for additional MSBuild command-line options.
dotnet build: Calls on the MSBuild engine to execute the build target (by default) within the project file. Like the restore command, you can pass MSBuild arguments to the dotnet build command. For example, a command such as dotnet build /property:configuration=Release will trigger a Release build to be output rather than a Debug build (the default). Similarly, you can specify the MSBuild target using /target (or /t). The dotnet build /t:compile command, for example, will run the compile target.
dotnet clean: Removes all the build output so that a full build rather than an incremental build will execute.
dotnet migrate: Upgrades a Project.json/*.XPROJ-based project into the *.CSPROJ/MSBuild format.
dotnet publish: Combines all the build output along with any dependencies into a single folder, thereby staging it for deployment to another machine. This is especially useful for self-contained deployment that includes not only the compile output and the dependent packages, but even the .NET Core runtime itself. A self-contained application doesn’t have any prerequisites that a particular version of the .NET platform already be installed on the target machine.
dotnet run: Launches the .NET Runtime and hosts the project and/or the compiled assemblies to execute your program. Note that for ASP.NET, compilation isn’t necessary as the project itself can be hosted.
There’s a significant overlap between executing msbuild.exe and dotnet.exe, leaving you with the choice of which one to run. If you’re building the default msbuild target you can simply execute the command “msbuild.exe” from within the project directory and it will compile and output the target for you. The equivalent dotnet.exe command is “dotnet.exe msbuild.” On the other hand, if you’re running a “clean” target the command is “msbuild.exe /t:clean” with MSBuild, versus “dotnet.exe clean” with dotnet. Furthermore, both tools support extensions. MSBuild has a comprehensive extensibility framework both within the project file itself and via .NET assemblies (see bit.ly/2flUBza). Similarly, dotnet can be extended but the recommendation for this, too, essentially involves extending MSBuild plus a little more ceremony.
While I like the idea of dotnet.exe, in the end it doesn’t seem to offer much advantage over MSBuild except for doing the things that MSBuild doesn’t support (of which dotnet new and dotnet run are perhaps the most significant). In the end, I feel that MSBuild allows you to do the simple things easily while still enabling the complicated stuff when needed. Furthermore, even the complicated stuff in MSBuild can be simplified down by providing reasonable defaults. Ultimately, whether dotnet or MSBuild is preferable comes down to preference, and time will tell which the development community generally settles on for the CLI front end.
global.json
While Project.json functionality has migrated to CSPROJ, global.json is still fully supported. The file allows specification of project directories and package directories, and identifies the version of the SDK to use. Here’s a sample global.json file:
The three sections correspond to the main purposes of the global.json file:
projects: Identifies the root directories in which .NET projects are located. The projects node is critical for debugging into the .NET Core source code. After cloning the source code, you can add the directory into the projects node and Visual Studio will then automatically load it up as a project within the solution.
packages: Indicates the location of your NuGet packages folder.
sdk: Specifies which version of the runtime to use.
Wrapping Up
In this article, I’ve provided a broad overview of all the places that MSBuild is leveraged within the .NET Tooling suite. Before closing, let me offer one bit of advice from my experience working on projects with thousands of lines of MSBuild. Don’t fall into the trap of scripting too much in a declarative, loosely typed language like the XML MSBuild schema. That’s not its purpose. Rather, the project files should be relatively thin wrappers that identify the order and dependencies among your build targets. If you let your MSBuild project file get too big, it can become a pain to maintain. Don’t wait too long before you refactor it into something like C# MSBuild tasks that can be debugged and easily unit tested.: Kevin Bost, Grant Erickson, Chris Finlayson, Phil Spokas and Michael Stokesbary
Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
Observing reaction of net developers in my company. I think backing from project.json is a mistake. Improving, wouldn't help. Readability and learning curve are not comparable. Also, Java and node programmers who started to pay close attention to Mic...
Jan 24, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
Haha yeah hard to find fault in your reasoning, David. I too have thought about this a bit and it's amazing how at the end of the day how little feedback there is given the scope and breadth of the market here. The medium used also matters, as wel...
Jan 19, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
I know people have been going mad over this. But yeah, those that don't engage, it's them that make up the 98%. Not you (I've seen your handle before) or me. Those at their desk doing their job, not following blog posts or twitter or github, not goin...
Jan 19, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
LOL @ 98% David... I invite you to check out the twitters and MSDN blog comments (or even the thread I mention above) to see how divisive this issue is. Unless you mean 98% of the developers don't even engage in these things, which could also be the ...
Jan 17, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
Let's be realistic here. 98% of the developers don't care if it's json or csproj. The 2% are the early adopters. I can agree it wasn't fair to them to change back to xml files.
Jan 17, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
Yeah, this article is all sunny skies and rainbows, but doesn't really speak to the total cluster and community backlash that has occurred from having to switch between different formats and the angst with having to be stuck with a particular format ...
Jan 16, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
In a previous blog post (), the PackageReference element in the csproj file was shown to have been simplified such that Version was an XML...
Jan 13, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
Nice article. What will happen to project.json in .net core projects? It will dissapear? We have to use .csproj now?
Jan 12, 2017
Essential .NET - Essential MSBuild: A Build Engine Overview for .NET Tooling
A very good article. Is there any mention of if/when non-coreclr projects will be able to use the new format? I was hoping that VS2017 would import and upgrade my .NET projects to this format, but for now (RC1) it does not. Is an upgrade process poss...
Jan 11, 2017 wit...
Jan 1, 2017 | https://msdn.microsoft.com/en-us/magazine/mt791801 | CC-MAIN-2019-43 | refinedweb | 2,939 | 58.48 |
Yes, I did a search, and I understand time() better than before, but I would appreciate personal help.
Initially, I wanted to make a program/function that would randomly generate a number. Next, I wanted to limit it between two defined numbers. I came across rand() yesterday, and I couldn't get it to work. I realized rand() had to be seeded with the function srand(), and the most preferred source was time, following being the code
#include <time> #include <iostream> #include <cstdlib> int main() { int random; srand(time(null)); random=rand() % 51; cout<<"\nA random number not greater than 50? Well, what about "<<random<<"?"; return 0; }
My doubt is at line 9. From what I have studied in my school so far, % finds and assigns the remainder of an expression. So, if time is calculated since 1-Jan-1970, how does dividing the seconds passed by until that day by 51, give a number between 0 and 50?
Or is this a piece of code specifically for rand() function?
Edited by Smartflight: n/a | https://www.daniweb.com/programming/software-development/threads/356005/how-does-time-function-really-work | CC-MAIN-2018-43 | refinedweb | 175 | 73.07 |
First, note the exception type. It is a SqlException, so it's being generated by the SqlClient provider. In other words, this is your database talking. The SQL Server datetime datatype is capable of storing dates in the range 1753-01-01 to 9999-12-31, or Jan 1st 1753 to way longer than anyone reading this needs to worry about. The datetime2 data type was introduced in SQL Server 2008. The range of dates that it is capable of storing is 0001-01-01 to 9999-12-31, or Jan 1st 1 AD to way longer than anyone reading this.... You get the idea.
The .Net datetime is isomorphic with the SQL Server datetime2 type - the range of possible values is the same. The default value for an uninitialised datetime variable is DateTime.MinValue, or 0001-01-01. And this is usually the cause of the error message featured in the title of this post. It happens when you do not provide a value for a datetime in your C# (or VB) code which is to be stored in a non-nullable datetime field in the database. The .Net variable or property will default to 0001-01-01 which SQL Server will see as a valid value for a datetime2 field, but then tries to convert to a datetime type to store it in the appropriate field in the database table. As has already been established, 0001-01-01 is outside of the range of acceptable values for a datetime field. Hence the error message.
So what are the possible fixes? Actually, there are a few:
1. Change the storage to DateTime2 in the database.
Datetime2 is the recommended type for dates and times in SQL Server 2008 onwards. You will need to explictly map the relevant columns to datetime2 since EF will always map .Net DateTimes to the SQL Server datetime type. You can do this via the fluent API:
modelBuilder.Entity<PageContent>() .Property(f => f.DateModified) .HasColumnType("datetime2");
If you want to do this globally and you are using EF6 or later, you can use custom conventions to specify the mapping:
modelBuilder.Properties<DateTime>() .Configure(c => c.HasColumnType("datetime2"));
Or you can use attributes on your model's properties:
[Column(TypeName="datetime2")] public DateTime DateModified{ get; set; }
Note that these approaches will result in a datetime2 column with a precision of 7 digits (the default and maximum value). If you want to specify an alternative precision, you can only do this via the fluent API at the moment:
modelBuilder.Entity<PageContent>() .Property(f => f.DateModified) .HasColumnType("datetime2") .HasPrecision(0);
2. Change the property to be Nullable
You haven't provided a value for the datetime property for one of two reasons: you forgot, or it doesn't need a value. If the reason is that your datetime doesn't actually need a value, then make it nullable. You can do this on your model property by adding a question mark after the data type:
public DateTime? DateModified { get; set; }
Or by using the long hand notation:
public Nullable<DateTime> DateModified { get; set; }
When you next add a migration, it will include an amendment to the database column to allow it to accept null values.
3. Specify a default value within an acceptable range
If you just forgot to provide a value, you can specify a default value for the property to prevent it ever happening again.
public class Myobject { public Myobject() { DateCreated = DateTime.Now; } public int Id { get; set; } public DateTime DateCreated { get; set; } }
And there you have it. Incidentally, if you were wondering why the SQL Server datetime data type's minimum value is a date somewhere in 1753, the answer to this Stackoverflow question will enlighten you. | https://www.mikesdotnetting.com/article/229/conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-out-o | CC-MAIN-2021-43 | refinedweb | 622 | 62.07 |
samplenhold +
prithviraj_eg + 1 comment?
quetonix + 9 comments
#include <iostream> int main() { int x,y,z; std::cin>>x>>y>>z; std::cout<<x+y+z; return 0; }
nelsonwong632 + 0 comments
It is a status return for the operating system. 0 means the program has executed successfully. Any non-0 return value indicates an error.
nagendrasunkara1 + 0 comments
We use int main()at starting it must return the value so,in my opinion, we return the zero value.
vivinraj07 + 1 comment
why std:: comes in the above program
lan956 + 1 comment
It means the standard input (std::cin) from input and standard output (std::cout) in the program
srivastava_maya2 + 1 comment
but in program already have using name space std;
than why it is necessary to write std::
tongue_teaser82 + 0 comments
That's exactly what I was thinking. using namespace std; means you don't put std:: before cin or cout.
saharshagarwal98 + 1 comment
why does the question state that the 3 inputs should have space in between and also that each number should be between 1-1000. The solution has no checking for the given conditions of the question ?
LiventrOP + 1 comment
Because if there would be no space then it would read as 1 variable, f.e. you want to input 1 2 and 7. If you wont use space you'll get 127 as one number (int a = 127). Another solution to this problem would be seperating numbers with new line (pressing enter for each number individualy), but well, with spaces it is easier to show "starting values for tests"
Sid1112 + 13 comments
As Simple as that, they just dont know how to phrase the question.
int a,b,c,sum; cin>>a>>b>>c; sum=a+b+c; cout<<sum; return 0;
skybird1227 + 1 comment
Your code doesn't work. I tested it.
Dwivedi_vivek + 1 comment
beacuse code is wrong . they have said that we have to give single line input . your code take input in diffrent line!!!! idiot
regis148 + 1 comment
Using simple C works too: You only have to be in mind that the machine will put three aleatory numbers and the output has to be a sum...
int a,b,c; scanf("%d",&a); scanf("%d",&b); scanf("%d",&c); printf("%d",(a+b+c)); return 0;
gitipiti + 1 comment
for variable number of inputs
#include <iostream> using namespace std; int main() { int i = 0; int sum = 0; while (cin >> i) { sum += i; } cout << sum << endl; return 0; }
girlwhocode27 + 0 comments
Hey, it looks very inticing. Can you please explain, how the code accepts inputs? I tried on a complier and don't know how to end the process of feeding the input ;(
srivastava_maya2 + 0 comments
in program already have using name space std;
than why it is necessary to write std:: in front of cin and cout
dkazgar + 0 comments
An input device sends information to a computer system for processing, and an output device reproduces or displays the results of that processing. Input devices only allow for input of data to a computer and output devices only receive the output of data from another device. Epson tech support
Sort 210 Discussions, By:
Please Login in order to post a comment | https://www.hackerrank.com/challenges/cpp-input-and-output/forum | CC-MAIN-2018-51 | refinedweb | 538 | 59.03 |
Subject: Re: [OMPI users] Did you break MPI_Abort recently?
From: Ralph Castain (rhc_at_[hidden])
Date: 2009-06-27 22:05:33
For anyone else on the list who is interested:
There definitely was a bug in the system that was causing Open MPI to
not forcibly terminate all processes when one called abort. However,
we also have a backup mechanism that should catch things even if our
primary method fails.
MPI processes in Open MPI will automatically terminate whenever their
local daemon dies unexpectedly. However, the processes have to call
into the MPI library before this can happen.
This particular example has all the processes immediately enter an
infinite loop once a process aborts. Thus, they never called into the
MPI library, and hence never aborted.
I have fixed the bug that caused the primary method to fail. Just
wanted to explain why the backup method also failed - the fact that
OMPI cannot locally respond to failures until/unless the app enters
the MPI library is an important point to remember.
Ralph
On Jun 27, 2009, at 7:37 PM, Mostyn Lewis wrote:
> Thank you.
>
> DM
>
> On Fri, 26 Jun 2009, Ralph Castain wrote:
>
>> Man, was this a PITA to chase down. Finally found it, though. Fixed
>> on trunk as of r21549
>>
>> Thanks!
>> Ralph
>>
>>
>> So something else is wrong.
>> On Jun 25, 2009, at 3:19 PM, Mostyn Lewis wrote:
>>
>>> Just local machine - direct from the command line wth a script like
>>> the one below. So, no launch mechanism.
>>> Fails on SUSE Linux Enterprise Server 10 (x86_64) - SP2 and
>>> Fedora release 10 (Cambridge), for example.
>>> DM
>>> On Thu, 25 Jun 2009, Ralph Castain wrote:
>>>> Sorry - should have been more clear. Are you using rsh, qrsh
>>>> (i.e., SGE), SLURM, Torque, ....?
>>>> On Jun 25, 2009, at 2:54 PM, Mostyn Lewis wrote:
>>>>> Something like:
>>>>> #!/bin/ksh
>>>>> set -x
>>>>> PREFIX=$OPENMPI_GCC_SVN
>>>>> export PATH=$OPENMPI_GCC_SVN/bin:$PATH
>>>>>>>>> mpicc -g -O6 mpiabort.c
>>>>> NPROCS=4
>>>>> mpirun --prefix $PREFIX -x LD_LIBRARY_PATH $MCA -np $NPROCS -
>>>>> machinefile fred ./a.out
>>>>> DM
>>>>> On Thu, 25 Jun 2009, Ralph Castain wrote:
>>>>>> Using what launch environment?
>>>>>> On Jun 25, 2009, at 2:29 PM, Mostyn Lewis wrote:
>>>>>>> While using the BLACS test programs, I've seen that with
>>>>>>> recent SVN checkouts
>>>>>>> (including todays) the MPI_Abort test left procs running. The
>>>>>>> last SVN I
>>>>>>> have where it worked was 1.4a1r20936. By 1.4a1r21246 it fails.
>>>>>>> Works O.K. in the standard 1.3.2 release.
>>>>>>> A test program is below. GCC was used.
>>>>>>> DM
>>>>>>> #include <stdio.h>
>>>>>>> #include <sys/types.h>
>>>>>>> #include <unistd.h>
>>>>>>> #include <math.h>
>>>>>>> #include <mpi.h>
>>>>>>> #define NUM_ITERS 100000
>>>>>>> /* Prototype the function that we'll use below. */
>>>>>>> static double f(double);
>>>>>>> int
>>>>>>> main(int argc, char *argv[])
>>>>>>> {
>>>>>>> int iter, rank, size, i;
>>>>>>> int foo;
>>>>>>> double PI25DT = 3.141592653589793238462643;
>>>>>>> double mypi, pi, h, sum, x;
>>>>>>> double startwtime = 0.0, endwtime;
>>>>>>> int namelen;
>>>>>>> char processor_name[MPI_MAX_PROCESSOR_NAME];
>>>>>>> /* Normal MPI startup */
>>>>>>> MPI_Init(&argc, &argv);
>>>>>>> MPI_Comm_size(MPI_COMM_WORLD, &size);
>>>>>>> MPI_Comm_rank(MPI_COMM_WORLD, &rank);
>>>>>>> MPI_Get_processor_name(processor_name, &namelen);
>>>>>>> printf("Process %d of %d on %s\n", rank, size, processor_name);
>>>>>>> /* Do approximations for 1 to 100 points */
>>>>>>> /* sleep(5); */
>>>>>>> for (iter = 2; iter < NUM_ITERS; ++iter) {
>>>>>>> h = 1.0 / (double) iter;
>>>>>>> sum = 0.0;
>>>>>>> /* A slightly better approach starts from large i and works
>>>>>>> back */
>>>>>>> if (rank == 0)
>>>>>>> startwtime = MPI_Wtime();
>>>>>>> for (i = rank + 1; i <= iter; i += size) {
>>>>>>> x = h * ((double) i - 0.5);
>>>>>>> sum += f(x);
>>>>>>> }
>>>>>>> mypi = h * sum;
>>>>>>> if(iter == (NUM_ITERS - 1000)){
>>>>>>> MPI_Barrier(MPI_COMM_WORLD);
>>>>>>> if(rank == 2){
>>>>>>> MPI_Abort(MPI_COMM_WORLD, -1);
>>>>>>> } else {
>>>>>>> /* Just loop */
>>>>>>> foo = 1;
>>>>>>> while(foo == 1){
>>>>>>> foo = foo + 3;
>>>>>>> foo = foo - 2;
>>>>>>> foo = foo - 1;
>>>>>>> }
>>>>>>> }
>>>>>>> }
>>>>>>> MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0,
>>>>>>> MPI_COMM_WORLD);
>>>>>>> }
>>>>>>> /* All done */
>>>>>>> if (rank == 0) {
>>>>>>> printf("%d points: pi is approximately %.16f, error = %.16f\n",
>>>>>>> iter, pi, fabs(pi - PI25DT));
>>>>>>> endwtime = MPI_Wtime();
>>>>>>> printf("wall clock time = %f\n", endwtime - startwtime);
>>>>>>> fflush(stdout);
>>>>>>> }
>>>>>>> MPI_Finalize();
>>>>>>> return 0;
>>>>>>> }
>>>>>>> static double
>>>>>>> f(double a)
>>>>>>> {
>>>>>>> return (4.0 / (1.0 + a * a));
>>>>>>> }
>>>>>>> _______________________________________________
>>>>>>> users mailing list
>>>>>>> users_at_[hidden]
>>>>>>>
>>>>>> _______________________________________________
>>>>>> users mailing list
>>>>>> users_at_[hidden]
>>>>>>
>>>>> _______________________________________________
>>>>> users mailing list
>>>>> users_at_[hidden]
>>>>>
>>>> _______________________________________________
>>>> users mailing list
>>>> users_at_[hidden]
>>>>
>>> _______________________________________________
>>> users mailing list
>>> users_at_[hidden]
>>>
>>
>> _______________________________________________
>> users mailing list
>> users_at_[hidden]
>>
> _______________________________________________
> users mailing list
> users_at_[hidden]
> | http://www.open-mpi.org/community/lists/users/2009/06/9744.php | CC-MAIN-2014-35 | refinedweb | 689 | 74.08 |
, singular.ok = TRUE, contrasts = NULL, …)
glm.fit(x, y, weights = rep(1, nobs), start = NULL, etastart = NULL, mustart = NULL, offset = rep(0, nobs), family = gaussian(), control = list(), intercept = TRUE, singular.ok = TRUE)
# S3 method for glm weights(object, type = c("prior", "working"), …)
a description of the error distribution and link
function to be used in the model. For
glm this can be a
character string naming a family function, a family function or the
result of a call to a family function. For
glm.fit only the
third option is supported. (See
family for details of
family functions.)
an optional data frame, list or environment (or object
coercible by
as.data.frame to a data frame) containing
the variables in the model. If not found in
data, the
variables are taken from
environment(formula),
typically the environment from which
glm is called.
an optional vector of ‘prior weights’ to be used
in the fitting process. Should be
NULL or a numeric vector.
an optional vector specifying a subset of observations to be used in the fitting process.
a function which indicates what should happen
when the data contain
NAs. The default is set by
the
na.action setting of
options, and is
na.fail if that is unset. The ‘factory-fresh’
default is
na.omit. Another possible value is
NULL, no action. Value
na.exclude can be useful.
starting values for the parameters in the linear predictor.
starting values for the linear predictor.
starting values for the vector of means. is
specified their sum is used. See
model.offset.
a list of parameters for controlling the fitting
process. For
glm.fit this is passed to
glm.control.
a logical value indicating whether model frame should be included as a component of the returned value.
the method to be used in fitting the model. The default
method
"glm.fit" uses iteratively reweighted least squares
(IWLS): the alternative
"model.frame" returns the model frame
and does no fitting.
User-supplied fitting functions can be supplied either as a function
or a character string naming a function, with a function which takes
the same arguments as
glm.fit. If specified as a character
string it is looked up from within the stats namespace.
For
glm:
logical values indicating whether the response vector and model
matrix used in the fitting process should be returned as components
of the returned value.
For
glm.fit:
x is a design matrix of dimension
n * p, and
y is a vector of observations of length
n.
logical; if
FALSE a singular fit is an
error.
an optional list. See the
contrasts.arg
of
model.matrix.default.
logical. Should an intercept be included in the null model?
an object inheriting from class
"glm".
character, partial matching allowed. Type of weights to extract from the fitted model object. Can be abbreviated.
For
glm: arguments to be used to form the default
control argument if it is not supplied directly.
For
weights: further arguments passed to or from other methods.:
a named vector of coefficients
the working residuals, that is the residuals
in the final iteration of the IWLS fit. Since cases with zero
weights are omitted, their working residuals are
NA.
the fitted mean values, obtained by transforming the linear predictors by the inverse of the link function.
the numeric rank of the fitted linear model.
the linear fit on link scale.
up to a constant, minus twice the maximized log-likelihood. Where sensible, the constant is chosen so that a saturated model has deviance zero.
A version of Akaike's An Information Criterion,
minus twice the maximized log-likelihood plus twice the number of
parameters, computed via the
aic component of the family.
For binomial and Poison families the dispersion is
fixed at one and the number of parameters is the number of
coefficients. For gaussian, Gamma and inverse gaussian families the
dispersion is estimated from the residual deviance, and the number
of parameters is the number of coefficients plus one. For a
gaussian family the MLE of the dispersion is used so this is a valid
value of AIC, but for Gamma and inverse gaussian families it is not.
For families fitted by quasi-likelihood the value is
NA.
The deviance for the null model, comparable with
deviance. The null model will include the offset, and an
intercept if there is one in the model. Note that this will be
incorrect if the link function depends on the data other than
through the fitted mean: specify a zero offset to force a correct
calculation.
the number of iterations of IWLS used.
the working weights, that is the weights in the final iteration of the IWLS fit.
the weights initially supplied, a vector of
1s if none were.
the residual degrees of freedom.
the residual degrees of freedom for the null model.
if requested (the default) the
y vector
used. (It is a vector even for a binomial model.)
if requested, the model matrix.
if requested (the default), the model frame.
logical. Was the IWLS algorithm judged to have converged?
logical. Is the fitted value on the boundary of the attainable values?
the matched call.
the formula supplied.
the
data argument.
the offset vector used.
the value of the
control argument used.
the name of the fitter function used (when provided as a
character string to
glm()) or the fitter
function (when provided as that).
(where relevant) the contrasts used.
(where relevant) a record of the levels of the factors used in fitting.
(where relevant) information returned by
model.frame on the special handling of
NAs..
# NOT RUN { ##) # } # NOT RUN { summary(glm.D93) # } # NOT RUN { ##) }) # } # NOT RUN { ## an example with offsets from Venables & Ripley (2002, p.189) utils::data(anorexia, package = "MASS") anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt), family = gaussian, data = anorexia) summary(anorex.1) # } # NOT RUN { #)) ##) # }
Run the code above in your browser using DataCamp Workspace | https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/glm | CC-MAIN-2022-21 | refinedweb | 980 | 60.41 |
The following code does not compile although I expect it to:
/// BEGIN CODE ///
#include <utility>
struct S {};
struct C {
S & mc2;
S && mc3;
C( S& b, S && c ) : mc2{b}, mc3{std::move(c)} {}
};
int main() { return 0; }
/// END CODE ///
I compile it with command:
g++ test.cpp -std=c++0x -o test.exe
The output is:
test.cpp: In constructor ‘C::C(S&, S&&)’:
test.cpp:9:48: error: invalid initialization of non-const reference of type ‘S&’ from an rvalue of type ‘<brace-enclosed initializer list>’
test.cpp:9:48: error: invalid initialization of reference of type ‘S&&’ from expression of type ‘<brace-enclosed initializer list>’
Compiler version (g++ -v):
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/i686-redhat-linux/4.6.0.6.0 20110428 (Red Hat 4.6.0-6) (GCC)
G++ is actually correct according to wording in the C++11 FDIS (see 8.5.4 paragraphs 5 and 6), but we've reported it as an issue that needs to be fixed.
It's not just class members, it applies to list-initialization of any reference type:
int i;
int& ir{ i };
The FDIS requires a temporary to be created, and a non-const reference cannot bind to a temporary.
(In reply to comment #1)
> G++ is actually correct according to wording in the C++11 FDIS (see 8.5.4
> paragraphs 5 and 6), but we've reported it as an issue that needs to be fixed.
Are you sure about the paragraphs 5 and 6? (5 starts with "An object of type", 6 starts with "The lifetime of the array"?) They only say how std::initializer_list is created and how it behaves, but the 6th bullet of paragraph 3 (the one starting with "Otherwise, if the initializer list has a single element") does not require that std::initializer_list is created or used. It simply says that in code like:
int i = 0;
int & ri{i};
"ri" is initialized with "i". (And BTW, this example works on the same compiler.)
sorry, I meant bullets 5 and 6 in paragraph 3
the 5th bullet applies before the 6th one, and that says for a reference type a temporary is created. The 6th bullet is never reached for references.
Your example with int& works because GCC doesn't implement the FDIS wording yet, according to the FDIS it should be rejected too, see
this is a wording problem in the FDIS and will be core issue 1288 in the next issues list
Does anybody know the DR #? We could add it to the description and suspend.
The corresponding CWG issue is
Link changed now that it has been voted into the working paper:
should it be un-suspended?
Yep, thanks, Marc.*’
Comment on attachment 28188 [details]
Testcase for Bug "error: invalid initialization of non-const reference of type ‘std::istream&"
(In reply to comment #9)
>*’
That's not mysterious, and is not related to this bug report.
Your code can be reduced to:
struct Base {
operator void*() { return 0; }
};
struct Derived1 : Base { };
struct Derived2 : Base { };
Derived1 d1;
Derived2 d2;
Base& b = true ? d1 : d2;
The conditional expression cannot implicitly convert two objects of different types to a common base class, so instead the conversion operator is used to convert both types to void*
To force the behaviour you expect use an explicit cast on one operand:
istream& si = sfile.is_open() ? (std::istream&)sfile : sbuf;
*** Bug 56032 has been marked as a duplicate of this bug. ***
Jason, I'd like to try and fix this, but need some clues.
A minimal example that fails to compile is:
struct S { } s;
S& r{s};
I find that in call.c:reference_binding we get compatible_p = false, which seems to be wrong. Even if compatible_p is true we don't take the branch that looks like it should be used:
/* Directly bind reference when target expression's type is compatible with
the reference and expression is an lvalue. In DR391, the wording in
[8.5.3/5 dcl.init.ref] is changed to also require direct bindings for
const and rvalue references to rvalues of compatible class type.
We should also do direct bindings for non-class xvalues. */
if (compatible_p
&& (is_lvalue
|| (((CP_TYPE_CONST_NON_VOLATILE_P (to)
&& !(flags & LOOKUP_NO_RVAL_BIND))
|| TYPE_REF_IS_RVALUE (rto))
&& (gl_kind
|| (!(flags & LOOKUP_NO_TEMP_BIND)
&& (CLASS_TYPE_P (from)
|| TREE_CODE (from) == ARRAY_TYPE))))))
Naively I would expect compatible_p and is_lvalue to be true for the case above. Does the code earlier in the function need to be adjusted for the case where a braced-init-list has a single element of reference-compatible lvalue type?
*** Bug 58977 has been marked as a duplicate of this bug. ***
This bug seems to be fixed with the current trunk. Both the example
in the original report and similar examples compile correctly, like
std::string& f() {static std::string s; return s;}
int main()
{
std::string& ri{f()};
}
and
int& f() {static int i = 42; return i;}
int main()
{
int& ri{f()};
}
Please close as resolved.
I agree. My examples are working.
Unfortunately, my account seems to not have the permissions to close a bug. I am a maintainer.
Any ideas how I can get such permissions set?
Now if only I can remember what libstdc++ ctor I had to have one paren init amongst all the other brace inits that annoyed me enough to post this error! ;-)
Sorry for the noise. I reported a dupe not this bug.
My question on permissions still stands though.
(In reply to Ed Smith-Rowland from comment #15)
> Unfortunately, my account seems to not have the permissions to close a bug.
> I am a maintainer.
>
> Any ideas how I can get such permissions set?
You need to log in with an @gcc.gnu.org email address.
Created attachment 32240 [details]
This is a test case for c++/50025.
This just has simple classes with various reference member and verifies that using brace-initialization is accepted. I put it under g++.dg/cpp0x.
Would anyone like more test cases?
If this passes on x86_64-linux I think I'll close this with the test case patch.
OK?
Sounds good.
Author: emsr
Date: Sat Mar 1 22:51:25 2014
New Revision: 208251
URL:
Log:
2014-03-01 Edward Smith-Rowland <3dw4rd@verizon.net>
PR c++/50025
* g++.dg/cpp0x/pr50025.C: New.
Added:
trunk/gcc/testsuite/g++.dg/cpp0x/pr50025.C
Modified:
trunk/gcc/testsuite/ChangeLog
Fixed.
For the record, I think r207164 fixed this
Is it related bug?
struct C
{
const std::string &st_ref;
explicit C(const std::string &st) : st_ref{st}
{
std::cout << &st << ' ' << &st_ref << std::endl;
assert(&st == &st_ref);
}
};
assert() fires! gcc 4.8.2
If we replace st_ref{st} with st_ref(st), assert() doesn't fire.
(In reply to __vic from comment #23)
> Is it related bug?
Yes, the original C++11 rules required a temporary to be created there and the reference member binds to that temporary (which then goes out of scope).
Your code works correctly with GCC 4.9
*** Bug 60583 has been marked as a duplicate of this bug. *** | https://gcc.gnu.org/bugzilla/show_bug.cgi?id=50025 | CC-MAIN-2018-05 | refinedweb | 1,175 | 64.51 |
Gosling Claims Huge Security Hole in .NET 687
Posted by CowboyNeal
from the throwing-stones dept.
from the throwing-stones dept.
renai42 writes "Java creator James Gosling this week called Microsoft's decision to support C and C++ in the common language runtime in .NET one of the 'biggest and most offensive mistakes that they could have made.' Gosling further commented that by including the two languages into Microsoft's software development platform, the company 'has left open a security hole large enough to drive many, many large trucks through.'" Note that this isn't a particular vulnerability, just a system of typing that makes it easy to introduce vulnerabilities, which last time I checked, all C programmers deal with.
Phew! (Score:5, Funny)
Oh. Never mind!
Re:Phew! (Score:2)
Re:Phew! (Score:3, Insightful)
Re:Phew! (Score:4, Informative)
Re:Phew! (Score:3, Insightful)
Fair enough, but at least 90% of the stuff written in C and C++ doesn't need to be.
Re:Phew! (Score:5, Insightful)
I mean seriously, this is like claiming ASSEMBLY is a worthless insecure language because you can hang the system while in supervisor mode, due to ineptness? Sheesh.
Re:Phew! (Score:5, Interesting)
Re:Phew! (Score:3, Informative)
I'd like to point out that in this day and age most C programmers have heard about the problems and make some effort to prevent them. While programmers in "safe" languages (VB) generally have not heard of these problems, so while they are harder to create, those programmers are also less likely to recognize them. In fact problems in C are generally minor mistakes that are easy (though tedious) to fix, while in the other languages the same problem tends to be major design level issues that are hard to co
Re:Phew! (Score:3, Funny)
Just imagine how secure the world would be if we wrote everything in PHP!
:)
Re:Phew! (Score:3, Insightful)
Re:Phew! (Score:5, Insightful)
For most applications assembly is a worthless insecure language, and you should stick to a higher level language if you don't want to introduce problems (for anything larger, but probably including "hello world").
Re:Phew! (Score:4, Insightful)
Are they really that high grade then?
Re:Phew! (Score:5, Insightful)
Re:Phew! (Score:3, Funny)
Give a man a gun, and he can kill many people with it.
Give that same man a pencil and... eh, not so much.
Re:Phew! (Score:5, Insightful)
That's just restating the question.
If managed languages make a certain class of exploits impossible or very unlikely while C doesn't, then C is insecure relative to those languages.
A good C programmer might be able to cut the exploit rate down to some very small value, but they're going to work pretty hard to get to that point while people in managed languages get it for free. And good C programmers still fuck up sometimes.
Of course, there's other ways to screw up. No language is immune from security problems. Using a "managed" language is nothing more than risk management, but it's pretty effective.
Re:Phew! (Score:5, Insightful)
Re:Phew! (Score:3, Insightful)
It all comes down to bad OS design in general. Take the IE exploits for example. Why the heck can you get so much system access through an exploit in a web browser?!? Lets be honest here, the security model employed in most of today's OS's is mind boggling in it's ineptness.
Linux is not immune e
Re:Phew! (Score:3, Interesting)
Anecdote time. After five years of working on a million+ line C/C++ codebase, I ran across my first buffer overflow last monday. I've seen many potential buffer overflows (and fixed them when I found them), but this was the first I've seen actually get thrown over the wall to QA.
If buffer over
Different != Better (Score:4, Insightful)
- segfault in C
- throw an unhandled exception in python
- churn up 2GB swap in java (or something similar)
In any case, think DoS. The solution is to program competently, regardless of language.
Re:Phew! (Score:3, Insightful)
buffer overflows are not the only kind of bug that plagues development. quite a few "plain old logic errors" or "insecure designs" are source of problems.
I mean I just reinstalled pam last night [for the second day in a row... diff versions] with maybe 20 patches applied to it. I doubt all 20 [or any at all] were due to buffer overflows.
A proper programmer would do proper bounds checking on their own [e.g. I need to store N bytes, do I have N bytes available]. People w
Re:Phew! (Score:3, Insightful)
It would help if C automatically initialized ram (and I've known at least one C that did, but it isn't a part of the language specs), just like it helps not to be able to use 0 as a pointer address. But the only thing that would make C safe would be to put it in a box, and not let it look outside. Even then you'd get buffer overflows within the code, but if
Re:Phew! (Score:5, Insightful)
These languages are inherently insecure because they allow for mistakes that other languages do not allow for. Combine this with the fact that it doesn't take a fool to make mistakes and you have the perfect proof that C is inherently insecure. Refute either of those arguments and you might have a point.
The problem with C is that it takes the inhuman capability to not make mistakes to end up with secure software. That's why all of the long lived C software projects have to be constantly patched to correct mistakes. Buffer overflows are no accidents, they are the predictable result of using C. Use C -> expect to deal with buffer overflows, memory leaks, etc. Every good C programmer knows this.
The difference between good C software and bad C software is that in the latter case the programmers are surprised whereas in the first case the programmers actually do some testing and prevention (because they expect things to go wrong). Mozilla Firefox comes with a talkback component because the developers know that the software will crash sometimes and want to be able to do a post mortem. The software crashes because the implementation language of some components is C. IMHO mozilla firefox is good software because it crashes less than internet explorer and offers nice features.
Of course we have learned to work around C's limitations. Using custom memory allocation routines, code verifiers and checkers, extensive code reviews we can actually build pretty stable C software. The only problem is that C programmers are extremely reluctant to let go of their bad habits. Some actually think they are gods when they sit down behind their editors and do such stupid things as using string manipulation functions everyone recommends to avoid like the plague, trying to outsmart garbage collecting memory allocaters by not using them, etc. If you'd build in a switch in the compiler which enforces the use of the improvements listed above, most of the popular C software simply wouldn't compile. But then it wouldn't be C anymore because the whole point of C is to allow the programmer to do all the bad things listed above, even accidentally.
IMHO programmer reeducation is an inherently bad solution to inherent security problems of the C language. You can't teach people not to make mistakes. You need to actively prevent them from making mistakes. You can make mistakes in other languages but they are a subset of the mistakes you can make in C. Therefore you should use those languages rather than C unless you have a good reason not to. Any other reason than performance is not good enough.
Rule for selecting programming language: (Score:3, Insightful)
Rule:
If you don't need to spend 5-10% of your development time to speed/size optimizing your program to make it useable, you are not using language/abstractions that is high level enough to your task.
Explanation:
If I use high level languge (say Haskell/OCaml/Clean/Common Lisp) and use all it's abstarction powers, program code will usually be 10-50% of the size compared to
Re:Phew! (Score:3, Insightful)
Re:Phew! (Score:3, Funny)
What Visual Studio
LK
Re:Phew! (Score:4, Insightful)
I feel confident in predicting that most of userland will eventually run in the context of some virtual machine or other. Of course, that doesn't exactly make me a prophet, since that's the plan for Longhorn, but I think it will become the norm on other platforms as well.
It would be nice if, in the long run, operating systems became irrelevant when it comes to choosing applications. You go with whatever has the best track record for speed, security, or whatever, and then just choose whatever applications you like. Since the virtual machine runs everywhere, so will your software.
Re:Phew! (Score:3, Insightful)
Advertisement? (Score:5, Insightful)
To me, it sounded like a big advertisement for Java.
It's the developers decision to use unsafe code in the
A hunting rifle can be used to kill people. Does that mean the trigger should only work after inserting a valid and current hunting license?
Re:Advertisement? (Score:2, Insightful)
Re:Advertisement? (Score:5, Insightful)
C and C++ allow for buffer overflows. They allow for improper or intentional coding to cause software to try to violate memory space of other functions or programs. They allow for memory allocation without necessarily providing any cleanup later. In the hands of bad, sloppy, lazy, or malicious programmers these traits have always proven to be a problem time and again on many different platforms. This doesn't mean that these languages are the wrong tool; I'd argue that part of Linux's success is because the kernel and most of the GNU-implemented services are written in these languages, which are flexible. Too much flexibility for the wrong purpose leads to problems though, just as too much rigidity leads to problems when things need to be flexible.
Re:Advertisement? (Score:5, Insightful)
Re:Advertisement? (Score:3, Interesting)
Note that the Java VM of Microsoft was not that safe. I am very curious if
Re:Advertisement? (Score:3, Informative)
Re:Advertisement? (Score:4, Informative)
Unless you're talking about anonymous inner classes (a different animal, typically with a different purpose altogether when it comes to design motivation).
This seems to have been a matter of designer taste on the part of Hejlsberg. 2.0 should bring anonymous methods, which aims to solve the same type of problems anonymous classes did, in a neater way.
Re:Advertisement? (Score:3, Insightful)
"Nested type" and "inner class" are, as far as I know, equivalent terms and the latter has been a common term used in both languages. However, this is the first time I know of someone who differentiates the two terms in practical use.
What makes the implicit "this.Outer" the essential feature of an "inner class" in your terminology? I'm also curious as to why you consider it such an important feature.
Once more this seems to be a matt
Re:Advertisement? (Score:5, Interesting)
In my current job, which involves quite a bit of C#, I had the opportunity to port large chunks of our legacy application from C++ to Managed C++. We didn't gain security benefits, nor did we gain speed; we didn't loose any either. However we gained a lot of maintainability since we now have a single stack-trace to deal with that bridges all of the languages that we have (now reduced to C# and C++ -- down significantly from when we relied heavily on COM)
The fact that MS gave us that choice is wonderful. If we wanted to be using JNI (which I had the unlucky opportunity to use), we'd not have made much progress at all.
Re:Advertisement? (Score:3, Informative)
Re:Advertisement? (Score:5, Insightful)
Nobody is going to use C or C++ to write a completely new program under
.NET. There are occasions where I might use C for something I wanted to make cross platform but no way would I ever go near C++.
Most people who are going to use the new
.NET support are people who have legacy C programs and want to gradually transition them to the .NET base in stages. The makes a good deal of sense.
The other constituency is folk who are writing stuff that is almost but not quite at driver level.
Re:Advertisement? (Score:3, Informative)
Not saying this can't be defeated but there are tools in the languages to protect yourself.
Re:Advertisement? (Score:3, Informative)
Re:Advertisement? (Score:3, Informative)
Sigh. There are plenty of garbage collectors and boundscheckers for C/C++. Heck, there are several bounds checker extensions/patches for GCC that introduce bounds checking to both stack and heap. Boehm is a fine garbage collector if you like that sort of thing. They go back at least 10 years.
Combined with a non-executable stack and heap, randomized address space layout and signed return addresses (StackGuard XORs with a random value and verifies before return
Re:Advertisement? (Score:3, Interesting)
It's irrelevant, actually. A bug is a bug. You can make them in any language. The consequences of the potential bugs are what matters. But only the implementation defines what a "buffer overflow" will actually do. Granted you can try and write past some allocated buffer in C (and C++). That doesn't mean the write should actually occur. That's the responsibility of the implementation, and mostly of the underlying operating system. I already said that earlier: the major
Re:Advertisement? (Score:3, Interesting)
Pascal isn't safe either (Score:4, Interesting)
"Object-oriented programming" is ill-defined. It encompasses a lot of languages that go about it in entirely different ways. To me, the most it can mean is "calling functions with an assumed this pointer." What does OO mean to you? Virtuals? What makes it "real"?
There are benefits to C beyond speed and direct access to memory, hardware, etc. People seem to forget that for us to make software "work together", calling conventions across libraries need to be compatible. Which is why we picked C calling conventions. It's not necessarily the most expressive if you're into fancy things, but it is flexible enough for most everything. My main problem with Java isn't the language -- it's the libraries. Lots of them, packaged in their own special way, not really designed for use by any language.
Languages, most of the time, aren't the issue. We haven't gained all that many 'new' features with new languages, at least not anything we can't easily live without. Access to symbols is an issue, however, and a really important one from the point of view of integration, code re-use, and even making sure you're using trusted/proven code.
Regardless of buffer overflows, you can still write infinite loops, incorrect logic, etc. in just about any language. These language wars are about markets -- they're about money.
Re:Advertisement? (Score:2, Insightful)
DISCLAIMER: COMPLETELY OFF-TOPIC
I don't know what the law is, but if a hunting rifle can only be legally used for hunting, this actually a pretty good idea. The card mechanism could also be used to enforce hunting seasons.
I realize this offends some people's sense of rights, but I'm not particularly inclined to defend somebody's "right" to use a firearm outside its
Re:Advertisement? (Score:3, Insightful)
Obviously.
but if a hunting rifle can only be legally used for hunting
A hunting license licenses the owner to take a certain type of game (deer season, etc) on certain land (assigned state land, private land, etc) during certain times (hunting seasons, obviously) with certain tools (shotgun only, bow, etc). It only grants this, in the case of firearms, to people who already legally own them. A "hunting rifle" is simply a subset of rifle suitable for a certain task (which var
Re:Advertisement? (Score:5, Insightful)
The article is heavy on sensationalism and short on content so it is difficult to tell what is actually being debated here, but I think that Gosling is claiming that support of C type handling in itself creates a chink in the armor of the CLR, regardless of any particular project's use of that feature.
Re:Advertisement? (Score:5, Insightful)
All use of unsafe features in
As far as I know, there is no example of unmanaged code that can violate the managed code type system, and
Also, this ignores that C/C++ support is much more complicated in
Frankly, this seems like a bit of sour grapes to me.
Re:Advertisement? (Score:3, Funny)
Me: "Oh, that would be, umm, James Gosling."
He: "No, that's not the name. It was a lady. Let me check
Me "Who?"
A web search revealed that Ms. Centoni's position was "Director of Java Marketing." Out of the mouths of babes come all wise sayings.
Re:Advertisement? (Score:3, Insightful)
A hunting rifle is fine for some purposes, but decorating your house with them is unwise. Java, effectively, has support for making
Re:Advertisement? (Score:3, Informative)
If that is the point, he's dead wrong.
Just like you can run Java code in or out of the sandbox, you can run
Re:Advertisement? (Score:3, Informative)
The developer can choose to do whatever he/she wants. The nice thing about
Woah (Score:5, Funny)
So you mean to tell me (Score:5, Insightful)
C'mon now. There is no vulnerability. Don't post this sort of crap. Its strictly knee-jerk material meant to bend a few people out of shape and start flames.
J2EE is great (for its target area)
Both are secure, stable and reasonably fast if you are a GOOD programmer. ANYONE who does ANY C or C++ code that will be used in industry needs to ENSURE that they just take a few extra precautions and are aware of secure coding techniques in both languages. Its rather quite simple.
To sum it up: nothing to see here folks.
Re:So you mean to tell me (Score:3, Interesting)
The fact that the editors actually chose to point out the flaw in the argument (in MS' favor!!!), rather than adding to the sensationalism is a welcome and refreshing change.
Don't disagree with Microsoft... (Score:5, Insightful)
What a surprise! (Score:5, Insightful)
In Java, everything is an object! Oh...except for the basic types, you need to use object wrappers for those.
Re:What's the flaw again? (Score:3, Informative)
It speaks to the purity of the language. Being able to deal with *everything* as an object is a distinct advantage since it allows you to, potentially, extend basic types into more complex ones and it also prevents you from having to "box" primitives in objects and "unbox" them on the way out.
BTW, JDK1.5 (aka Java 5) has a new feature called "autoboxing" which does the above boxing for you. This doesn't really count as those types being objects, it's more of a kl
Re:What's the flaw again? (Score:3, Interesting)
These are quite distinct from their corresponding boxed types in the System namespace,
The "box" and "unbox" CLI instructions allow for the translation between the two sets above. There is nothing automatic about this at the CLI level.
The reason you've probabl
Re:What's the flaw again? (Score:3, Informative)
It's ugly and non-orthoganal. Look at the Arrays [sun.com] class for example; there are dozens of duplicated methods that are identical except that they take bytes, chars, shorts, ints, etc. as arguments. I'd much rather have everything be a true object; any performance issues can be handled by the compiler, runtime, or Moore's law. Autoboxing helps, but better to fix it for real than with syntactic sugar.
JNI (Score:3, Informative)
Re:JNI (Score:5, Informative)
It is completely fair to point out that
Pat Niemeyer
Author of Learning Java, O'Reilly & Associates
Re:JNI (Score:3, Insightful)
Java lets you write to the user's filesystem. Does that make it insecure? You could run a program to wipe out your hard drive!
But Java allows for a "sandbox". So does
A truck, eh? (Score:5, Funny)
Like, say, a truck about the size of Sun's Java runtime environment.
Java is a type-safe language at the VM level... (Score:5, Insightful)
To support C/C++ semantics (ad-hoc pointers) you'd have to throw all that out the window and I assume that's what he's talking about.
Pat Niemeyer,
Author of Learning Java, O'Reilly & Associates and the BeanShell Java Scripting language.
Re:Java is a type-safe language at the VM level... (Score:2)
The Microsoft CLR is also type-safe at the VM level. If you choose to use pointers in Managed C++, though, you lose any ability to assert heap access safety, and therefore must mark your code as unsafe, because you can perform pointer arithmetic.
you got it backwards (Score:4, Insightful)
You arae kidding, right? Do you seriously believe Java is the first or only language to guarantee runtime safety? Safe languages are the rule, not the exception.
To support C/C++ semantics (ad-hoc pointers) you'd have to throw all that out the window and I assume that's what he's talking about.
C# distinguishes safe and unsafe code. C#'s safe code is as safe as "pure" Java code. You can think of C#'s unsafe code (or its equivalent in C/C++) as code linked in through the JNI interface, except that C#'s unsafe code has far better error checking and integration with the C# language than anything invoked through JNI.
Altogether, C#'s "unsafe" construct results in safer and more portable code than the Java equivalent, native code linked in through JNI.
Pat Niemeyer, Author of Learning Java, O'Reilly & Associates and the BeanShell Java Scripting language.
Well, then I suggest you learn some languages other than Java before making such ridiculous statements.
Re:Java is a type-safe language at the VM level... (Score:2)
Re:Java is a type-safe language at the VM level... (Score:4, Interesting)
You imply that compiled C code is faster than compiled C++ code, which IME is rarely the case these days. In particular, optimisations performed by C++ compilers have almost caught up with their C brethren. With almost perfect zero-overhead implementations of all the major C++-only language features now in common use and the added performance boost from things like inlined code in templates, the balance often tips significantly in C++'s favour now.
Can you give some examples of high quality numerical libraries written in pure Java (i.e., without JNI)?
Disclaimer: I'm a professional C++ developer, and I write high performance maths libraries for a living.
Re:Java is a type-safe language at the VM level... (Score:3, Interesting)
Re:Java numeric libraries (Score:3, Interesting)
Of the two "numeric" libraries mentioned on the website only one handles complex numbers and the implementation in java leaves much to be desired (relative to assembly or C). To my knowledge, the Lau Numerical libraries based on algol routines ar
Java has many potential drawbacks for numerics (Score:3, Interesting)
Java has several pretty fundamental disadvantages when it comes to serious numerical work, compared to a language like C or C++.
The most obvious is the "everything is an object" principle. If you can't create value types for things like vectors or complex numbers, you're imposing performance overheads for dereferencing before you even start doing any maths.
Moreover, serious maths work often involves large data sets. We work with graphs with many thousands of nodes pretty routinely, which can make fine c
Re:Java is a type-safe language at the VM level... (Score:5, Informative)
Garbage collection in Java has been faster than free/malloc in C for years. This is in large part due to the fact that the runtime can recognize very short lived objects and put them on a special part of the heap.
It's not necessary to use unsafe languages to get performance any more.
Pat Niemeyer
Re:Java is a type-safe language at the VM level... (Score:5, Informative)
You're quite right that Java's speed is excellent these days (for non-GUI code, at least). I've spent a lot of time recently working with a large system that was first implemented in Java (by highly skilled developers) and then ported to C++ (by greenhorns). The C++ port is only 50-100% faster, which isn't worth the price in developer time that's been wasted on memory leaks and other forms of memory corruption that were never a factor in Java. Besides that, supporting multiple platforms with the C++ version is the #definition of pain.
However, the C++ version uses only about 1/4 or 1/5 as much memory as the Java version, and starts up far more quickly. If a *desktop* application needs to be deployed on older machines, or if the application is so memory-intensive it taxes the limits of today's server hardware, Java still falls flat.
Re:Java is a type-safe language at the VM level... (Score:3, Interesting)
If 'greenhorn' C++ developers can make an app that is even ONE PERCENT faster, then the Java Developers WERE NOT 'highly skilled'. Period. But TWICE as fast? As in, C++ takes 1/2 the time to execute 'x' as the Java version? No way. Not even if we are talking linear algebra code* [home.cern.ch].
An experienced Java programmer knows you have to memory manage large apps. Yes, Java will *always* use more memory than an equally well written C++ app; however, unless you are working *exclusively* with *huge* arr
Re:Java is a type-safe language at the VM level... (Score:3, Insightful)
Re:Java is a type-safe language at the VM level... (Score:3, Insightful)
Re:Java is a type-safe language at the VM level... (Score:5, Interesting)
So you have to measure time per malloc and time per free, then total them up and compare it to GC's time per allocation and time spent in GC. In some cases, one will be significantly larger than the other, but in most nontrivial programs, using modern malloc/free and modern GC, it comes out pretty close to even.
Some argue that the "pause" from GC is a problem. Maybe. Except that as mentioned before, malloc can also "pause" for arbitrarily long times. And a lot of work has been done on "concurrent" GC that doesn't pause. If you can afford paging in from disk (swap file), you can also afford GC's "pause".
Finally, when you write a big program, you spend incredible effort in your program tracking memory. That takes cycles. "If x then save a copy cause we'll have to free it later, etc."
The bottom line is that there are some cases where GC still won't work, but those cases are getting smaller and smaller. For most cases, the argument that GC is slow or inefficient just isn't true. Go do some real benchmarks, or go study up on the already published benchmarks. GC is pretty efficient, and malloc/free has no significant speed advantage anymore.
malloc+free: fast, simple, and can be even faster (Score:5, Informative)
I don't know where you got your understanding of malloc, and especially free, but it's severely out of date. Knuth published about "Boundary Tags" no later than 1973 (citeseer is down, so no link). Saying that a coalesce operation "can be arbirarily slow" is just FUD. A boundary tag makes free() a fast O(1) operation: check the previous block in memory to see if it's free and if so join, a fast O(1) operation; check the next block in memory to see if it's free and if so coalesce; add free block to free-list, done. Yes, it's not zero work like a GC implementation sort-of is, but "arbitrarily slow"? It's basically at least as fast as malloc().
Allocation requests can hit disk, sure, but so can GC allocations even if they're just bumping a pointer: it all depends on the working set size. GC compaction can reduce fragmentation to reduce working set size, but that is only a big win if there's a lot of fragmentation, and most apps using a good malloc() don't exhibit that much. (It is also possible for a GC to rearrange memory so more in-working-set data is on pages together, reducing the working set page count without changing the total memory used. I don't know of any in-use implementations of this, since you need hardware support to know what objects are more-in-use; generally this is only available at the page level, where it's no help. I think maybe an early microde-based Smalltalk implementation might have done this.)
If your malloc has to walk giant free lists to find an open block, then sure, that can be slow. That's why people use trees of free lists based on size and such to make it more O(log N), and O(1) for small allocations. (On large allocations, actually using the memory amortizes the cost.) Read about dlmalloc [oswego.edu], for example.
Furthermore, let's not misrepresent GC. Stop-and-collect GCs have obvious extra costs beyond the free-of-charge free (or lack of need for one). Incremental GCs that don't pause are usually slower overall and only preferred for interactive programs. For example, incremental GCs usually require "write barriers" or "read barriers" which require several extra instruction on every fetch from memory or every write of a pointer variable in memory. This can add up across the entire program. Incremental GCs also tend to be conservative, and only end up collecting things that, say, were garbage at the start of the most recent collection round, and generational collectors allow garbage to collect in later generations for some time, so they don't actually necessarily have a smaller working set than a non-leaky malloc()/free() program.
Another big win in non-GC systems is that you can use pointers that don't come off the heap. That way you can avoid allocation and deallocation and GC entirely. (You can actually do some of this in a GC system too if it's a 'conservative' GC that copes with pointers into the middle of blocks. Those pretty much only get used for adding GC to C and C++, though.) Here are some common ways this happens:
Of course, doing all these things requires that you balance your different types of malloc()s with the correct, matching type of free(). In practice, GC proponents overestimate the diffi
Unsafe code is called -- duh, Unsafe (Score:3, Interesting)
Why is this here? (Score:2)
What a well researched article! (Score:5, Insightful)
Hey, what about the keyword unsafe in C#? Sheesh.
It's called unsafe code for a reason (Score:5, Informative)
Applications that require safety (for example running plugins downloaded from the net) simply don't allow those assemblies to be loaded.
Where is the problem again?
Someone should tell (Score:2, Insightful)
Re:Someone should tell (Score:2)
Too funny. (Score:2)
In
B:
In Java you can write code that harms a computer and deletes files.
A:
You can write code in C#, in which case it is managed and helps prevent you from making stupid mistakes.
B:
You can write code in Java in which case it is somewhat managed and helps prevent you from stupid mistakes.
A:
Under
B:
Under Java you read Sun's doc
Rediculous (Score:2, Interesting)
A
For example: The end user can grant unsafe permissions to the Microsoft Managed Di
Re:Rediculous (Score:5, Insightful)
To me this looks like a similar problem as allowing running native code via ActiveX. Yeah, we have permissions, signing and what ever - how much does it take for a trusted but buggy ActiveX applet to be exploited?
Huge mistake, IMHO. And do not compare this to JNI - I am no Java expert, but AFAIK you simply cannot call JNI functions from something like web applet by design, whereas here it is on the discretion of the app developer.
Why oh why (Score:4, Insightful)
It's the same with C. We should know by now "you cannot use C to handle untrusted data (ie, data from untrusted machines on the net)". All such data need to be handled in a sandboxed system, a system with safe memory access. This means something like Java or similar things.
A lot of people will make posts that say things like "C doesn't cause the problems, it's incompetent or lazy programmers who cause the problems." Whatever. No excuse. That's like saying "we shouldn't need seat belts or airbags; all we need is to make sure that drivers don't make mistakes." Drivers and programmers do make mistakes and that's why we need safety mechanisms in both cases. C provides none. Programming in C is like driving around in a car from the fifties, with no seat belts, no airbags, no head rests, no ABS.
So any decision to extend the use of C is just foolish. What is the purpose of doing this? If people must use horrible legacy code then just use it, but why drag that into new frameworks like
.NET?
It does not compute, for me at least.
Re:Why oh why (Score:3, Informative)
So any decision to extend the use of C is just foolish. What is the purpose of doing this? If people must use horrible legacy code then just use it, but why drag that into new frameworks like
.NET?
Managed C++ is basically a compatibility language. It exists to provide developers an easy way to interface legacy C/C++ code with
.NET code. By providing MC++ Microsoft is actually providing a way for developers to slowly migrate to more modern languages (sorta like JNI with Java; imagine if you couldn't make
Homeowners!! Beware! (Score:5, Funny)
--The Elmer's Glue Foundation for Strength and Security
Beware the agenda (Score:4, Interesting)
Unstructured? Yes. A huge security hole? No more than any other language using COM objects. You can write crappy spaghetti code in any language. The type interface for
What Gosling is really criticising is the way
I believe Gosling is wrong (Score:5, Funny)
Gosling is dead wrong. I believe that Microsoft will soon prove they are capable of even bigger and more offensive security mistakes.
Also, the choice to actually use
.NET is at least as big of a security error.
pots and kettles, you know... (Score:4, Funny)
oh. nevermind.
Yay, more rhetoric from Sun (Score:4, Informative)
In order to use "unsafe" code from managed C++ (or unsafe blocks in C#) you must have "FullTrust" security rights, otherwise the code fails to run.
You could shoot yourself in the foot but the runtime is perfectly capable of detecting and coping with corruption of the managed heap (generally by closing down the offending AppDomain.) Of course you can write a COM component in C++ and call it from dotnet, which is (in effect) the same exact thing! (I dare you to try and stop me from trashing Java or dotnet once I'm loaded in process via JNI or COM...)
CAS (Code Access Security) means that no other code can call your "unsafe" methods without FullTrust either, so there is no danger from code running off the web of doing this.
JNI is the same thing, Sun just gets to hide behind the lie since the risks aren't known by or integrated with the platform. At least with unsafe code the runtime is fully aware of that pointer voodoo magic you are trying to pull and can deal with it appropriately.
In other words Game Developer X can hand-tune the rendering algorithm inside the "unsafe" code areas, but develop the rest of the platform in fully managed code, making the development process much easier to write, test, and debug.
(As an aside, thanks to the antitrust ruling Microsoft is not allowed to comment on a great many things, including competitors. I don't know if this falls under that heading, but in many cases Microsoft's employees can't just come out and call bullshit when they see it for legal reasons.)
In conclusion: Sun should shut the hell up.
C programmer deals with it (Score:5, Insightful)
Yes, CowboyNeal, but do they want to deal with it, and should they deal with it?
For every programmer who reads security bulletins and keeps tabs on the latest string-copying buffer overflow issues and fundamental security principles, there are a hundred who don't know or care.
C is a high-level language that:
Programmers want to be productive -- most want to make things make colourful stuff happen on the screen, not fiddle around with buffer guard code. So the more security can be built into the language and its running environment, the better.
Many languages, such as Python or Ruby, provide security against what I mention in my first bullet, through a virtual machine. They're not impenetrable, and are of course, as dynamic languages, subject to a different class of security holes (eg., string evaluation of code), but they're a step up from the C level.
Other languages, like Java, provide capability-based security models, allowing for sandbox environments with fine-grained control over what a program may or may not do. Java's security system is ambitious, but since most Java apps run on the server these days, it's not frequently used, and except for browser applets, Java code tend to run unchecked.
In a way, Java tries to do what the OS should be doing. Programs run on behalf of its human user, and their destructive power is scary. Why should any given program running on my PC have full access to my documents or personal data? As we're entering an age where we have more and smaller programs, and the difference between "my PC" and "the net" is increasingly blurred. Operating systems need to evolve into being able to distinguish between different capabilities it can grant to programs, or processes -- we need to think about our programs as servants that are doing work for us by proxy.
The same way you wouldn't let a personal servant manage your credit cards, you don't want to let your program do it -- unless, of course, it was a servant (or, following this metaphor, program) hired to deal with credit cards, which introduces the idea of trust. The personal accountant trusts the bank clerk, who trusts the people handling the vault, who trust the people who built the vault, and so on.
In short, any modern computer system needs to support the notions of delegated powers, and trust.
Programmers will certainly never stop having to consider vulnerabilities in code. But painstakingly working around pitfalls inherent in one's language, be it C or indeed
.NET -- we need to evolve past that. The users, upon whom we exert so much power, certainly deserve it.
Gosling Emacs security holes + spyware + malware! (Score:4, Funny)
Emacs has a notorious "shell" facility that can actually run a shell and send it arbitrary commands!!!
In fact, there's even a built-in scripting langauge called "Mocklisp" that enables hackers and viruses to totally reprogram the behavior of the editor (and it looks like Lisp, but without any of those confusing lexical closures and list processing functions).
Gosling Emacs is actually spyware, because it has a hidden "keyboard macro" facility that can spy on every character you type! Emacs is also malware, because at any point it can instantly undo any editing changes you've made!
One of the biggest most offensive mistakes is that James Gosling has not fixed these huge security holes in Emacs, after all these years. In fact, many of the security holes have been reimplemented in another notorious piece of communist spyware called Gnu Emacs!
All Emacs should be banned!!!
-Don
Gosling is right, but Java has the same problem (Score:3, Interesting)
If you want to implement a system based on language-level security using a mixture of code in safe and unsafe languages, as little as possible of the system must be written in the unsafe language(s), and that part must be treated as being in the system TCB.
Some unsafe code is unavoidable if you want the system to be able to use OS facilities on Windows and Unix. However, it must be written by people who know how to write secure code, and gone over with a fine-tooth comb for possible weaknesses.
It is completely disingenuous for either Microsoft or Sun to claim that these platforms are secure, given that their implementations depend on millions of lines of unsafe-language code that no-one is ever going to review properly. Even more so since both
So basically, Gosling's argument is correct:
Re:James Gosling is an expert in this area (Score:4, Interesting)
No, Java is not suitable (or useful) for what an engineer would call a "critical" application. Those applications are coded in C or C++ (or Assembler).
I'm using java because that was the business decision made by my boss (or my boss' boss). So I'm just told what I have to do (what interface the user expects, what system I have to connect to, etc.) But for the company I work for, Java might be a critical part of their business plan.
For example, you won't find java in a heart monitor in the hospital but probably find the server that keeps your health records is done in Java. Whoever is developing the Health record system can (more or less) pass the code to a new developer to continue working on it without expecting the new guy to be an expert on that particular system.
Anyway, this could all be bullshit if sound coding practices are not follow on ANY language.
Re:James Gosling is an expert in this area (Score:3, Insightful) | http://it.slashdot.org/story/05/02/04/2139259/gosling-claims-huge-security-hole-in-net | CC-MAIN-2015-11 | refinedweb | 7,174 | 62.58 |
Introduction
In a previous tutorial, we showed you how to Receive a Phone Call with Java and respond using Text-to-Speech. In addition to receiving a phone call, you can also make outgoing phone calls.
In this tutorial, you will create an application that can make outgoing text-to-speech phone calls utilizing Java and the Vonage Voice 11, which is the current LTS, in this tutorial.
Finally, you’ll need the Vonage CLI installed. You’ll use it to configure your Vonage account to point at your new application.
Make Text-to-Speech Phone Call with Java
This tutorial will walk you through the following steps:
- Signup for a Vonage account and get a phone number and create an application.
- Using Gradle to initialize a new Java application.
- Using the Vonage Java Client Library to initiate a phone call and execute text-to-speech.
Configure Your Vonage Account
If you do not have an application, you can use the Vonage CLI to create one. You will need to define the name of the application, and an answer and event URL that the Voice API will use by default:
- The Vonage Voice API will make a request to your answer URL when a phone number linked to your application receives a phone call.
- The Vonage Voice API will make requests to your event URL when various status changes occur.
To learn more about applications see our Vonage Concepts Guide.
Use the following command to create an application using the Vonage CLI:
vonage apps:create "Send TTS Call" --voice_answer_url= --voice_event_url=
This command will also create a file called
private.key which you will need to authenticate with the Vonage Voice API to make calls. This file will be saved to the directory you run the command inside of. Also make a note of the Application ID that is returned, as you will need it later.
Using Gradle to Set Up a New Java Project
You will be using Gradle to manage your dependencies and to create and run your Java application.
The
gradle init --type=java-application command will create all of the folders you need as well as a sample class where you will be writing your code.
From the command line, create a new Java project with the following command and accept the default values at the interactive prompts:
mkdir make-tts-call cd make-tts-call gradle init --type java-application
Gradle will create the
App class in the
src/main/java/make/tts make.tts.call; public class App { public static void main(String[] args) { // Future Code Goes Here } }
Add the Dependencies
You will be using the Vonage Java Library to communicate with the Vonage Voice API. Add the following to the
dependencies block in your
build.gradle file:
// Nexmo Java Client implementation 'com.nexmo:client:4.2.0'
Initialize the Nexmo Client
The Vonage Java Library contains a
NexmoClient class which gives you access to the various Vonage APIs. You will use your Application ID, and the path to your
private.key file from a previous step. The
NexmoClient will use this information to authenticate to the Vonage Voice API.
Add the following to the
main method of the
App class, resolving any imports:
NexmoClient nexmoClient = NexmoClient.builder() .applicationId(APPLICATION_ID) .privateKeyPath(PRIVATE_KEY_PATH) .build(); VoiceClient voiceClient = nexmoClient.getVoiceClient();
The
NexmoClient throws an
Exception if the private key file cannot be loaded. For the sake of convenience, modify your
main method signature to throw any exceptions. Your
main method should now look like this:
public static void main(String[] args) throws Exception { NexmoClient nexmoClient = NexmoClient.builder()` .applicationId(APPLICATION_ID) .privateKeyPath(PRIVATE_KEY_PATH) .build(); VoiceClient voiceClient = nexmoClient.getVoiceClient(); }
Build the Nexmo Call Control Object
The Vonage Voice API is controlled using Nexmo Call Control Object (NCCO). An NCCO is a JSON array which contains a set of actions that the Voice API will execute.
The following NCCO will instruct the Vonage Voice API to speak to the recipient when they answer the call:
[ { "action": "talk", "text": "This is a text-to-speech call from Vonage" } ]
The Vonage Java Client Library provides classes that allow you to construct an NCCO. You will use the
Ncco and
TalkAction classes to build the NCCO.
Add the following to the
main method, resolving any imports:
TalkAction intro = TalkAction.builder("This is a text-to-speech call from Vonage").build(); Ncco ncco = new Ncco(intro);
Make the Phone Call
The
VoiceClient contains a method called
createCall which expects a
com.nexmo.client.voice.Call. The
Call object is used to define which number you're calling from, the recipient you wish to call, and the NCCO to control the call.
Create a new
Call object in the
main method and invoke the
createCall method with the created object, resolving any imports:
Call call = new Call(TO_NUMBER, NEXMO_NUMBER, ncco); voiceClient.createCall(call);
Test Your Application
Start your application with the
gradle run command inside of your
make-tts-call directory. You should receive a phone call from your Vonage number.
Once you answer this call, the Vonage Voice API will speak the message, "This is a text-to-speech call from Vonage."
Conclusion
In a few lines of code, you have created an application that can call a recipient and speak a message.
Check out our documentation on Vonage Developer where you can learn more about call flow or Nexmo Call Control Objects. See our Nexmo Code Snippets for Java for full code examples on this tutorial and more. | https://developer.vonage.com/blog/2019/03/21/make-text-to-speech-phone-call-java-dr | CC-MAIN-2022-27 | refinedweb | 913 | 53.1 |
4 Core Concepts of. The next person to ask me will receive a fully detailed answer, an essay even. So buckle up for my official answer…
someone: What is Object Oriented Programming?
me: What a great question! Object Oriented Programming (OOP) is a programming paradigm that makes developing large projects easier and has four core concepts:
- Encapsulation
- Inheritance
- Abstraction
- Polymorphism
OOP differs a little per language, for example in Ruby, C#, JavaScript and Python, but the overall concept is the same.
Encapsulation
OOP centres around ‘objects’, common examples are to imagine a cat, a dog or a person. Each of these objects will have their own individual attributes and their own individual methods/behaviours like walk, talk, meow, bark, and so on. To stop these objects from interacting with each other when they shouldn’t, they need to be encapsulated.
Encapsulation refers to holding each object inside a defined boundary, this limiting interference from other objects. A bonus of this is data hiding and security measures.
Class names are a way of encapsulating and producing objects that are alike. Cats and dogs can be stored under the class of ‘Animal’, but not a person. If you had a class called ‘Language’ you could produce objects called Ruby, Python and JavaScript!
In Ruby, if we wanted to create a class like the above, it would look like this:
class Language def initialize(name, creator) @name = name @creator = creator end
def description puts "I'm #{@name} and I was created by #{@creator}!" endendruby = Language.new("Ruby", "Yukihiro Matsumoto")python = Language.new("Python", "Guido van Rossum")javascript = Language.new("JavaScript", "Brendan Eich")
ruby.descriptionpython.descriptionjavascript.description
What we’ve done here is defined the class name, and give it two variables (name, creator) unique to that class and its objects. Whatever object we produce from this class will use those variables.
The
def is a method (function) that each object we create under Language will have access to.
The lines referring to
Language.new()are filling out the parameters for name & creator, for example “Python” was created by “Guido van Rossum” — there’s your fun fact for the day. So when we call
javascript.description we are calling the method defined above, and we will get an output of
“I’m JavaScript and I was created by Brendan Eich!”
instead of “I’m #{@name} and I was created by #{@creator}!”.
Inheritance
Now we move on to inheritance, which is when the classes essentially share (inherit) from each other. A vague example of this is a class called Computers and class called Phones could inherit from each other for a method call send_email, rather than having to type it all out again for every object you have that can send an email.
Abstraction
Abstraction is a bit like a cover blanket. It hides what isn’t relevant for the use of other objects and only exposes high methods that are public. When you turn your phone on, it’s done at the click of a button, and a click of a button is all we see on the surface, but inside your phone much more than that happened underneath the hood, especially for mobiles that have finger-ID. Abstraction hides all the details and technical pieces. This is also a security measure against exposing personal data.
Polymorphism
Polymorphism is what it sounds like. Morphing, different shapes, different forms. Objects can ‘morph’ when necessary and take on many forms in a parent — child relationship. There are two types of polymorphism: static and dynamic. But that’s an explanation for part two.
Happy coding!!! | https://oliviacodes.medium.com/junior-devs-object-oriented-programming-bcf45d0d7adf?source=post_internal_links---------6---------------------------- | CC-MAIN-2022-33 | refinedweb | 598 | 64.2 |
Objects are usually models of conceptual or real-world entities; they consist of a combination of data, which models the state of the entity and operations which model the behavior of the entity. The body of a Sather class consists of a list of features which define the data and behavior of the class. A class defines a new type and may be used to create object instances of that type.[1]
[1] This is only true for reference, immutable and some kinds of external classes. Abstract a, partial and most external classes cannot have instances. state of a class is defined by attributes, which are have the prefix attr:
The POINT class above defines an 'x' and a 'y' attribute both of which are integers. This class is useless, as it stands, since it provides no way to create instances of itself.
To make objects of the POINT class, we have to introduce a create routine
The create routine first calls the special expression 'new'. 'new' creates a new uninitialized instance of the POINT class and returns it. All the attributes in the new instance have default 'void' values. It then assigns the 'x' and 'y' attributes of this new instance to xvalue and yvalue respectively. Instances of the POINT class can then be created as shown below
Since creation is such a common operation, Sather provides a special shorthand for calls to the routine 'create'. The 'create' routine shown could be invoked with the # sign as shown below
Expressions using the # sign are referred to as creation expressions, and are a convenient shorthand used for creating new objects and initializing their attributes.
When an object of the class POINT is created, the 'x' and 'y' attributes may be accessed by 'dotting' into the object.
The semantics of a class is independent of the textual order of its class elements. In particular, the actual attribute layout used by a Sather implementation is invisible to a programmer.
The scope of feature names is the class body
Feature names may be either lower or upper case.
Class names must be all upper case letters (underscores and digits are permitted except as the first character).
The feature namespace is separate from the class namespace.
The scope of class names is the entire program; no two classes can have the same name (unless they have different number of parameters, which will be explained in the chapter on class parametrization).
You have to explicitly call 'new' in the create routine. The following code exhibits a common error:
Before a variable is assigned to an object, the variable has the void value. The expression 'void' may be used to determine whether a value is void or not.
The following example will print out the string "a is void!" since a POINT is a reference class and 'a' has not been created.
In the second version, the string "a is not void!" will be printed since an object has been assigned to the variable 'a':
Note that the above test will not work in the same way for some of the built-in classes such as integers and booleans[2].
[2] The void test returns true for all integers with a value of 0 and booleans with a value of false. In general, the void test is not useful for immutable classes.
Each Sather variable and object has an associated type. The type of the object indicates the class that was used to create the object. In the following example, both 'a' and 'b' have the type POINT, indicating that they are associated with instances of the POINT class.
In this example, the type of the variable 'a' is the same as the type of the object to which it is assigned. This is always the case with the reference classes we have seen so far.
When we introduce abstract classes (unnamedlink),).
A fundamental feature of object oriented programming languages is that they permit an object to hide certain features which are for internal use only. Attributes may be completely hidden by marking them private. Routines may likewise be marked private, meaning that they cannot be accessed outside the original class. Attributes can also be hidden so that they can be read but not modified from outside the class, by marking them readonly.
This restricts external access to the attributes in the object
Privacy is on a per-class basis, rather than on a per-object basis. Thus, an object can access the private features of other objects of the same class. We actually use this fact in the create routine of the class POINT2 above. Assignments to the attributes of res are being done outside the object being returned. | http://www.gnu.org/software/sather/docs-1.2/tutorial/classes275.html | CC-MAIN-2014-42 | refinedweb | 784 | 61.56 |
Recompiling for different channels
Could someone help me understading how to recmpile MYSBootloader for a different channel?
I searched around but I haven't found a guide or anything similar.
I'm not very familiar with gcc and it's configurations...
I could work both on a Windows or Linux box, I guess the second could be easier to set up.
Daniele
@danielef First load the clear eeprom sketch for the gateway and nodes. This will let you start with a clean arduino.
Then simply add
#define MY_RF24_CHANNEL (97)
(Or whatever channel you want)
This MUST be Before
#include <MySensors.h>
in your sketch.
No recompiling needed.
Note that I am assuming that you are using mysensors 2.3.0, an nrf24l01+ and an arduino gateway/node.
Might not work, but perhaps you start by modyfing line 53 in MYSBootloader.c () and then recompile?
(That's not arduiono code, so I'd use commandline and start with "make")
Aha, then I take it all back!
I thought DanieleF was simply wanting to use a different channel and had assumed that the bootloader needed to be modified to do this (as was the case in earlier versions of my sensors).
@rejoe2 I tried this, and I also changed the frequency in the makefile (CLK = ... at line 8), but when I flash this bootloader, the arduino hangs and I'm not able to upload any sketch.
I'm using a micro 3.3V 8MHz and MYSBootloader DEV branch.
@danielef Didn't find any option to change CLK and imo this should not be necessary (hope all the three versions are build and you have just to choose the right one for your board).
As the file states, it was build using the 2.2 MySensors version. Perhaps you have to downgrade first (and then go back after BL is build successfully).
The option I found is here.
When I run make, only one hex file is generated, so I assumed I have to change it in order to configure che frequency of my arduino.
BTW, I don't understand your reference to MySensors version: I'm compiling a C program, not ann Arduino sketch (and I haven't seen a place to give the path to MySensors library).
@danielef OK, seems your changes have been ok.
I didn't check any dependencies, just saw tekka's remark in Line 4 of MYSBootloader.c.
Did you add anything in your boards definitions in Arduino IDE for the new BL? Or tried to use the BL definitions from boards.txt included already in the repo?
I'm using the definitions from board.txt available in the repo, simply changing the hex file in the folder where the IDE searches the bootloaders.
@danielef said in Recompiling for different channels:
I'm using a micro 3.3V 8MHz and MYSBootloader DEV branch.
Sorry, didn't realize this when first reading through it.
So are you using a ATmega328p as mcu (pro mini) or in fact a pro micro (ATMega32U..)?
The BL project seems to be limited to the first mcu type (L8 of MYSBootloader.c). Porting to the other mcu most likely is much more work, as this should support upload through USB also.
Sorry, my mystake!!!
Pro mini!
Seems I'm running out of ideas. If you are sure to have flashed succcessfully the new BL and won't get any sync afterwards to upload any sketch built using that board def, most likely you shoud open an issue in github wrt that.
(I myself went the other way round and modified the MYSENSORS modules in FHEM to make use of a second Gateway for flash purposes only - this GW with the standard channel (etc.) settings... Testing is ongoing, but seems to work)
Suggested Topics
MYSBootloader 1.3 pre-release & MYSController 1.0.0beta
MYSBootloader 1.4 testing
ESP8266 WiFi MQTT gateway won't respond to parent request.
MYSBootloader 1.3pre2 testing
Firmware does not load MYSController & MYSBootloaderV13pre
Windows GUI/Controller for MySensors
Bootloader ATmega 2560 for OTA
MY_DEBUG_OTA results in compile errors | https://forum.mysensors.org/topic/9930/recompiling-for-different-channels/13 | CC-MAIN-2019-35 | refinedweb | 678 | 74.9 |
Lecture 13 — Data from Files and Web Pages¶
Overview¶
- Files on your computer
- Opening and reading files (review)
- Closing (new)
- Writing files (new)
- Accessing files across the web
- Parsing basics
- Parsing html
Our discussion is only loosely tied to Chapter 8 of the text.
Review — String operations often used in file parsing¶
Let’s review and go over some very common string operations that are particularly useful in parsing files.
Remove characters from the beginning, end or both sides of a string with lstrip, rstrip and strip:
>>>>> x.strip("red!") " Let's go red! Go red! Go " >>> x.lstrip("red!") " Let's go red! Go red! Go red!" >>> x.rstrip("red!") "red! Let's go red! Go red! Go " >>> " Go red! ".strip() 'Go red!'
Space is the character removed by default.
Split a string using a delimiter, and get a list of strings. Space is the default delimiter:
>>>>> x.split() ["Let's", 'go', 'red!', "Let's", 'go', 'red!', 'Go', 'red!', 'Go', 'red!'] >>> x.split("!") ["Let's go red", " Let's go red", ' Go red', ' Go red', ''] >>> x.split("red!") ["Let's go ", " Let's go ", ' Go ', ' Go ', '']
It returns the strings before and after the delimiter string in a list.
Find the first location of a substring in a string, return -1 if not found. You can also optionally give a starting and end point to search from:
>>> x "Let's go red! Let's go red! Go red! Go red!" >>> x.find('red') 9 >>> x.find('Red') -1 >>> x.find('red',10) 23 >>> x.find('red',10,12) -1 >>> 'red' in x True >>> 'Red' in x False
Opening and Reading Files¶
Given the name of a file as a string, we can open it to read:
f = open('abc.txt')
This is the same as
f = open('abc.txt','r')
- Variable
fnow “points” to the first line of file
abc.txt.
- The
'r'tells Python we will be reading from this file — this is the default.
We can read in data through three primary methods. First,
line = f.readline()
reads in the next line up to and including the end-of-line character, and “advances”
fto point to the next line of file
abc.txt.
By contrast,
s = f.read()
reads the entire remainder of the input file as a single string,
- storing the one (big) string in
s, and
- advancing
fto the end of the file!
When you are at the end of a file,
f.read()and
f.readline()will both return
""(empty string).
Reading the contents of a file¶
The most common way to read a file is as follows:
f = open('abc.txt') for line in f: print line
This for loop will equivalent to the following:
f = open('abc.txt') for each line in the file: line is assigned the string corresponding to the contents of the line, including the new line
You can combine the above steps into a single for loop:
for line in open('abc.txt'): ....
Closing and Reopening Files¶
The code below closes and reopens a file
f = open('abc.txt') # Insert whatever code is need to read from the file # and use its contents ... f.close() f = open('abc.txt')
fnow points again to the beginning of the file.
This can be used to read the same file multiple times.
Writing to a File¶
In order to write to a file we must first open it and associate it with a file variable, e.g.
f_out = open("outfile.txt","w")
The
"w"signifies write mode which causes Python to completely delete the previous contents of
outfile.txt(if the file previously existed).
It is also possible to use append mode:
f_out = open("outfile.txt","a")
which means that the contents of
outfile.txtare kept and new output is added to the end of the file.
Write mode is much more common than append mode.
To actually write to a file, we use the
writemethod:
f_out.write("Hello world!")
- Each call to
writepasses only a single string.
- Unlike what happens when using
- The string may be formatted
You must close the files you write! Otherwise, the changes you made will not be recorded!!
f_out.close()
Part 1 Exercise¶
Given the file
census_data.txt:
Location 2000 2011 New York State 18,976,811 19,378,102 New York City 8,008,686 8,175,133
What are the value of variables
line1,
line2,
line3, and
line4after the following code executes?
f = open("census_data.txt") line1 = f.readline() line2 = f.read() line3 = f.readline() f.close() f = open("census_data.txt") line4 = f.readline()
For the same data above, what does the following program produce?
f = open('census_data.txt') s = f.read() line_list = s.split('\n') print len(line_list)
Write code to print all the lines in the above file except for the header line (the first line).
Given a file containing test scores, one per line, write Python code to write a second file with the scores output in decreasing order, one per line, with the index on each line. For example, if the input file contains:
75 98 21 66 83
then the output file should contain:
0: 98 1: 83 2: 75 3: 66 4: 21
This can be done in 10 or fewer lines of Python code.
Opening Static Web Pages¶
We can use the
urllibmodule to access web pages.
We did this with our very first “real” example:
import urllib words_file = urllib.urlopen(words_url)
Once we have
words_filewe can use the
read,
readline, and
closemethods just like we did with “ordinary” files.
When the web page is dynamic, we usually need to work through a separate API (application program interface) to access the contents of the web site. Recall the Flickr example.
Parsing¶
- Before writing code to read a data file or to read the contents of a web page, we must know the format of the data in the file.
- The work of reading a data file or a web page is referred to as parsing.
- Files can be of a fixed well-known format
- Python code
- C++ code
- HTML (HyperText Markup Language, used in all web pages)
- JSON (Javascript Object Notation, a common data exchange format)
- RDF (resource description framework)
- Often there is a parser module for these formats that you can simply use instead of implementing them from scratch
- For code, parsers check for syntax errors.
Short tour of data formats¶
Python code:
- Each statement is on a separate line
- Changes in indentation are used to indicate entry/exit to blocks of code, e.g. within
def,
for,
if,
while...
HTML: Basic structure is a mix of text with commands that are inside “tags”
< ... >.
Example:
<html> <head> <title>HTML example for CSCI-100</title> </head> <body> This is a page about <a href="">Python</a>. It contains links and other information. </body> </html>
Despite the clean formatting of this example, html is in fact free-form, so that, for example, the following produces exactly the same web page:
<html><head><title>HTML example for CSCI-100</title> </head> <body> This is a page about <a href="">Python</a>. It contains links and other information. </body> </html>
JSON: used often with Python in many Web based APIs:
{ "class_name": "CSCI 1100" , "lab_sections" : [ { "name": "Section 01" , "scheduled": "T 10AM-12PM" , "location": "Sage 2704" } , { "name": "Section 02" , "scheduled": "T 12PM-2PM" , "location": "Sage 2112" } ] }
Similar to HTML, spaces do not matter.
Simplejson is a simple module for converting between a string in JSON format and a Python variable:
>>> import simplejson as sj >>>>> sj.loads(x) ['a', ['b', 3]]
Parsing ad-hoc data formats - Regular tabular data¶
We will examine some simple formats that you have already seen in various homeworks.
Parsing files with fixed format in each line, delimited by a character
Often used: comma (csv), tab or space
Example: lego list:
2x1, 2 2x2, 3
Is there a header or not?
Pseudo code:
for each line of the file split using the separator read each column
Exercise: write a simple parser for the lego list that returns a list of the form:
['2x1', '2x1', '2x2', '2x2', '2x2']
Parsing ad-hoc data formats - Irregular tabular data¶
Parsing files with one line per row of information, different columns containing unknown amount of information seperated with a secondary delimiter
Example: Yelp from Lab 4:
Meka’s Lounge|42.74|-73.69|407 River Street+Troy, NY 12180|
Information after column 5 are all reviews
The address field is separated with a plus sign
Pseudo code:
for each line of the file split using the separator read column with secondary separator, split for each value in the column read value
Exercise: Return the address as a list of [street, city, state, zip] and the number of reviews for each line of the Yelp file.
Parsing ad-hoc data formats - Nontabular data that spans multiple lines¶
More complex file formats:
Blocks of data (of unknown length) separated by spaces making up a record:
4590 - Friday, July 16, 2004 Comments: Ken Jennings game 33. Contestants: Frank McNeil: a facilities management specialist from Louisville, Kentucky Mary McCarthy: a homemaker from Las Vegas, Nevada Ken Jennings: a software engineer from Salt Lake City, Utah (whose 32-day cash winnings total $1,050,460) First Jeopardy! Round: AMERICAN WRITERS, IT'S A TEAM THING, NOT NO. 1, POPULATIONS, WHIRLED CAPITALS, THE ANATOMY OF EVEL AMERICAN WRITERS | 8 days after publishing his first novel, "This Side of Paradise", he married Zelda Sayre | (F. Scott) Fitzgerald right: Ken Wrong: Value: $200 Number: 1 AMERICAN WRITERS | His ability to imitate the family doctor earned him this playwright the nickname "Doc" | Neil Simon right: Wrong: Triple Stumper Frank: Who was Eugene O'Neill? Value: $400 Number: 2
Pseudo code:
for each line in the file if the line in the same block as the previous add to the block of lines to process else process the current block start a new block
Exercise: Write a simple piece of code to decide when a new block is reached. What is the initial value?
Summary¶
- You should now be comfortable opening, reading, writing and closing files on local computers.
- Once text (or HTML) files found on the web are opened, the same reading methods apply just as though the files were local. Binary files such as images require special modules.
- Parsing a file requires understanding its format, which is, in a sense, the “language” in which it is written.
- We will continue with file parsing exercises in Lab 7 and in HW 6. | http://www.cs.rpi.edu/~sibel/csci1100/fall2015/course_notes/lec13_files_web.html | CC-MAIN-2018-05 | refinedweb | 1,750 | 71.55 |
Remove numbers from string in Python
In this article, we will learn to delete numerical values from a given string in Python. We will use some built-in functions and some custom codes"
A string in Python can contain numbers, characters, special characters, spaces, commas, etc. We will learn four different ways to remove numbers from a string and will print a new modified string.
Example: Remove Numbers from String using regex
Python provides a regex module that has a built-in function
sub() to remove numbers from the string. This method replaces all the occurrences of the given pattern in the string with a replacement string. If the pattern is not found in the string, then it returns the same string.
In the below example, we take a pattern as r'[0-9]’ and an empty string as a replacement string. This pattern matches with all the numbers in the given string and the sub() function replaces all the matched digits with an empty string. It then deletes all the matched numbers.
#regex module import re #original string string1 = "Hello!James12,India2020" pattern = r'[0-9]' # Match all digits in the string and replace them with an empty string new_string = re.sub(pattern, '', string1) print(new_string)
Hello!James,India
Example: Remove Numbers from String using join() & isdigit()
This method uses
isdigit() to check whether the element is a digit or not. It returns True if the element is a digit. This method uses for loop to iterate over each character in the string.
The below example skips all numbers from the string while iterating and joins all remaining characters to print a new string.
string1 = "Hello!James12,India2020" #iterating over each element new_string = ''.join((x for x in string1 if not x.isdigit())) print(new_string)
Hello!James,India
Example: Remove Numbers from String using translate()
This method uses
string Python library. With the help of a string object,
maketrans() separates numbers from the given string. Afterward, a translation table is created where each digit character i.e. ‘0’ to ‘9’ will be mapped to None and this translation table is passed to
translate() function.
The below example creates a translation table and replaces characters in string based on this table, so it will delete all numbers from the string
import string string1 = "Hello!James12,India2020" #digits are mapped to None translation_table = str.maketrans('', '', string.digits) #deletes all number new_string = string1.translate(translation_table) print(new_string)
Hello!James,India
Example: Remove Numbers from String
This example uses the filter() and lambda in the generating expression. It filters or deletes all the numbers from the given string and joins the remaining characters of the string to create a new string.
The filter() function uses the original string and lambda expression as its arguments. First, we filtered all digit characters from a string and then joined all the remaining characters.
#original string string1 = "Hello!James12,India2020" #Filters all digits new_string = ''.join(filter(lambda x: not x.isdigit(), string1)) print(new_string)
Hello!James,India
Conclusion
In this article, we learned to remove numerical values from the given string of characters. We used different built-in functions such as
join(),
isdigit(),
filter(),
lambda,
sub() of regex module. We used custom codes as well to understand the topic. | https://www.studytonight.com/python-howtos/remove-numbers-from-string-in-python | CC-MAIN-2022-21 | refinedweb | 542 | 66.54 |
Note: This document is written against rev776 on February 14, 2006 (not that it should matter)
Writing Tests
TurboGears tries to achieve good test coverage. This helps to keep bugs from becoming problems and lets developers know when they break something by changing some code that would seem to be unrelated. A patch with tests is more likely to be accepted and will generally be accepted faster than the same patch without tests.
What to test
Virtually every patch that somone creates comes with an implicit contract for its use: what parameters it takes and what its output should be. A simple example from turbogears/widgets/tests/test_widgets.py:
def test_label(): """Tests simple labels""" label = widgets.Label("foo") rendered = label.render("The Foo") print rendered assert """<LABEL CLASS="label" FOR="foo">The Foo</LABEL>""" == rendered
This exercises the label widget's creation interface (by setting the name to 'foo'), its render method (setting the labeltext to 'The Foo') and ensures their correctness by checking the rendered output.
Most interfaces will be more complex and there will be considerably more assertions.
The other main source of tests is to exercise a bug and verify that it's fixed and remains fixed. The following test method demonstrates this (incidentally it's from the same file as the previous example):
def test_ticket272(): """ TextFields with a "name" attribute = "title" should be OK """ w = widgets.TableForm(fields=[widgets.TextField(name='title')]) output = w.render().lower() assert 'value' not in output
How to test
Nose is an extension of the builtin python unittest module but provides additional features (such as fixtures and auto-discovery and starting the tests as soon as the first is found). For full documentation, see the nose documentation for test writing.
Nose defines a test case as any function or method starting with 'test' or 'Test'. All testing is done using the builtin python assert statement. If you have a setup_func or teardown_func fixture defined, it will be run before/after every test case.·
The only tricky part of testing comes when you're trying to test for exceptions. The following is the easiest way to do this is:
try: val = Ipv4.to_python('blueberry') assert False, "should have raised an exception" except Invalid, e: assert e.msg == Ipv4._messages['not_a_ip'] | http://trac.turbogears.org/wiki/WritingTests?version=1 | CC-MAIN-2015-22 | refinedweb | 378 | 53.81 |
I'm trying to speed up the time taken to compile my application and one
thing I'm investigating is to check what resources, if any, I can add to
the build machine to speed things up. To this end, how do I figure out if I
should invest in more CPU, more RAM, a better hard disk or whether the
process is being bound by some other resource? I already saw this (How to
check if app is cpu-bound or me
I have a datagridview in vb.net that is bound to a datasource. I did
this in design view, and I wanted minimum coding.
So without
any SQL, I did the following steps:
AllDB_dataset
i have to maintain a list of numbers, count up to 100,000...
if the data is (for example)
1, 4, 9, 12, 20, 35,
52, 77, 91
and i query for a number, say 27, i want the
number just immediately previous to 27, available in the list, so that will
be: 20
the data is also going to be modified frequently, like
lots of Inserts and erases.
I have a checkbox in a UserControl:
<CheckBox
Content="Existing" IsChecked="{Binding Path=IsExistingTemplate,
Mode=TwoWay}"/>
It is bound to a
DataContext with Property IsExistingTemplate which always returns False.
(In my real application, it doesn't always return False!). DataContext
implements INotifyPropertyChanged.
pub
For example:
class MyClass<T extends MyClass2> { // Do stuff...}
Then later:
MyClass<MyClass2> myClass = new MyClass<MyClass2>();
Does this work? My coworker's hunch is no, but I can't
find anything to confirm that for me and the documentation suggests
perhaps.
I have a binding to an unknown source. All I have is the binding. I have
no other way of looking at the bound object. I need to figure out the Type
for the bound object, even if the value is null (this is where my problem
is).
I was evaluating the binding by binding to an object and
then using the object as a way to get the Type, but I need to know the type
even if the value is null
Case:
public class customer{ public string
Adress { get; set; }}
Xaml:
<Grid x:
<StackPanel> <TextBox Text="{Binding Adress}"/> </StackPanel></Grid>
.cs
public MainPage() {
Finding
Bound
property
from
UIelement
after
I have a program where I send data over TCP link. I am using
Asynchronous Reads and writes to both the disk and network. If I put a
DeflateStream in the middle (so I compress before I write to the network
link and I decompress when I receive the data and write it out to the disk)
I am CPU bound on the compressing side. This causes my max transfer rate to
be about 300 KB/s. However
300 KB/s
I've got an application that does few computational CPU work, but mostly
memory accesses (allocating objects and moving them around, there's few
numeric or arithmetic code).
How can I measure the share of the
time that am I spending in memory access latencies (due to cache misses),
with the CPU being idle?
I should note that the app is running
on a Hyper-V guest; I'm not | http://bighow.org/tags/bound/1 | CC-MAIN-2017-47 | refinedweb | 533 | 67.69 |
One of the major critics against the user controls is that everyone thinks that it is not possible to share them across multiple web applications and that you need to do some cut and paste to reuse them. Well, we will see in this article that this critic is wrong and that it is possible to share user controls across multiple applications. Lets see how and the steps to achieve this.
First let's create a web project in Visual Studio .NET that will contain all user controls that we need to share.
For our demo, we add a new user control named DateBox.ascx to the project and add a calendar and two labels to it.
In order to demonstrate that it is also possible to reuse the code behind along with the user control we will add some custom code to the page_load event.
page_load
public string Company
{
get { return _company; }
set { _company = value; }
}
public string Year
{
get { return _year; }
set { _year = value; }
}
protected void Page_Load(object sender, System.EventArgs e)
{
Response.Write("DateBox Page Load Event successfully called!");
lblDate.Text = Year;
lblCompany.Text = Company;
}
private string _company,
_year;.
AssemblyKeyFile
filename
path
sn.exe -k ControlsLibraryKeys.snk
Next, we build our solution and to register our assembly in the GAC we choose to either drag and drop it directly in the \WINNT\assembly folder or use the following DOS command.
Gacutil.exe -i yourassemblypath
We must also inform the ASPX compiler that we want him to check for our new shared assembly. To do that we need to edit the machine.config. This file contains most .NET configuration of our local machine. You can find it in the following directory:
\WINNT\Microsoft.net\FrameWork\YourVersion\CONFIG
Load the file in a plain text editor and search for the <assemblies> element, add the following child element to it :
<assemblies>
<add assembly="UserControlsLibrary, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=29f4c43ca2dde360"/>
These values might change depending on your current settings. You can get the current publicKeyToken of your assembly from the \WINNT\assembly folder.
publicKeyToken functionality user control we must first add the register directive in the HTML part of our page.
<%@ Register TagPrefix="DNG" TagName="DateBox"
Src="~/Controls/DateBox.ascx" %>.
<DNG:DateBox
If we did everything correctly our shared user control should appear on our test page.
Looks nice ;)
We can also use and set the user control properties directly from the code behind of our aspx page.
public class WebForm1 : System.Web.UI.Page
{
protected DateBox DateBox1;
private void Page_Load(object sender, System.EventArgs e)
{
DateBox1.Company = "Amiga";
DateBox1.Year = "1985";
}
}
For people who love using the dynamic features of ASP.NET you can also use this solution to add dynamically.
This article was originally published in French at dotnetguru. | https://www.codeproject.com/script/Articles/View.aspx?aid=4971 | CC-MAIN-2017-47 | refinedweb | 463 | 50.73 |
Welcome to the Parallax Discussion Forums, sign-up to participate.
Tracy Allen wrote: »
I'm attaching two files, one a BS2pe program (which can run in other Stamps too), and an Excel spreadsheet.
#define RBIAS_OHM 20000
#define ADCRES_BITS 12
#define PTC_ADC(r) ( (r << ADCRES_BITS) / (r + RBIAS_OHM) )
#define ARRAY_ELEMENTS(a) ( sizeof(a)/sizeof(a[0]) )
typedef struct
{
uint16_t adc;
int16_t temp;
} PtcArrayType;
static const PtcArrayType ptcArray[] =
{
{ PTC_ADC(6508), -40 },
{ PTC_ADC(6717), -35 },
{ PTC_ADC(6937), -30 },
{ PTC_ADC(7165), -25 },
{ PTC_ADC(7404), -20 },
{ PTC_ADC(7651), -15 },
{ PTC_ADC(7906), -10 },
{ PTC_ADC(8170), -5 },
{ PTC_ADC(8442), 0 },
{ PTC_ADC(8722), 5 },
{ PTC_ADC(9010), 10 },
{ PTC_ADC(9305), 15 },
{ PTC_ADC(9607), 20 },
{ PTC_ADC(9916), 25 },
{ PTC_ADC(10233), 30 },
{ PTC_ADC(10557), 35 },
{ PTC_ADC(10888), 40 },
{ PTC_ADC(11226), 45 },
{ PTC_ADC(11571), 50 },
{ PTC_ADC(11923), 55 },
{ PTC_ADC(12283), 60 },
{ PTC_ADC(12651), 65 },
{ PTC_ADC(13026), 70 },
{ PTC_ADC(13409), 75 },
{ PTC_ADC(13800), 80 },
{ PTC_ADC(14200), 85 },
{ PTC_ADC(14609), 90 },
{ PTC_ADC(15026), 95 },
{ PTC_ADC(15453), 100 },
{ PTC_ADC(15890), 105 },
{ PTC_ADC(16338), 110 },
{ PTC_ADC(16796), 115 },
{ PTC_ADC(17265), 120 },
{ PTC_ADC(17746), 125 }
};
static int16_t GetTemperatureFromAdc(uint16_t adc)
{
uint8_t i;
if(adc <= ptcArray[0].adc)
{
return ptcArray[0].temp;
}
for(i=1; i < ARRAY_ELEMENTS(ptcArray); i++)
{
if(adc < ptcArray[i].adc)
{
return ((ptcArray[i].temp - ptcArray[i-1].temp)*(adc - ptcArray[i-1].adc)) / (ptcArray[i].adc - ptcArray[i-1].adc) + ptcArray[i-1].temp;
}
}
return ptcArray[i-1].temp;
}
I for one would be interested in seeing an example.
linearVal = ( Kslope / ( nonLinearVal + Kyintercept ) ) - Koffset
You can check the curves in the Excel graphs to see if you are getting the interpolation you like. This saves on table reading/parsing, but may or may not give you the linearity you are looking for. The file was written for a Sharp IR detector, but can be used for any non-linear to linear conversion.
This particular program is for the thermistor that is in the Apogee environmental oxygen probe, and has a nominal resistance of 10kOhms at 25 degC. It is in series with a 25.5 kOhm precision resistor (included in the probe body). In the data logger (OWL2pe) the thermistor is connected to a 4.096 V reference, and the bottom of the 25.5 k resistor is connected to ground, and the junction goes to an input of a TLC2543 ADC. Voltage increases as temperature increases. The DATA in the table is the milliVolts is expected at -40, -35, ... and so on up to +85 degC. The program locates the present voltage in the table and then interpolates back to temperature. The program is set up to run in one slot of a BS2pe. If it runs in slot 0 (of any stamp), or if it is called with a cross-slot index of zero, it runs a test routine that shows current readings on the DEBUG screen. If it is called from some other slot, a slot index of 1 causes it to return Celsius (in units of 0.1 degree) in a word variable using an ADC channel stored in eeprom. If the calling slot index is 2, it uses a value passed in with the call to specify the ADC channel number (This project had to read several probes).
The spreadsheet generates the DATA statements for the program. The DATA in this example is entered at 5 degree Celsius increments. At the top are cells to enter the fixed resistance (25.5k in this case), and the reference voltage (4.096 V in this case). The spreadsheet is also useful for exploratory purposes to check for how much error you can expect, against a Steinhart-Hart or polynomial fit.
Depending on the way things are set up, isn't this the kind of thing for which it would make sense to simply have the BS2 report the raw data to PLX-DAQ, and have Excel do all the conversion? If I'm understanding it, that's what Zoot is suggesting. It must be easier to do that than to have the Stamp do the math.
My method (a space saver) uses the formula given to linearize a non-linear value (say from an IR ranger, thermistor, RCTIME value on a light sensor, etc). The thing is you need the three constants to plug in -- the Excel file lets you pre-calculate desired output value ranges, actual input readings, to generate the constants. These constants are used in the formula in Stamp Pbasic code.
For example, on two of my IR rangers, I took very accurate ADC readings at 10cm intervals, plugged the values into the Excel file, and calculated my three constants.
The table-based interpolation actually does the same thing, in a way, by going through a table of pre-defined data points, finding the closest match, then interpolating between those two points to get the closest value. Again, Dr. Allen's Excel file is used to *create* the original table of "ready-to-go" data points; those data statements are copied to the Stamp application to be read by the main program.
But, yes, if the data is being sent to a PC, doing it there would be fast.) : 1/7/2010 9:52:38 PM GMT
-Mike
Edit: Oops, sorry! It looks like the Excel solution does the job.
In the end it may not matter -- I might argue that it is always beneficial to linearize sensitive input values in code, so that the app can *always* be tuned regardless of what sensors, circuitry or methods are used to acquire the input at the
It might be possible to implement the Steinhart-Hart equations on the Stamp, but I wouldn't want to tackle it. It involves the natural log and the natural log cubed of the resistance of the thermistor, added up with the specific coefficients to give the inverse of temperature. Not an easy thing to do on the Stamp. And PBASIC still has to calculate the resistance given a voltage divider, so there is more chance for cumulative error. I'd much rather do it as a direct table lookup with interpolation, and let Excel do the heavy lifting in advance.
Makes perfect sense! thanks! i was thinking of using a thermistor in a cabinet enclosure A/C controller using just rctime, acurracy would only need to be within 2-5 deg f. i think im gonna use an a/d converter now after some thought, probably a dual channel because i want to add a humidity sensor also.
Consequently you can also place a "virtual" 10K resistor in parallel with the Thermistor and mathematically calculate it in software.
R = 1 / [noparse][[/noparse] (1/Rt) + (1/10K) ]
Where:
Rt is the Thermistor resistance value
R is the linear resistance value
In the Attached Image, Rt is the 'top' resistance graph, while R is the 'bottom' resistance graph with a 10K resistor in parallel to the Thermistor.)) : 1/9/2010 7:30:18 AM GMT
Tracy,
Thanks for the spreadsheet you provided. I've been taking a look at it but was wondering what would be needed if I wanted to modify this to an different thermistor.
I have the was looking at using the the 2904 epcos (link) which is 10k Ohms @ 25 Deg C. I wonder if I just changed the given data points, source voltage and the resister in series with the Thermistor if I would be good to use your excel sheet. Or is there something else I would need to consider like insert the B 25 / 100 or anything like that?
thanks in advance
-J
-Phil
You should be able to use that spreadsheet. Alter the column of resistance to match your thermistor found in the table under type 2904. E.g, next to 25 degrees Celsius enter 10000 Ohms, next to 30 °C enter 7942 Ω and so on. And enter your reference resistor and excitation voltage. The program creates the DATA table that is used by the Stamp program to interpolate temperature in units of 0.1 °C. The program is set up to start at -40 °C.
That thermistor has tolerance of +/-5% or +/-10%. If you measure your thermistor at 25°C and find that it is 9500Ω instead of 10000Ω, then put 9500 next to 25 Celsius in the spreadsheet, and adjust all the resistance values in the spreadsheet by the same proportion. Note that 500Ω amounts to about 1 °C error if you don't bother to correct that. The table method can also be used in conjunction with one of the linearization techniques.
The B parameter is the basis of a math approximation to the thermistor curve. The B formula for a Excel would be:
Resistance =10000*EXP(4300*(1/(degC+273) - 1/(25+273)))
That gives resistance vs temperature, but remember that it is in fact an approximation (worse than the Steinhart-Hart formula) and the values you read from the table will be a better fit to the true performance. For fun you can enter the formula and compare with the values from the table.
For NTC it will require modification of array or function.
It depends if it is NTC or PTC and if it is connected to + or - .
The simplest way is to reverse array order with entries to keep ascending trend of .adc value ( then .temp values will go descending )
Second solution is to connect NTC to + and modify PTC_ADC(r) macro.
PTC_ADC(r) - macro assuming that ADC reference voltage is the for R + PTC circuit supply.
Preprocessor will calculate correct values of ADC for given resistance value from PTC datasheet.
As an aside, this is an 8 year old thread. This isnt to say your code contribution is unlikely to help someone, someday, but the immediate need has passed. Come join us in a current thread!
Once you have the equation for it, just plug in your read value. | http://forums.parallax.com/discussion/comment/1490828/ | CC-MAIN-2021-04 | refinedweb | 1,641 | 61.46 |
Hello, I am new to Java. I got in to it a couple months ago and I've been looking for tutorials but only help me with basic stuff and I keep learning the same things over and over again. I would be able to make some simple programs from what I remember but none of it makes sense to me and why it's there.. such as this 'Hello world' program :
********************************************
public class MyFirstJavaProgram{
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args){
System.out.println("Hello World"); // prints Hello World
}
}
*********************************************
I would know how to make that simple program but I don't know what it means that I'm typing. Such as, what's the point of the brackets at the beginning and end? What does **public static void main(String []args)** do? Those are the only things in that programming that doesn't make any sense to me.. Please somebody explain. Thanks very much >:)
(by the way, I'm 13. Not expecting complicated stuff anytime soon. Looking for a bright future from programming) | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/29500-new-java-what-does-mean-printingthethread.html | CC-MAIN-2014-41 | refinedweb | 188 | 83.15 |
This formula uses the formula for the field due to a thin shell solenoid, integrated over a range of radii to obtain the magnetic field at any point on the axis of a finite.
$B = \frac {\mu_o i n}{2 (r_2 - r_1)} \left [ x_2 \ln \left ( \frac {\sqrt{r_2^2 + x_2^2} + r_2}{\sqrt{r_1^2 + x_2^2} + r_1} \right ) - x_1 \ln \left ( \frac {\sqrt{r_2^2 + x_1^2} + r_2}{\sqrt{r_1^2 + x_1^2} + r_1} \right ) \right ]$
B is the magnetic field, in teslas, at any point on the axis of the solenoid. The direction of the field is parallel to the solenoid axis.
$\mathbf \mu_o$ is the permeability constant (1.26x10-6 Hm-1)
i is the current in the wire, in amperes.
n is the number of turns of wire per unit length in the solenoid.
r1 is the inner radius of the solenoid, in meters.
r1 is the inner radius of the solenoid, in meters.
r2 is the outer radius of the solenoid, in meters.
x1 and x2 are the distances, on axis, from the ends of the solenoid to the magnetic field measurement point, in meters.
The field can be expressed in a form that separates the unit system, power and winding configuration from the unitless geometry of the coil. This introduces the "G Factor":
$B = \mu_o G \sqrt \frac {P \lambda} {r_1 \rho}$
where G is the unitless geometry factor defined as:
$G = \sqrt{\frac {1}{8 \pi \beta (\alpha^2 - 1)}} \left [ (\gamma + \beta) \ln \left ( \frac {\alpha + \sqrt{\alpha^2 + (\gamma + \beta)^2}}{1 + \sqrt{1 + (\gamma + \beta)^2}} \right ) - (\gamma - \beta) \ln \left ( \frac {\alpha + \sqrt{\alpha^2 + (\gamma - \beta)^2}}{1 + \sqrt{1 + (\gamma - \beta)^2}} \right ) \right ]$
where,
$\alpha = \frac {r_2}{r_1}$, $\beta = \frac l {2 r_1}$ and $\gamma = \frac {x_1 + x_2}{2 r_1}$
P is the total power consumed by the coil, in watts.
$\lambda$ is equal to the total conductor cross section area divided by the total coil cross section area, which ranges from 0.6 to 0.8 in typical coils.
$\rho$ is the conductor resistivity, in units of ohms-length. The length units must match those of r1.
When the magnetic field measurement point is at the center of the solenoid:
$B = \frac {\mu_o i N}{2(r_2 - r_1)} \ln \left ( \frac {\sqrt{r_2^2 + (\frac l 2)^2} + r_2}{\sqrt{r_1^2 + (\frac l 2)^2} + r_1} \right )$
or...
$B = \frac {\mu_o j l}{2} \ln \left ( \frac {\sqrt{r_2^2 + (\frac l 2)^2} + r_2}{\sqrt{r_1^2 + (\frac l 2)^2} + r_1} \right )$
j is the bulk current density in the coil cross section, in amperes per square meter.
l is the length of the solenoid, in meters.
N is the total number of turns of wire in the coil.
The unitless geometry factor G is simply:
$G = \sqrt \frac {\beta} {2 \pi (\alpha^2 - 1)} \ln \left ( \frac {\alpha + \sqrt{\alpha^2 + \beta^2}} {1 + \sqrt{1 + \beta^2}} \right )$
Note that G is maximum when $\alpha=3$ and $\beta=2$. A coil built with a given inner diameter and input power will deliver the highest central field strength when these conditions are met.
%matplotlib inline from scipy.special import ellipk, ellipe, ellipkm1 from numpy import pi, sqrt, linspace, log from pylab import plot, xlabel, ylabel, suptitle, legend, show uo = 4E-7*pi # Permeability constant - units of H/m # Compute G Factor from unitless parameters def GFactorUnitless(a, b, g=0.0): # alpha, beta - omit gamma for central gpb2 = (g+b)*(g+b) gmb2 = (g-b)*(g-b) if not g == 0.0: sq = sqrt(1/(8*pi*b*(a*a-1))) t1 = (g+b)*log((a+sqrt(a*a+gpb2))/(1+sqrt(1+gpb2))) t2 = (g-b)*log((a+sqrt(a*a+gmb2))/(1+sqrt(1+gmb2))) B = sq*(t1-t2) else: sq = sqrt(b/2/pi/(a*a-1)) B = sq*log((a+sqrt(a*a+b*b))/(1+sqrt(1+b*b))) return B # Compute G Factor from all dimensions def GFactor(r1, r2, l, x1=0.0, x2=0.0): # omit x1, x2 to compute central field a = r2/r1 b = l/2/r1 g = (x1+x2)/2/r1 return GFactorUnitless(a, b, g) # Compute B field on axis from unitless dimensions def BFieldUnitless(power, packing, resistivity, r1, a, b, g=0.0): return uo*GFactorUnitless(a, b, g)*sqrt(power*packing/r1/resistivity) # Compute B field on axis from actual dimensions (x is measurement point - center if none) def BField(power, packing, resistivity, r1, r2, length, x=0.0): a = r2/r1 b = length/2/r1 g = x/r1 return BFieldUnitless(power, packing, resistivity, r1, a, b, g)
Now let's apply the
B function to a typical coil. We'll assume copper (at resistivity of 1.68x10-8 ohm-m) conductors at a packing density of 0.75, inner radius of 1.25 cm, power of 100 W and with supposedly optimal $\alpha$ and $\beta$ of 3 and 2, respectively:
resistivity = 1.68E-8 # ohm-meter r1 = 0.0125 # meter packing = 0.75 power = 100.0 # watts B = BFieldUnitless(power, packing, resistivity, r1, 3, 2) print("B Field: {:.3} T".format(B))
B Field: 0.107 T
Now try any combination of factors (assuming packing of 0.75 and standard copper conductors) to compute the field:
from ipywidgets import interactive from IPython.display import display def B(power, r1, r2, length, x): return "{:.3} T".format(BField(power, 0.75, resistivity, r1, r2, length, x)) v = interactive(B, power=(0.0, 200.0, 1), r1 = (0.01, 0.1, 0.001), r2 = (0.02, 0.5, 0.001), length = (0.01, 2, 0.01), x = (0.0, 4, 0.01)) display(v)
'7.68e-05 T'
For a given inner radius, power and winding configuration, the field strength is directly proportional to G. Therefore, we can test the assertion that G is maximum when $\alpha$ is 3 and $\beta$ is 2 by constructing a map of G as a function of $\alpha$ and $\beta$:
from pylab import pcolor, colorbar, meshgrid, contour from numpy import arange a = arange(1.1, 6.0, 0.1) b = arange(0.1, 4.0, 0.1) A, B = meshgrid(a,b) G = GFactorUnitless(A, B) contour(A, B, G, 30) colorbar() xlabel("Unitless parameter, Alpha") ylabel("Unitless parameter, Beta") suptitle("Electromagnet 'G Factor'") show() print("G Factor at A=3, B=2: {:.3}".format(GFactorUnitless(3,2))) print("G Factor at A=3, B=1.9: {:.3}".format(GFactorUnitless(3,1.9)))
G Factor at A=3, B=2: 0.142 G Factor at A=3, B=1.9: 0.143
Although it is apparent that the maximum G Factor occurs near the $\alpha=3$, $\beta=2$ point, it is not exactly so:
from scipy.optimize import minimize def GMin(AB): return -GFactorUnitless(AB[0], AB[1]) res = minimize(GMin, [3, 2]) print("G Factor is maximum at Alpha = {:.4}, Beta = {:.4}".format(*res.x))
G Factor is maximum at Alpha = 3.096, Beta = 1.862 | https://nbviewer.jupyter.org/github/tiggerntatie/emagnet-py/blob/master/solenoids/solenoid.html | CC-MAIN-2019-09 | refinedweb | 1,176 | 64.51 |
On Thu, Oct 07, 2010 at 01:01:16PM +0300, Martin Storsj?: > > [...] > > I tried doing the split, and the attached diff isn't something that could > be used as such, but it's an initial proof of concept. > > Since the common code paths calls out to the use case specific code, > splitting of the code is a bit trickier and needs function prototypes for > the use case specific parts, and needs to enclose the callers within small > #ifdefs within the functions, like this for example: > > - if (s->iformat) > + if (s->iformat) { > +#if CONFIG_RTSP_DEMUXER > err = rtsp_setup_input_streams(s, reply); > - else > +#endif > + } else { > +#if CONFIG_RTSP_MUXER > err = rtsp_setup_output_streams(s, host); > +#endif > + } Would be cleaner like this: if (CONFIG_RTSP_DEMUXER && s->iformat) err = rtsp_setup_input_streams(s, reply); else if (CONFIG_RTSP_MUXER) err = rtsp_setup_output_streams(s, host); > This is in the common RTSP connection code, while the setup_*_streams > functions are in either the demuxer or in the muxer. We already have some > similar code in rtsp_fetch_packet, like this one: > > switch(rt->lower_transport) { > default: > #if CONFIG_RTSP_DEMUXER > case RTSP_LOWER_TRANSPORT_TCP: > len = tcp_read_packet(s, &rtsp_st, rt->recvbuf, RECVBUF_SIZE); > break; > #endif > case RTSP_LOWER_TRANSPORT_UDP: > > The attached patch splits the current code from rtsp.c and rtspenc.c into > the following files: > > rtsp.c - handling of RTSP protocol things, shared by the RTSP muxer > and demuxer > rtspenc.c - RTSP muxer only > rtspcommon.c - common code shared by all three components, such as opening > of the transport contexts, cleanup of transport contexts, > common parsing helpers such as get_word(), get_word_sep(), > get_word_until_chars() > rtprecv.c - functions for receiving RTP packets, shared by the RTSP and > SDP demuxers > rtspdec.c - RTSP demuxer only > sdpdec.c - SDP demuxer only" ? Aurel | http://ffmpeg.org/pipermail/ffmpeg-devel/2010-October/099471.html | CC-MAIN-2016-44 | refinedweb | 268 | 50.87 |
Created on 2011-07-11.22:45:33 by pekka.klarck, last changed 2011-10-30.13:15:19 by amak.
When using sax.parse, attributes passed to startElement are broken if an element has an attribute with name 'id'. This can be demonstrated with the attached script. Below is the output I get with Jython 2.5.2:
$ jython saxbug.py
attr : idx
value : 1
attr : (u'i', u'd')
value :
Traceback (most recent call last):
File "saxbug.py", line 11, in <module>
sax.parse(StringIO('<tag id="1"/>'), Handler())
File "/home/peke/Prog/jython2.5.2/Lib/xml/sax/__init__.py", line 34, in parse
parser.parse(source)
File "/home/peke/Prog/jython2.5.2/Lib/xml/sax/drivers2/drv_javasax.py", line 146, in parse
self._parser.parse(JyInputSourceWrapper(source))
File "/home/peke/Prog/jython2.5.2/Lib/xml/sax/drivers2/drv_javasax.py", line 187, in startElement
self._cont_handler.startElement(qname, self._attrs)
File "saxbug.py", line 8, in startElement
print 'value :', attrs.values()[0]
File "/home/peke/Prog/jython2.5.2/Lib/xml/sax/drivers2/drv_javasax.py", line 311, in values
return map(self.getValue, self.getNames())
File "/home/peke/Prog/jython2.5.2/Lib/xml/sax/drivers2/drv_javasax.py", line 266, in getValue
value = self._attrs.getValue(_makeJavaNsTuple(name))
TypeError: getValue(): 1st arg can't be coerced to String, int
I just encountered this bug as well. It actually affects all attribute names that are exactly 2 characters long.
The dirty workaround is to use -
attrs._attrs.getValue('id')
instead to get values, and remember that that will throw a KeyError exception if it does not exist.
The bug is rather simple - in Lib/xml/sax/drivers2/drv_javasax.py, in the function _fixTuple, on line 241, it checks the length of the first argument, nsTuple, and if it is a length of 2, assumes it is a tuple of (namespace, localName) and proceeds to unpack it.
Unfortunately it doesn't check the type, and other methods (specifically _makeJavaNsTuple and _makePythonNsTuple) pass in a string instead, therefore a string of length 2 is assumed to be a (namespace, localName) tuple as a string is a sequence type as well.
The solution is to enact a type check that specifically excludes strings, e.g.
def _fixTuple(nsTuple, frm, to):
# NOTE the isinstance check that excludes strings
if not isinstance(nsTuple, str) and len(nsTuple) == 2:
nsUri, localName = nsTuple
if nsUri == frm:
nsUri = to
return (nsUri, localName)
return nsTuple
The alternative is to check for a tuple, but that then you would exclude other sequence and sequence-like types.
I hope this is enough information to perform the one-liner fix; I can provide a diff file if necessary.
Fix checked in at | http://bugs.jython.org/issue1768 | CC-MAIN-2017-17 | refinedweb | 454 | 52.76 |
autodie::Scope::GuardStack - Hook stack for managing scopes via %^H
use autodie::Scope::GuardStack; my $stack = autodie::Scope::GuardStack->new $^H{'my-key'} = $stack; $stack->push_hook(sub {});
This class is a stack of hooks to be called in the right order as scopes go away. The stack is only useful when inserted into
%^H and will pop hooks as their "scope" is popped. This is useful for uninstalling or reinstalling subs in a namespace as a pragma goes out of scope.
Due to how
%^H works, this class is only useful during the compilation phase of a perl module and relies on the internals of how perl handles references in
%^H. This module is not a part of autodie's public API.
my $stack = autodie::Scope::GuardStack->new;
Creates a new
autodie::Scope::GuardStack. The stack is initially empty and must be inserted into
%^H by the creator.
$stack->push_hook(sub {});
Add a sub to the stack. The sub will be called once the current compile-time "scope" is left. Multiple hooks can be added per scope
This module is free software. You may distribute it under the same terms as Perl itself. | http://search.cpan.org/~pjf/autodie-2.24/lib/autodie/Scope/GuardStack.pm | CC-MAIN-2016-26 | refinedweb | 193 | 72.46 |
The schema used in
graph.sqlite is defined by
schema.sql. Since Callgraph is new, the schema is fairly simple and is expected to evolve. If you have suggestions or use cases that require changes, please file a bug. (In particular, there are several pending improvements mentioned below.)
The schema contains the following tables:
node. This represents a function, and contains the following fields:
id INTEGER PRIMARY KEY, a unique identifier for the node
name TEXT, the fully-qualified function or method name, including return type and parameters. See below.
isPtr INTEGER, 1 if the function call (in this case, the callee) is a function pointer, 0 otherwise.
isVirtual INTEGER, 1 if the function call is a virtual method, 0 otherwise.
loc TEXT, the fully-resolved source file containing the declaration or definition of the function. See below.
UNIQUE (name, loc) ON CONFLICT IGNORE
The fully-qualified method name includes the return value, namespaces, class name, method or function name, and parameter types. For instance, the code
namespace ns { class cs { int method(float, double); }; };
would result in a
nameof
int ns::cs::method(float,double). For nonstatic methods,
thisis excluded from the parameter list, though we may want to denote nonstatic methods with a separate field. The global namespace is indicated by a leading
::. (Types are currently not fully-qualified.) The
locrefers to the source file in which the declaration or definition appeared. For classes, the declaration context will always be available, and this location will refer to the file containing the declaration (for instance,
foo.h). For function calls, this location may refer to the declaration or definition, and cannot presently be used in concert with
nameas a reliably unique identifier. (This could potentially be solved by implementing linker-style name resolution rules in Callgraph.) For function pointers, it is impossible to determine a location, and
locwill be the empty string. (You should guard on this case using
isPtr.) For compiler built-ins,
locwill be
<built-in>. Since symlinks are prevalent in the Mozilla build process, the path in
locis always fully-resolved; that is, it will be an absolute path which is guaranteed to have a one-to-one mapping with a particular file in the source or object tree. (In the case of generated files, such as from xpidlgen, it will point into the object tree. Note also that one can override gcc's notion of the current source file using the
#filedirective; in the likely case where this file doesn't exist, the resulting
locwill not be fully-resolved. Caveat emptor. Thankfully, this practice is uncommon.)
The
(name, loc)pair is intended to be a unique identifier for a given function or method call. (Though this currently breaks down for functions and function pointers.) In the future, we may include a
mangledNamefield in the table, which would allow more consistency with linker rules regarding function name resolution and uniqueness. We may also add a field indicating whether the function definition has been seen (which would distinguish, say, calls into library functions from functions who simply don't call anyone else).
edge. This represents a call between functions, and contains the following fields:
caller INTEGER REFERENCES node, the
idof a
noderepresenting the caller function.
callee INTEGER REFERENCES node, likewise for the callee.
PRIMARY KEY(caller, callee) ON CONFLICT IGNORE
The primary key is currently unique on caller and callee, meaning that if the caller calls the callee multiple times, only one edge will exist in the table. We may change this if there are cases where the number of calls is relevant.
implementors. This table provides information about the inheritance chain of C++ classes, specifically which virtual interface methods are overridden or implemented by which classes.
implementor TEXT, the fully-qualified class name of the class which implements the method.
interface TEXT, the fully-qualified class name of the class which declares the method to be pure virtual. See below.
method TEXT, the method name (not including return type or arguments).
loc TEXT, the fully-resolved source file containing the declaration of the interface class.
id INTEGER PRIMARY KEY, a unique identifier for the entry.
UNIQUE (implementor, interface, method, loc) ON CONFLICT IGNORE
An interface is considered a class which declares the method in question to be virtual (either pure or non-pure), while an implementor overrides it with a declaration that is non-pure. (Whether the implementor actually defines the function is not considered.) For instance, consider the code
class iFoo { public: virtual void method1(float) = 0; virtual void method2(float) = 0; }; class iBar : public iFoo { public: virtual void method1(float) = 0; virtual void method2(float); }; class Bar : public iBar { public: virtual void method1(float); virtual void method2(float); };
The class
iBarwould be considered an implementor of
method2, while class
Barwould be an implementor of both
method1and
method2. For implementor
iBar,
iFoo::method2would be considered an interface method. For implementor
Bar, both methods on
iFooand
iBarwould be listed as interface methods. Uniqueness is determined by implementor, interface, method, and loc. (Note that the parameter list to the virtual method is also required to determine uniqueness, and will be added.) | https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Callgraph/Schema_Reference | CC-MAIN-2017-30 | refinedweb | 854 | 53.81 |
An Introduction to the Java Logging API
Pages: 1, 2
When we created our Logger, we specified the name
of our class
(logging.example4.HelloWorld) as the
Logger name, but didn't specify anything else. Each
Logger has its own Level, used to screen out
any record which doesn't have a high enough level (this is part of what
makes logging inexpensive at runtime when not turned up). By default,
the threshold is set
to Level.INFO. This means that records we log through
our Logger will only get printed if they are at least
has high as Level.INFO.
Logger
logging.example4.HelloWorld
Level
Level.INFO
To get finer-grained records to
be logged, we need to set the logging level for our class to
something more verbose. But that isn't quite enough, because when a
record is logged to a Logger, that Logger
actually delegates the output of the record to a subclass of the
Handler class, like this:
Handler
And:
Level.FINE
package logging.example5;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.LogManager;
/**
* A simple Java Hello World program, in the tradition of
* Kernighan and Ritchie.
*/
public class HelloWorld {
private static Logger theLogger =
Logger.getLogger(HelloWorld.class.getName());
public static void main( String[] args ) {
// );
}
// We also have to set our logger to log finer-grained
// messages
theLogger.setLevel(Level.FINE);
HelloWorld hello =
new HelloWorld("Hello world!");
hello.sayHello();
}
private String theMessage;
public HelloWorld(String message) {
theMessage = message;
}
public void sayHello() {
theLogger.fine("Hello logging!");
System.err.println(theMessage);
}
}
This will produce output on the console like this:
FINE; 992190676635ms; 5213611;# 1; logging.example5.HelloWorld; sayHello; Hello logging!
Hello world!
This might lead you to wonder what handler is actually producing this
output. After all, our test program didn't create any handler. The answer
lies in the tree structure of loggers. we see. Note that this
forwarding behavior be controlled via the
setUseParentHandlers(boolean) method in the
Logger class.
LogRecord
Handler(s)
Filter
ConsoleHandler
setUseParentHandlers(boolean)
There is much more that can be done with the provided handlers. It is
also possible to create your own custom handlers. Space won't allow us
to discuss them in more detail here; see the references below for
places to learn more about handlers.
The LogManager is, in many ways, the central class of the
logging library. It provides much of the control over what gets
logged and where it gets logged, including control over
initialization of logging. In terms of logging levels, it allows us
to set different logging levels for different "areas" of the
program. To understand this, we need to think of our program as
being broken down into different areas based on the package prefix
of the classes involved. So our program areas are organized in a
tree structure, like this (only some of the tree is shown, to
simplify the discussion):
LogManager
But.setLevel(String name, Level level)
LogManager.getLogManager().setLevel("logging", Level.FINE);
This would make every Logger with the package prefix of
"logging" have a level of Level.FINE, unless that particular
Logger already had a Level explicitly set:
logging
We would still need to turn up the levels of the root handlers as
before, but would not have to set the individual loggers one at a
time.
In addition to providing this ability to control log levels
en masse, the LogManager provides:
There is one thing to keep in mind when setting the level for a package and
everything below it:.
null
While space won't permit us to go into a description of
Filters, the logging API provides them as a means to
further control what records get logged. So, if you are using
logging and find that you want use more than the log
Level of the record when deciding whether to log it,
Filters are there. They can be attached to both
Loggers and Handlers, and can be thought
of like this:
In this situation, the record must pass the Logger's
level check, the Logger's Filter, the
Handler's level check, and the Handler's
Filter before it would actually be sent to the outside
world. This allows things to start out simple (with no filters) and
become more sophisticated as needed. In situations where you're
trying to get at just the right information without altering the
behavior of the program too much (and without overwhelming someone
reading the output), the ability to create more sophisticated
filters can be key to learning what needs to be known.
This article demonstrates using the fully qualified class name of
your class as the name of your Logger. This is the
approach recommended by the Logging API documentation. However, the
LogManager and Loggers really only care
that the names used are made up of strings separated by period
characters. So if you need to organize the logging of your software
in some other manner, you can -- as long as your scheme fits
into a tree hierarchy.
Loggers
In addition, it is possible to use anonymous loggers, which don't
have a name or affect any other loggers.
These are good for applets running in a
browser, as well as other high-security situations. They can also be
used to keep classes relatively self-contained. However, when using
anonymous loggers, you don't get many of the benefits of a named
logger (the ability to have records forwarded to the global
handlers, the ability to alter logging levels of groups of loggers
by their common prefix, etc.).
The Logging API seems to strike a good balance between simplicity
and power. As the examples above show, it is possible to get
started with the Logging API very quickly, yet it is designed to be
extensible so that it can be tailored to your needs. This article
has really just scratched the surface of what can be done with
logging. In particular, topics that we didn't discuss, which the API
allows for, include:
SocketHandler
For more information about logging, the best sources of information
are the JDK 1.4 documentation on logging and JSR 47. There is also
Javadoc for the java.util.logging package, which
provides details about the classes.
java.util.logging
Brian R. Gilstrap
is an experienced Java developer, Mac user, Tai Chi practitioner. | http://www.onjava.com/pub/a/onjava/2002/06/19/log.html?page=2 | CC-MAIN-2015-06 | refinedweb | 1,060 | 54.12 |
David Nuescheler on JCR and REST
InfoQ: Can you give us a quick overview of JCR/JSR-170?
David Nuescheler (DN): I think this boils down to explaining the feature set of a content repository.
Generally in a one sentence description I always describe a Content Repository as the “best of both worlds” from “relational databases” and “filesystems” plus all the good stuff that we always missed and had to build into our own applications.
This includes things like transactions, scalability, query on the DB side, being really good with very large files, streaming, access controls and hierarchies on the filesystem side and things like versioning, fulltext search and most importantly a “data first” approach which neither of the two support.
JCR is a Java API describing all these features.
InfoQ: How do you feel about JCR adoption in the market today?
DN: When it comes to adoption I always think that it is important to think of both sides, the implementors and the users of an API.
First of all I am excited that I am aware of over a dozen of repositories that are compliant with JCR v1.0 (aka JSR-170) only two years after the initial release of JCR. As expected some repositories are compliant through third party connectors but the majority already shipping JCR compliance out of the box. This includes the major repository vendors as well as young and innovative new repositories. Another very encouraging fact is that there are already four open source implementations of JCR which I think shows the great support of the specification from an implementation side of things and is definitely comparable with the most widely adopted specs in the Java space.
Much more importantly, the adoption amongst users of the API has been fantastic, and in my view this is the much more important part of the adoption. In many ways this is what really fuels the repository consolidation that everybody was hoping for. Every single new content management initiative can nowadays rely on a standard based ready to use content repository instead of building yet another “their own” content repository from scratch. This means for applications developers that they can rely on features like access control, full fledged versioning or full text search right from the start of their project. We see a great deal of new applications built on top of Apache Jackrabbit on a weekly basis as the most accessible content repository implementation and I think you cannot overstate the fact that for each and every of those applications people would probably have built a new proprietary content repository on top of something like hibernate in the absence of JCR.
InfoQ: How does your employer, Day, monetize this?
DN: When we started the specification process of JCR back in 2001 we did that because there was no industry standard and we considered ourselves primarily an application vendor that had to come up with their own proprietary content repository. Which we did. But it was very unsatisfactory for our customers to have all their most valuable content locked into a proprietary silo, so we wanted to make sure that we offer an open platform for all our content applications (which include Web Content Management, Digital Asset Management and Social Collaboration software) that is based on a standard. Given the absence of such a standard we owed it to our customers to do something about that.
So generally, being open and standards compliant is a key selling feature of our content applications.
In the meantime through our involvement in JCR and our open source activities around Apache Jackrabbit we started to sell our highly scalable and enterprise ready commercial fully compliant content repository called CRX.
CRX is a very surprising product in many different ways, for example it allows the entire fine-grained content in the repository to be persisted in simple old fashioned tar files in a transactional way that in our loadtests outperforms the traditional RDBMS-backed persistence layers by factors.
InfoQ: There has recently been a lot of buzz about Atom and AtomPub, and even some claims that they obsolete JCR. What are your thoughts on this?
DN: Frankly, I still have a hard time understanding why people think that protocols and API’s are competing. I remember back in the days when people compared WebDAV and JCR (which btw I think is a much more appropriate comparison from a feature set perspective) we drew the comparison to HTTP and the Servlet API. You wouldn’t see anybody saying things like “Now I have HTTP, why do I need the Servlet API”. Programmers use API’s not protocols.
Now comparing Atom and AtomPub to JCR is a bit of joke from a functional perspective. While Atom and AtomPub offer reading and writing JCR certainly goes beyond that in many different ways (Search, Locking, Versioning, Access Control, …). From a technology perspective I think Atom and AtomPub are a more light-weight (probably needed) replacement for the WebDAV collections handling, but that’s about it.
InfoQ: But isn’t the common problem with API standards that they tie the solution to a particular programming language (in this case, Java)? Wouldn’t I want my content to be accesible from other platforms, too?
DN: I don’t think of it as a problem. It is a feature. Protocols as mentioned allow access in a “platform neutral way”, unfortunately that's entirely pointless for the developer, since they will have to come up with their own API’s wrapping the parser. As mentioned the servlet API is tied into a java platform and makes http accessible to Java programmers. Now saying that the Servlet API has the “common problem” that it is tied to a particular language would not be a fair statement. In the world of content repositories (opposed to the example with HTTP and Servlets) we lack a widely adopted content repository protocol. WebDAV and Atom are probably the best candidates but I am confident that there will be more widely adopted specs on a protocol level in the future. Personally, I don’t see how the lack of a good, well adopted protocol spec could be considered a flaw in the API spec.
I would like to mention that JCR has been ported to a large variety of language environment including .NET, PHP, Perl and amongst other also JavaScript.
InfoQ: Given that REST inventor Roy Fielding is Day’s chief scientist, what’s your opinion on REST?
DN: I consider myself a “child of the web”, in the sense that I started to use the web fairly early on and learned to understand and love the architecture of web before I learned traditional application development techniques. So I never ran into the usual problem that app developers have, trying to make the web fit into their stateful application development paradigms. I came from the other side and had to make apps fit into my web-world.
So when I first met Roy I realized that we already built our applications according to a restful architecture without even knowing about or formally referring to REST. It just felt like the only natural architectural style at the time and of course it still feels that way. So count me in as a “full on RESTafarian” or whatever the nickname of the season is, or let’s just say I am a “web guy” in contrast to an “app guy”. Of course the formalization of the REST architectural style in Roy’s dissertation in 2001 is a very important asset for the web community and I am amazed how long it took the general public to appreciate its value.
InfoQ: How, if at all, does JCR relate to REST?
DN: In my mind JCR and REST are related in various different ways. First of all they both are information centric and support hierarchical addressing of the information. So the JCR paths map very intuitively to URLs just like paths in filesystems. One of the first exercises we went through was to map all the JCR API calls to WebDAV to offer a complete remoting of the JCR API in a RESTFul manner.
This was not only important to be sure that we are aligned with WebDAV from a feature perspective but also manifest that we did not violate any of the constraints imposed by the REST architecture style.
For static Filesystem based websites there is a natural mapping from a URL to the Filesystem. If I look at the URL, I pretty much know what’s going on. This is due to the natural and intuitive mapping of the hierarchic filesystem path to the URL. A content repository brings back a store that supports a hierarchy and allows for this very intuitive mapping.
In my mind JCR is the ideal information store for web centric, REST oriented applications.
InfoQ: Can you give us a little background on Apache Sling? Why does the world need another Java web framework?
DN: Playing devil’s advocate I might assume the position that I have not seen a java “web” framework yet.
I would argue that the world is full of Java “application” frameworks that sort of expose their services to the “web”, but really I would not call them “web frameworks”.
Generally I think there is a void for a framework that does not consider the stateless architecture of the web as a necessary evil or does pay more attention to the URL than “it’s just a string”. Sling really is not another “Java Application Framework” and does not try to be one. Sling is the first “Web Framework” that I have seen that not just respects the fundamental principals and constraints of the web but actually “feels good” about them.
We like the web the way it is and don’t try to circumvent then basic principals as soon as possible by injecting sessions or continuations. One of them biggest differentiators that I have seen comparing Sling to existing application frameworks is its relationship to the URL. In legacy application frameworks like J2EE or struts, the URL was mainly used to address your scripts or controllers (.jsp, .php, .do) and pass in parameters to execute certain operations. So.
While this allows for a more resource oriented or even a RESTful architecture, it does by no means lead people to do the right thing. It just gives them more choices and in most cases choices or let’s say the lack of a good default behavior is bad.
Sling is very different, since Sling is backed by a content repository it exposes a hierarchic namespace that is mapped very naturally to the hierarchic namespace exposed through a URL, while this still gives people full control over the URL it also gives them very clear guidance one how to expose their content nodes as resources in a well designed manner. Sling puts the “web” back into “web framework”.
InfoQ: I have to admit I haven’t seen the argument about non-hierarchical URLs being unRESTful before. How well does Sling do in terms of other REST aspects, such as hypermedia?
DN: The hierarchical aspects of the URL has nothing to do with RESTful-ness per se. Back in the days when websites were still file system based it was reasonably apparent that the URL /news/newsitem.html was an “newsitem.html” file sitting somewhere on a filesystem in a “news” folder. adding an archive folder or another news item was very straight-forward because the mapping of the hierarchical URL was very transparent. While of course the web servers give you all sorts of possibilities to do crazy mappings, the simple case is solved in a very simple and intuitive way. Sling adopts that very same concept where by default that path of a URL is mapped to a node in the content repository. Of course sling allows you to take partial or full control of the URL, but I think it is of great importance to provide a simple, intuitive and very powerful default mapping that is proven and scalable and adheres to best “web” practices. Just providing the ability to a developer to go in an map out their own URL space is not useful at all since this will be the first thing that I will have to come up with when I start a project and every single developer will come up with a completely different mapping.
Generally, I would argue that Sling does very well on encouraging all four constraints that make up the REST architecture. This may be the most important differentiator, while other application frameworks may allow you to build RESTful applications if you really spend the time, Sling is “built” to develop RESTful repository backed web apps right out of the box and makes it hard to ignore the REST architecture.
InfoQ: Thanks for your time!
David Nuescheler is responsible for the technology strategy and ongoing product development at Day Software in Switzerland. He is the specification lead on JSR 170 and JSR 283, Content Repository for Java Technology API. His group has been working for over 4 years to standardize the content repository market. David is also a committer on the Apache Jackrabbit Project and a member of the Apache Software Foundation.
Zope
by
Neil Ellis
Probably a good subject to have a talk on, have you already done that on InfoQ?.
That's why despite being a true blue Java developer I will always remain a lifelong Zope fan, those guys understood RESTful architecture (and ideas we still aren't stealing yet in the Java world) while we were still writing noddy JSP applications :-) To this day I regard Zope as containing some of the most elegant concrete programming concepts invented.
All the best
Neil
Brilliant - Would like to see more..
by
Ambuj Tiwari
The study on “application framework” in Java and “web framework” in Java is also interesting.
Cheers,
Ambuj | http://www.infoq.com/articles/nuescheler-jcr-rest/ | CC-MAIN-2014-52 | refinedweb | 2,330 | 57.1 |
NAME
roar_vs_volume_get, roar_vs_volume_mono, roar_vs_volume_stereo - Get or set volume for audio stream
SYNOPSIS
#include <roaraudio.h> int roar_vs_volume_get (roar_vs_t * vss, float * l, float * r, int * error); int roar_vs_volume_mono (roar_vs_t * vss, float c, int * error); int roar_vs_volume_stereo (roar_vs_t * vss, float l, float r, int * error);
DESCRIPTION
Those functions are used to get or set volume for the given stream. roar_vs_volume_get() gets the volume for the given stream in stereo form as a left and a right component (L/R). If you need the mono volume just devide the sum of both by two. See examples below. roar_vs_volume_mono() sets the mono volume for the stream. Balance information is not kept. roar_vs_volume_stereo() sets the stereo volume for the stream as left and rigth component (L/R).
PARAMETERS
vss The VS object for wich volume is get or set. l, r, c The volume for left, right or center (mono) channel. Value is a float in range zero to one. Zero means this channel is fully muted. One means the channel is passed without altering the amplitude. Small numerical errors are detected and corrected. Bigger errors will result in a out of range error. Note that to mute the stream you MUST NOT use volume setting but roar_vs_mute(3). 0. On error, -1 is returned.
EXAMPLES
Getting mono volume: float l, r, c; int err; if ( roar_vs_volume_get(vss, &l, &r, &err) == -1 ) { /* handle error */ } c = (l + r)/2.;
SEE ALSO
roarvs(7), libroar(7), RoarAudio(7). | http://manpages.ubuntu.com/manpages/precise/man3/roar_vs_volume_mono.3.html | CC-MAIN-2016-30 | refinedweb | 241 | 76.01 |
TypeScript and React are an increasingly common pair. Learn how to get up and running with TypeScript for your next React project.
TypeScript is more and more becoming a common choice to make when starting a new React project. It’s already being used on some high profile projects, such as MobX, Apollo Client, and even VS Code itself, which has amazing TypeScript support. That makes sense since both TypeScript and VS Code are made by Microsoft! Luckily it’s very easy to use now on a new create-react-app, Gatsby, or Next.js project.
In this article we’ll see how to get up and running with TS on the aforementioned projects, as well as dive in to some of the most common scenarios you’ll run into when using TS for your React project. All three examples can be found here.
With version 2.1.0 and above, create-react-app provides TypeScript integration almost right out of the box. After generating a new app (create-react-app app-name), you’ll need to add a few libraries which will enable TypeScript to work and will also provide the types used by React, ReactDOM, and Jest.
create-react-app app-name
yarn add typescript @types/node @types/react @types/react-dom @types/jest
You can now rename your component files ending in js or jsx to the TypeScript extension tsx. Upon starting your app, the first time it detects a tsx file it will automatically generate you a tsconfig.json file, which is used to configure all aspects of TypeScript.
js
jsx
tsx
tsconfig.json
We’ll cover what this config file is a little further down, so don’t worry about the specifics now. The tsconfig.json file that is generated by create-react-app looks like:
{
"compilerOptions": {
"target": "es5",
"allowJs": true,
"skipLibCheck": false,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve"
},
"include": ["src"]
}
Funny enough, the App.js file, renamed to App.tsx works without requiring a single change. Because we don’t have any user defined variables, functions, or even props that are being received, no more information needs to be provided for TypeScript to work on this component.
App.js
App.tsx
With your Next.js app already set up, add the @zeit/next-typescript package with the command yarn add @zeit/next-typescript.
yarn add @zeit/next-typescript
After that, we can create a next.config.js file in the root of our project which is primarily responsible for modifying aspects of the build process of Next.js, specifically modifying the webpack configuration. Note that this file can’t have a .ts extension and doesn’t run through babel itself, so you can only use language features found in your node environment.
next.config.js
.ts
const withTypeScript = require("@zeit/next-typescript");
module.exports = withTypeScript();
Create a .babelrc file (in root of project):
.babelrc
{
"presets": ["next/babel", "@zeit/next-typescript/babel"]
}
Create a tsconfig.json file (in root of project):
{
"compilerOptions": {
"allowJs": true,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"jsx": "preserve",
"lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"preserveConstEnums": true,
"removeComments": false,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"target": "esnext"
}
}
I would recommend then adding yarn add @types/react @types/react-dom @types/next as well so that our app has access to the types provided by those libraries. Now we can rename our index.js page to be index.tsx. We’re now ready to continue app development using TypeScript.
yarn add @types/react @types/react-dom @types/next
index.js
index.tsx
We’ll start by creating a new Gatsby app gatsby new app-name. After that finishes, it’s time to install a plugin which handles TypeScript for you: yarn add gatsby-plugin-typescript
gatsby new app-name
yarn add gatsby-plugin-typescript
Although it doesn’t seem to be required, let’s create a tsconfig.json. We’ll take it from the Gatsby TypeScript example.
{
"include": ["./src/**/*"],
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"lib": ["dom", "es2017"],
"jsx": "react",
"strict": true,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": true,
"skipLibCheck": true
}
}
Now we can rename src/pages/index.js to be index.tsx, and we have TypeScript working on our Gatsby project… or at least we almost do! Because a default Gatsby project comes with a few other components such as Header, Image, and Layout, these need to be converted into .tsx files as well, which leads to a few other issues around how to deal with props in TS, or other external packages which might not come with TS support out of the box.
src/pages/index.js
Header
Image
Layout
.tsx
We’ll quickly cover a few settings in the tsconfig.json file that are especially important and then dive into how we can move beyond the TS setup by actually using and defining types on our React projects.
We’ve already seen the tsconfig.json file a few times, but what is it? As the name suggests, it allows you to configure TypeScript compiler options. Here are the default TypeScript compiler options which will be used if no tsconfig.json file is provided.
The jsx setting when being used on a React app whose target is the web will have one of two values: You’ll either choose react if this is the final stage of compilation, meaning it will be in charge of converting JSX into JS, or preserve if you want babel to do the conversion of JSX into JS.
react
preserve
strict is typically best set to true (even though its default is false), especially on new projects, to help enforce best TS practices and use.
strict
true
Most other options are up to you and I typically wouldn’t stray too far from the recommended setup that comes defined by the framework you’re using unless you have a real reason to.
If you have never worked with TS before, I would first recommend doing their TypeScript in 5 minutes tutorial. Let’s look at some of the basic types, without diving into too much detail.
let aNumber: number = 5;
let aString: string = "Hello";
let aBool: boolean = true;
// We can say that ages will be an array of `number` values, by adding `[]` to the end of our number type.
let ages: number[] = [1, 2, 3];
You’ll notice that it basically looks like JavaScript, but after the variable name there is : sometype, where sometype is one of the available types provided by TS or, as you’ll see below, created ourselves.
: sometype
sometype
With functions, we’re tasked with providing the types of both the argument(s), and also the type that will be returned from a function.
// receives 2 number arguments, returns a number
let add = (num1: number, num2: number): number => num1 + num2;
let response = add(5, 6);
console.log(response);
The beauty of TypeScript is that often it can figure out the type of a variable on its own. In VS Code if you hover over the response variable it will display let response: number, because it knows the value will be a number based on the declaration of the add function, which returns a number.
response
let response: number
add
In JS it’s common to receive JSON responses or to work with objects that have a certain shape to them. Interfaces are the tool for the job here, allowing us to define what the data looks like:
interface Person {
name: string;
age?: number;
}
const register = (person: Person) => {
console.log(`${person.name} has been registered`);
};
register({ name: "Marian" });
register({ name: "Leigh", age: 76 });
Here we are saying that a Person can have two properties: name, which is a string, and optionally age, which, when present, is a number. The ?: dictates that this property may not be present on a Person. When you hover over the age property you’ll see VS Code tell you that it is (property) Person.age?: number | undefined. Here the number | undefined part lets us know that it is either a number or it will be undefined due to the fact that it may not be present.
name
age
?:
(property) Person.age?: number | undefined
number | undefined
number
undefined
React comes with a number of predefined types that represent all of the functions, components, etc. that are declared by React. To have access to these types, we’ll want to add two packages to our project: yarn add @types/react @types/react-dom.
yarn add @types/react @types/react-dom
Let’s say we have the JSX:
<div>
<a href="">Google</a>
<p href="">Google</p>
</div>
It’s a little hard to catch the mistake right off the bat, but the p tag has an href prop that is invalid in HTML. Here’s where TS can help us a ton! In VS Code, the whole href="" prop is underlined in red as invalid, and when I hover it I see:
p
href
href=""
[ts] Property 'href' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLParagraphElement>, HTMLParagraphElement>'. [2339]
If I hover over href on the a tag, I’ll see (JSX attribute) React.AnchorHTMLAttributes<HTMLAnchorElement>.href?: string | undefined. This means that href is an optional attribute on an anchor element (HTMLAnchorElement). Because it’s optional ?:, it can either be a string or undefined.
a
(JSX attribute) React.AnchorHTMLAttributes<HTMLAnchorElement>.href?: string | undefined
string
All of these type definitions come from the @types/react package, which is a massive type declaration file. For the anchor tag example above, its interface looks like the following, which declares a number of optional properties specific to this type of tag:
@types/react
interface AnchorHTMLAttributes<T> extends HTMLAttributes<T> {
download?: any;
href?: string;
hrefLang?: string;
media?: string;
rel?: string;
target?: string;
type?: string;
}
React’s PropTypes provided a runtime way to declare which props (and their types) would be received by a component. With TypeScript, these aren’t required any more as we can bake that right into our TS code and catch these issues as we’re typing the code rather than executing it.
From the default Gatsby build, we got a Header component that looks like this (I have removed the styles to make it smaller):
import React from "react";
import { Link } from "gatsby";
const Header = ({ siteTitle }) => (
<div>
<h1>
<Link to="/">{siteTitle}</Link>
</h1>
</div>
);
export default Header;
We can see that it receives a siteTitle, which looks to be a required string. Using TS we can declare using an interface what props it receives. Let’s also make it a bit fancier by adding functionality for it to display a subTitle if provided.
siteTitle
subTitle
interface Props {
siteTitle: string
subTitle?: string
}
const Header = ({ siteTitle, subTitle }: Props) => (
<div>
<h1>
<Link to="/">{siteTitle}</Link>
</h1>
{subTitle && <h2>{subTitle}</h2>}
</div>
)
We’ve declared a Props interface that states we will receive a siteTitle as a string, and optionally receive a subTitle, which, when defined, will be a string. We can then in our component know to check for it with {subTitle && <h2>{subTitle}</h2>}, based on the fact that it won’t always be there.
Props
{subTitle && <h2>{subTitle}</h2>}
Let’s look at the same example above but with a class-based component. The main difference here is that we tell the component which props it will be receiving at the end of the class declaration: React.Component<Props>.
React.Component<Props>
interface Props {
siteTitle: string
subTitle?: string
}
export default class Header extends React.Component<Props> {
render() {
const { siteTitle, subTitle } = this.props
return (
<div>
<h1>
<Link to="/">{siteTitle}</Link>
</h1>
{subTitle && <h2>{subTitle}</h2>}
</div>
)
}
}
We have two more things left to do to fix up our default Gatsby install. The first is that, if you look at the Layout component, you’ll see an error on this line: import Helmet from 'react-helmet'. Thankfully it is easy to fix, because react-helmet provides type declarations by adding yarn add @types/react-helmet to our package. One down, one more to go!
import Helmet from 'react-helmet'
react-helmet
yarn add @types/react-helmet
The last issue is what to make of the line const Layout = ({ children }) =>. What type will children be? Children, if you aren’t fully sure, are when you have a React component that receives “child” component(s) to render inside itself. For example:
const Layout = ({ children }) =>
children
<div>
<p>Beautiful paragraph</p>
</div>
Here we have the <p> component being passed as a child to the <div> component. OK, back to typing! The type of a child in React is ReactNode, which you can import from the react project.
<p>
<div>
ReactNode
// Import ReactNode
import React, { ReactNode } from "react";
// ... other packages
// Define Props interface
interface Props {
children: ReactNode;
}
// Provide our Layout functional component the typing it needs (Props)
const Layout = ({ children }: Props) => <div>{children}</div>;
export default Layout;
As a bonus, you can now remove the PropTypes code which comes with Gatsby by default, as we’re now doing our own type checking by way of using TypeScript.
Now let’s take a look at some specific types involved in Forms, Refs, and Events. The Component below declares a form which has an onSubmit event that should alert the name entered into the input field, accessed using the nameRef as declared at the top of the Component. I’ll add comments inline to explain what is going on, as that was a bit of a mouthful!
onSubmit
nameRef
import React from "react";
export default class NameForm extends React.Component {
// Declare a new Ref which will be a RefObject of type HTMLInputElement
nameRef: React.RefObject<HTMLInputElement> = React.createRef();
// The onSubmit event provides us with an event argument
// The event will be a FormEvent of type HTMLFormElement
handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
// this.nameRef begins as null (until it is assigned as a ref to the input)
// Because current begins as null, the type looks like `HTMLInputElement | null`
// We must specifically check to ensure that this.nameRef has a current property
if (this.nameRef.current) {
alert(this.nameRef.current.value);
}
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" ref={this.nameRef} />
<button>Submit</button>
</form>
);
}
}
In this article we explored the world of TypeScript in React. We saw how three of the major frameworks (or starter files) in create-react-app, Gatsby, and Next.js all provide an easy way to use TypeScript within each project. We then took a quick look at tsconfig.json and explored some of the basics of TypeScript. Finally, we looked at some real-world examples of how to replace PropTypes with TypeScript’s type system, and how to handle a typical scenario with Refs and a Form Event. | https://www.telerik.com/blogs/typescript-and-react-bff | CC-MAIN-2020-50 | refinedweb | 2,454 | 53.31 |
With the uxtheme in Vista, the uxtheme new-world theme mechanism now supports menu themeing. We should use this on Vista to get a native look, because the menu look is now much more complex than a simple color.
(Note: this is only tangentally related to the trainwreck in bug 243078, because this is Vista-only; the MENU theme bits are not present in any earlier version of uxtheme.dll)
(Note#2: I already have a patch for this, I'm just working on fixing some issues with it before attaching it.)
Created attachment 241502 [details]
MENU theme reference PNG
Reference PNG for the menu theme bits. I used parts 1-6, even though many things only have only 2 or so parts, just to make sure there was nothing missing. These elements draw the "invalid" parts the same as the first part. The constants are defined in vsstyle.h in the Vista SDK; the first 6 are various _TMSCHEME constants that seem to draw bogus things.
Created attachment 241511 [details] [diff] [review]
patch for native menu theme (with bugs)
Patch; I think that the nsNativeThemeWin portion of this is pretty solid (note that the "MENU" theme stuff is not available under anything less than Vista, so we'll fall through into the same code paths we've always taken there).
The menu.css stuff needs a ton of work. The resulting menubar looks too fat, with too much padding up and down. Harder to fix is the handling of things like popup arrows and checkboxes and stuff -- we should probably just draw these using the native theme code, and I'll try to do that in a new version of the patch, but for now all the "-hover.png" versions of these icons have the lighter color baked in -- so they're a light gray or even white, which usually shows up against dark hover highlights on themes but looks wrong when Vista just draws the outline around the menu item.
We also need a bit more padding, and the menu background doesn't match the rest of Vista; we need more space for icons and we need the slight gutter to be drawn.
Note to self: Office 2007 doesn't follow the Vista menu theme at all, at least OneNote and Visio 2007 don't. The menus are white text on a dark gray background; the menus themselves on hover get an orange gradient. On dropdown, the hover look there is a translucent orange background with a solid 1px orange border. It doesn't even follow the Vista color scheme.
So, should there be a seperate win32 Vista nightly build?
no. hoping that the same build will work on all flavors of windows 32.
Thanks. I was thinking that it might mess up the program for people on non-Vista systems that are Win32.
*** Bug 333486 has been marked as a duplicate of this bug. ***
What's the status of this? Need a new patch? Not really blocking?
This is a nice to have, but it's not blocking.
Recommend this block bug 352420 (vista support tracking).
Created attachment 268130 [details] [diff] [review]
new patch (still with bugs)
Still have magic numbers in some places (see menuitem padding)
All formulas used in menu widget placement are my guesses and not based on documentation.
Menu separators are too tall (slightly).
Menu highlight text should be black, not white.
Menu icons do not appear in the correct place (this can be fixed like checkboxes/submenu arrows).
Context menus do not have a gutter (see IsTopLevelMenu).
Untested on XP, but works on Vista Aero/Vista Classic.
Created attachment 268257 [details] [diff] [review]
Fixed some issues, caused some others
Incompatible CSS changes were made to accommodate the following:
Menu separators are still too tall (can be fixed in CSS, just didn't get to it).
Menu highlight text is now appropriate in all themes.
Menu icons placement is ok now.
Context menus now have gutters (and proper boarders)
Untested on XP. Looks good on Vista Aero, too wide on Vista Classic (probably same with XP classic).
Adding beltzner for ui review
Created attachment 268737 [details]
Shows checkboxes/radio menuitems, menu separators and more
Created attachment 268738 [details]
Bookmark/history icons in the menu
I did not find a reference app for this. Icon placement is not yet ideal (a few pixels off I think)
Created attachment 268739 [details]
Menu bar w/mouse hover
Created attachment 268740 [details]
Old menu look
Created attachment 268741 [details]
Old bookmarks/history look
Created attachment 268742 [details]
Old menubar hover
This caused a regression on combo boxes and the location bar; I have a temporary fix, but I need to clean it up
Created attachment 268986 [details] [diff] [review]
Contains temporary CSS hacks for combo boxes/location bar
All popups which want the menu look should be menupopup elements so that popup elements can be free of native theming for use with other widgets.
Comment on attachment 268986 [details] [diff] [review]
Contains temporary CSS hacks for combo boxes/location bar
some tabs crept in:
>+popupset > popup
>+{
>+ -moz-appearance: menupopup;
>+ int width = leftMargin + checkboxSize.cx + rightMargin;
>+ int height = topMargin + checkboxSize.cy + bottomMargin;
>+ int width = max(itemSize.cx, checkboxSize.cx + gutterSize.cx);
>+ int height = max(itemSize.cy, checkboxSize.cy);
>+ case NS_THEME_CHECKMENUITEM:
>+ case NS_THEME_RADIOMENUITEM:
>+ if(part == MENU_POPUPITEM)
>+ {
>+ if(aWidgetType != NS_THEME_MENUITEM)
>+ drawThemeBG(theme, hdc, MENU_POPUPITEM, state, &widgetRect, &clipRect);
>+ }
>+ SIZE borderSize;
>+ getThemePartSize(theme, hdc, MENU_POPUPBORDERS, 0, NULL, TS_TRUE, &borderSize);
>+ RECT sepRect = widgetRect;
>+ sepRect.left += gutterSize.cx;
>+ //sepRect.bottom += 2;
>+ if(!theme)
>+ return PR_FALSE;
>+ if(aWidgetType == NS_THEME_MENUITEM && IsTopLevelMenu(aFrame))
>+ return NS_OK; // Don't worry about it for top level menus
>+ SIZE gutterSize(GetGutterSize(theme, hdc));
>+ aResult->width = max(aResult->width, gutterSize.cx);
Created attachment 268997 [details] [diff] [review]
Same as previous patch sans tabs
Created attachment 269898 [details] [diff] [review]
Fixes regressions in combo boxes and location bar
This should be in a state where it can be checked in.
Comment on attachment 269898 [details] [diff] [review]
Fixes regressions in combo boxes and location bar
This does not look good on WinXP.
Rob: while you're at making this look good on XP, maybe you could include as much as possible from the patch to bug 337771 so that I don't have to start over if you get this in before I do.
And while I'm at it:
+ if(IsThemed())
Missing space between if and ( [if is not a function].
+ margin-left: 30px !important;
This doesn't look RTL safe. Why not use -moz-margin-start?
+.menu-iconic-left {
+ width: 22px;
+ margin-right: 5px;
+}
Can't you set those dimensions from the native theme code?
+menulist > menupopup
+{
+ -moz-appearance: none !important;
+}
This appears in two different files. Is that intended?
...
- color: HighlightText;
+ color: -moz-menuhovertext;
Please change the background-color from Highlight to -moz-menuhover as well, for consistency.
+popup[type="autocomplete"]
+{
+ -moz-appearance: none !important;
+}
Why not use popupset > popup:not([type="autocomplete"]) instead right above? The less !important the better for themers.
+static PRBool IsTopLevelMenu(nsIFrame *aFrame)
+{
+ PRBool isTopLevel;
Please set isTopLevel explicitly to PR_FALSE or PR_TRUE to indicate what the default/fallback value is.
+ else if(aWidgetType == NS_THEME_MENUITEM || aWidgetType == NS_THEME_CHECKMENUITEM || aWidgetType == NS_THEME_RADIOMENUITEM)
No space after if (happens several times in this method).
(In reply to comment #26)
> Rob: while you're at making this look good on XP, maybe you could include as
> much as possible from the patch to bug 337771 so that I don't have to start
> over if you get this in before I do.
I think we have slightly incompatible implementations.
>
> +.menu-iconic-left {
> + width: 22px;
> + margin-right: 5px;
> +}
>
> Can't you set those dimensions from the native theme code?
Only if they have a -moz-appearance which currently mine don't. I intend to fix this.
>
> +menulist > menupopup
> +{
> + -moz-appearance: none !important;
> +}
>
> This appears in two different files. Is that intended?
Nope, good catch.
>
> ...
Here's where we should agree on the semantics of the different moz-appearance styles. Ideally, my patch should not change any CSS except for 'tagging' elements with -moz-appearance styles, so those margin and size adjustments will have to go. I can set them from C++ if they have a moz-appearance, but I do not want to use the menucheck and menuradio appearances there; I need those two appearances on the actual images used so that (and this is a change I made) the image does not draw itself and I can then draw the native vista checkbox/radio images (which are fetched from the theme itself). I use the same trick for the submenu arrows.
I see that your patch removes the images from the checks/radios/submenuarrows so that will eliminate a great deal on my end (which is fine; less code is better).
>
> - color: HighlightText;
> + color: -moz-menuhovertext;
>
> Please change the background-color from Highlight to -moz-menuhover as well,
> for consistency.
Sure. The actual colors are fine though so I won't change the implementation.
>
> +popup[type="autocomplete"]
> +{
> + -moz-appearance: none !important;
> +}
>
> Why not use popupset > popup:not([type="autocomplete"]) instead right above?
> The less !important the better for themers.
This is my first time doing any real CSS; I like your solution better though.
(In reply to comment #27)
> I think we have slightly incompatible implementations.
I've moved mine closer and already included some bits of your last patch. Can you now adapt your patch around mine or do you need anything else?
Note that we seem to prefer menucheckbox instead of menucheck (consistency) and menuarrow instead of submenuarrow for -moz-appearance (see bug 337771 comment #6).
Created attachment 272892 [details] [diff] [review]
Proposed solution
CSS changes consist of margin->padding and -moz-appearance tagging
Theme looks great on Vista, XP and classic. Untested on Win2k, but the code should behave like classic. Also fixes combo box and dropdown regressions on vista caused by bug 337771. The vista theme should be pixel perfect, and the changes to xp are close enough that I can't tell. Classic is classic.
).
(In reply to comment #30)
> ).
>
I take it you are going to fix the combo boxes too? It would be nice to have a list of all the known regressions and their bug numbers as some of them are quite significant.
(In reply to comment #31)
> I take it you are going to fix the combo boxes too?
Well, now that I know about the issue... For further issues, you should be able to monitor the dependencies of bug 243078. There shouldn't be that many regressions in the first place, though.
Created attachment 273605 [details] [diff] [review]
Fixes menubar height
Created attachment 273607 [details]
Toolbar comparison
In order to get the menubar height to be right in vista, the height in xp was shrunk as well
Created attachment 273608 [details] [diff] [review]
Forgot the throbber changes
Comment on attachment 273608 [details] [diff] [review]
Forgot the throbber changes
>+#define MENU_POPUPITEM 14
>+
>+#define MPI_NORMAL 1
>+#define MPI_HOT 2
>+#define MPI_DISABLED 3
>+#define MPI_DISABLEDHOT 4
>+
>+// From tmschema.h in the Vista SDK
>+#define TMT_TEXTCOLOR 3803
For all of these, if we ever include the right include file, this will break... so we need to
either wrap these in #ifndef TMT_TEXTCOLOR #define TMT_TEXTCOLOR 3803 #endif type things, or call
these MOZ_TMT_TEXTCOLOR. I'd do the former. (for the MPI_* block it should be ok to just #ifndef MPI_NORMAL for the whole block)
Then again, there's a whole pile of these later on in the file, so maybe we shouldn't bother.
>- case eColor_highlighttext:
>+ case eColor__moz_menubarhovertext:OSVERSIONINFOEX:
I think the stuff after the : is bogus?
Looks fine otherwise.
Checking in widget/src/windows/nsLookAndFeel.cpp;
new revision: 1.63; previous revision: 1.62
Checking in widget/src/windows/nsNativeThemeWin.cpp;
new revision: 3.88; previous revision: 3.87
Checking in widget/src/windows/nsNativeThemeWin.h;
new revision: 3.27; previous revision: 3.26
Checking in widget/src/windows/nsWindow.cpp;
new revision: 3.701; previous revision: 3.700
Checking in widget/src/windows/nsWindow.h;
new revision: 3.237; previous revision: 3.236
Checking in layout/style/nsCSSKeywordList.h;
new revision: 3.94; previous revision: 3.93
Checking in layout/style/nsCSSProps.cpp;
new revision: 3.154; previous revision: 3.153
Checking in gfx/public/nsThemeConstants.h;
new revision: 1.21; previous revision: 1.20
Checking in toolkit/themes/winstripe/global/menu.css;
new revision: 1.13; previous revision: 1.12
Checking in toolkit/themes/winstripe/global/popup.css;
new revision: 1.13; previous revision: 1.12
Checking in browser/themes/winstripe/browser/browser.css;
new revision: 1.71; previous revision: 1.70
+/* auto complete popups don't render well as vista menus */
+popupset > popup:not([type="autocomplete"])
+{
Why does this check for popupset? The popupset element is not a required element.
(In reply to comment #38)
> +/* auto complete popups don't render well as vista menus */
> +popupset > popup:not([type="autocomplete"])
> +{
>
> Why does this check for popupset? The popupset element is not a required
> element.
This was fixed before being checked in; I noticed that the context menu in about:config was incorrect.
(In reply to comment #27)
>Ideally, my patch should not change any CSS except for 'tagging' elements with
>-moz-appearance styles, so those margin and size adjustments will have to go.
So, in theory, could I write a theme that emulated Windows 2000 in CSS, and then apply -moz-apperance styles, and it would automatically work in Luna/Vista?
>I need those two appearances on the actual images used so that the image does
>not draw itself and I can then draw the native vista checkbox/radio images
I always thought that -moz-appearance was able to suppress CSS painting.
(From update of attachment 273608 [details] [diff] [review])
>+ nsIMenuFrame *menuFrame(nsnull);
Personally I don't like C++-style initialisers for pointers.
I missed the changes in browser/themes/winstripe/browser/browser.css but the tree is closed right now, so I cannot check them in. Rob - remind me tomorrow?
actually, it looks like I did get that file - nevermind me...
Created attachment 277136 [details] [diff] [review]
Fixing small regression
I don't know what caused the regression, but this seems to fix it.
Schrep marked this wanted for the 1.8 branch, but at this point I'm guessing we wouldn't really want to take it given upcoming FF3 will have the fix and the downside of potential regressions. Not to mention the need to steal resources from FF3 to get this in. | https://bugzilla.mozilla.org/show_bug.cgi?id=355789 | CC-MAIN-2017-09 | refinedweb | 2,414 | 65.83 |
Siphash alternatives and similar libraries
Based on the "Cryptography" category.
Alternatively, view SipHash alternatives based on common mentions on social networks and blogs.
CryptoSwift9.8 7.8 L4 Siphash VS CryptoSwiftCryptoSwift is a growing collection of standard and secure cryptographic algorithms implemented in Swift
RNCryptor9.2 1.0 Siphash VS RNCryptorCCCryptor (AES encryption) wrappers for iOS and Mac in Swift. -- For ObjC, see RNCryptor/RNCryptor-objc
SwiftShield8.5 1.7 Siphash VS SwiftShield🔒 Swift Obfuscator that protects iOS apps against reverse engineering attacks.
Themis8.0 6.9 L3 Siphash VS ThemisEasy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.
Swift-Sodium6.2 2.1 L5 Siphash VS Swift-SodiumSafe and easy to use crypto for iOS and macOS
IDZSwiftCommonCrypto5.6 2.3 L4 Siphash VS IDZSwiftCommonCryptoA wrapper for Apple's Common Crypto library written in Swift.
BlueCryptor4.4 2.6 L2 Siphash VS BlueCryptorSwift cross-platform crypto library using CommonCrypto/libcrypto
JOSESwift4.1 3.0 Siphash VS JOSESwiftA framework for the JOSE standards JWS, JWE, and JWK written in Swift.
BlueRSA3.9 0.0 Siphash VS BlueRSARSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).
SwiftSSL3.8 0.0 L5 Siphash VS SwiftSSLAn Elegant crypto toolkit in Swift.
AES256CBC3.4 5.0 L4 Siphash VS AES256CBCMost convenient AES256-CBC encryption for Swift 2
OpenSSL2.3 0.0 L4 Siphash VS OpenSSLSwift OpenSSL for OS X and Linux
SCrypto1.6 0.0 L5 Siphash VS SCryptoElegant Swift interface to access the CommonCrypto routines
SweetHMAC1.2 0.0 L5 Siphash VS SweetHMACA tiny and easy to use Swift class to encrypt strings using HMAC algorithms.
Keys1.2 0.0 L4 Siphash VS KeysUncomplicated cryptography frameworks base on CommonCrypto
Appwrite - The Open Source Firebase alternative introduces iOS support
* Code Quality Rankings and insights are calculated and provided by Lumnify.
They vary from L1 to L5 with "L5" being the highest.
Do you think we are missing an alternative of Siphash or a related project?
README
SipHash
SipHash is a pure Swift implementation of the SipHash hashing algorithm designed by
Jean-Philippe Aumasson and Daniel J. Bernstein in 2012:
SipHash is a family of pseudorandom functions (a.k.a. keyed hash functions) optimized for speed on short messages.
Target applications include network traffic authentication and defense against hash-flooding DoS attacks.
SipHash is secure, fast, and simple (for real):
- SipHash is simpler and faster than previous cryptographic algorithms (e.g. MACs based on universal hashing)
- SipHash is competitive in performance with insecure non-cryptographic algorithms (e.g. MurmurHash)
-- 131002.net
SipHash has a variety of flavors; this package implements the one called SipHash-2-4.
Note that the Swift Standard Library already includes an implementation of SipHash-2-4 and SipHash-1-3; however, the APIs are currently private and not available for use outside of stdlib. This package provides an independent implementation that's available for use in third-party code.
The current release of SipHash requires Swift 4.
Sample Code
import SipHash // `SipHashable` is like `Hashable`, but simpler. struct Book: SipHashable { let title: String let pageCount: Int // You need to implement this method instead of `hashValue`. func appendHashes(to hasher: inout SipHasher) { // Simply append the fields you want to include in the hash. hasher.append(title) hasher.append(pageCount) } static func ==(left: Book, right: Book) -> Bool { return left.title == right.title && left.pageCount == right.pageCount } } // You can now use Books in sets or as dictionary keys. let book = Book(title: "The Colour of Magic", pageCount: 206) let books: Set<Book> = [book] // If you prefer to do so, you may also create & use hashers directly. var hasher = SipHasher() hasher.add(book) hasher.add(42) // Finalizing the hasher extracts the hash value and invalidates it. let hash = hasher.finalize()
Why Would I Use SipHash?
Unless you're targeting an ancient Swift release (<4.2), you shouldn't use
SipHash. This package is obsolete; it remains here for posterity and for compatibility only. Do not import it into new code.
What follows is the original documentation, contrasting
SipHashable to the original (now deprecated)
Hashable.hashValue protocol requirement.
Repeated for emphasis: Do not import this package into newly written code.
Writing a good implementation of
hashValue is hard, even if we just need to combine the values of a couple of fields.
We need to come up with a deterministic function that blends the field values well, producing a fixed-width
result without too many collisions on typical inputs. But how many collisions are "too many"? Do we even know what
our "typical inputs" look like? For me, the answer to both of these questions is usually "I have absolutely no idea",
and I bet you have the same problem.
Thus, verifying that our
hashValue implementations work well is an exercise in frustration.
We need to somehow check the properties of the hash function by looking at its behavior given various inputs.
It is easy enough to write tests for the requirement that equal values have equal
hashValues.
But verifying that the hash has few collisions requires making some assumptions on the
statistical properties of "typical" inputs -- and even if we'd be somehow confident enough to do that, writing the code
to do it is way too complicated.
Instead of rolling your own ad-hoc hash function, why not just use an algorithm designed specifically to blend data into a hash? Using a standardized algorithm means we don't need to worry about collision behavior any more: if the algorithm was designed well, we'll always have good results.
The SipHash algorithm is a particularly good choice for hashing. It implements a 64-bit cryptographic
message-authentication code (MAC) with a 256-bit internal state initialized from a 128-bit secret key that's (typically)
randomly generated for each execution of the binary.
SipHash is designed to protect against hash collision attacks, while remaining simple to use and fast.
It is already used by Perl, Python, Ruby, Rust, and even Swift itself -- which is why the documentation of
Hashable
explicitly warns that the value returned by
hashValue may be different across executions.
The standard library already implements SipHash, but the implementation is private. (It is technically available for use, but it is not formally part of the stdlib API, and it is subject to change/removal across even point releases.) I expect a refactored version of stdlib's SipHash will become available as public API in a future Swift release. But while we're waiting for that, this package provides an alternative implementation that is available today.
Is this code full of bugs?
Indubitably. Please report all bugs you find!
The package has 100% unit test coverage. Unfortunately this doesn't tell you much about its reliability in practice.
The test suite verifies that the package generates values that match the test vectors supplied by SipHash's original authors, which makes me reasonably confident that this package implements SipHash correctly. Obviously, your mileage may vary.
Reference docs
Nicely formatted reference docs are available courtesy of Jazzy.
Installation
CocoaPods
If you use CocoaPods, you can start using
SipHash by including it as a dependency in your
Podfile:
pod 'SipHash', '~> 1.2'
Carthage
For Carthage, add the following line to your
Cartfile:
github "attaswift/SipHash" ~> 1.2
Swift Package Manager
For Swift Package Manager, add
SipHash to the dependencies list inside your
Package.swift file:
import PackageDescription let package = Package( name: "MyPackage", dependencies: [ .Package(url: "", from: "1.2.1") ] )
Standalone Development
If you don't use a dependency manager, you need to clone this repo somewhere near your project, and add a reference to
SipHash.xcodeproj to your project's
xcworkspace. You can put the clone of SipHash wherever you like on disk, but it is a good idea to set it up as a submodule of your app's top-level Git repository.
To link your application binary with SipHash, just add
SipHash.framework from the SipHash project to the Embedded Binaries section of your app target's General page in Xcode. As long as the SipHash project file is referenced in your workspace, this framework will be listed in the "Choose items to add" sheet that opens when you click on the "+" button of your target's Embedded Binaries list.
There is no need to do any additional setup beyond adding the framework targets to Embedded Binaries.
*Note that all licence references and agreements mentioned in the Siphash README section above are relevant to that project's source code only. | https://swift.libhunt.com/siphash-alternatives | CC-MAIN-2022-40 | refinedweb | 1,438 | 56.15 |
15 December 2009 03:57 [Source: ICIS news]
SINGAPORE (ICIS news)--Japanese producer Idemitsu Kosan’s plans to shut its Tokuyama-based benzene, toluene, mixed xylenes (BTX) facility in mid September 2010 for a three week turnaround, a company official said on Tuesday.
The BTX unit located in Tokuyama can produce up to 230,000 tonnes/year of benzene, 130,000 tonnes/year of toluene and 50,000 tonnes/year of xylenes.
“The downstream 210,000 tonnes/year styrene monomer (SM) plant at the same location will be taken offline with the BTX unit, therefore it will not be necessary to buy benzene for SM production,” the official said, explaining that there would be no impact in the benzene supply for the captive usage in SM production.
The current operating rate of the SM plant was similar to that of the BTX facility at 80%, the official added.
Besides the aromatics facilities in Tokuyama, the 350,000 tonnes/year benzene unit in Chiba would not undergo maintenance next year, while the two SM lines at the same site, having a total capacity of 340,000 tonnes/year, were expected to be taken offline in end of March for 30 days.
Currently, the benzene and SM units at ?xml:namespace>
Other key benzene producers | http://www.icis.com/Articles/2009/12/15/9319173/idemitsu-kosan-to-shut-btx-unit-for-turnaround-in-sep.html | CC-MAIN-2013-48 | refinedweb | 213 | 51.52 |
Modules
Unlike most languages, a compilation unit in Silver is not tied to a file, but instead to a directory. A grammar (“module”) consists of the declarations and definitions found in all files with a “
.sv” suffix in the directory identifying the grammar.
For example,
a:module:name corresponds to
a/modules/name/*.sv in the first matching directory in the grammar search path given to the Silver compiler.
The Silver files in a grammar optionally specify their grammar name as the first declaration of the file. This practice is recommended, to avoid any potential problems with grammar search paths.
grammar a:module:name;
All declarations in a grammar have a name. This name is sequence of alpha-numeric characters or underscores beginning with a letter. This name is called the short name of the construct.
The full name of such a construct is formed by prepending the name of the grammar in which it is defined and an additional colon.
Example:
nonterminal Expr;
in the grammar
a:module:namewill have short name
Exprand full name
a:module:name:Expr.
Other grammars can be imported to every file in a grammar using the
imports statement:
imports another:module:name;
All symbols in that grammar are imported, including any symbols in grammars that grammars exported by the imported grammar.
See the later section on import modifiers .
Other grammars can be exported by a grammar using the
exports statement:
exports more:modules;
No modifiers are possible on an
exports statement. There is no equivalent
export statment.
Although not a part of Silver’s focus on extensibility, Silver supports a notion of conditional exports to facilitate modularity. This allows, for example, code specific to supporting a feature to be factored out, to allow for builds that do not include that feature. (This is unnecessary for extensions because they should forward to the host language. But modular specifications of a host language will likely take advantage of this feature, as they often cannot forward to the kernel “host” language.)
exports a:grammar:to:export with if:this:grammar;
This causes any grammar that imports the grammar this statement appear in to also import
if:this:grammar but ONLY if that grammar also imports
a:grammar:to:export. Either directly, by importing that grammar, or indirectly, by importing something that exports that grammar. (But importing something that merely imports that grammar will not cause this to trigger!)
Although this sounds as if it could cause problems, the feature is typically only used to resolve the “intersection problem,” where glue code is necessary to fit two features together, and the above semantics “just work.” (Again, a reminder that this is for modular specifications of the host language. True extensions require no glue code to compose, as forwarding takes care of the issue.)
For parsers, only those grammars included in the parser are used to trigger conditional exports. So if the grammar includes a trigger, it won’t necessarily trigger for the parser, unless that grammar is also included in the parser’s list of grammars.
The simple form of an
import statement is
import <grammar-name> ;
and has the effect of making all exported names from the named grammar visible in the current file. Note that both the full and short names are made visible in the importing grammar. Typically this includes all the nonterminals, terminals, attributes, and productions that are declared in the grammar.
Both
import and
imports support different ways to control the short names imported. Note that full names are always imported.
The import can be limited to including only a few short names with a
only clause. For example:
imports silver:langutil only ast; import core only Maybe, just, nothing;
The import can exclude some short names with a
hiding clause:
imports silver:langutil hiding pp, unparse; import core hiding implode;
The import can rename some short names using a
with clause. Note that full names are again left unaffected.
imports silver:langutil:pp with implode as ppimplode; import core with append as listappend, List as BuiltinList;
Renaming is also supported in conjuction with
only and
hiding:
import core only Maybe, orElse with orElse as maybeOrElse; import core hiding List with Maybe as BuiltinMaybe;
The short name assigned to each imported symbol can be qualified using the
as clause:
import silver:langutil:pp as pp;
This will result in all the the short names imported to be prefixed with
pp:. For example, the
implode symbol will now be
pp:implode. Of course, full names are unaffected, as always. | http://melt.cs.umn.edu/silver/concepts/modules/ | CC-MAIN-2021-10 | refinedweb | 756 | 52.8 |
In my homework, this question is asking me to make a function where Python should create dictionary of how many words that start with a certain letter in the long string is symmetrical. Symmetrical means the word starts with one letter and ends in the same letter. I do not need help with the algorithm for this. I definitely know I have it right, but however I just need to fix this Key error that I cannot figure out. I wrote
d[word[0]] += 1
{'d': 1, 'i': 3, 't': 1}
t = '''The sun did not shine
it was too wet to play
so we sat in the house
all that cold cold wet day
I sat there with Sally
we sat there we two
and I said how I wish
we had something to do'''
def symmetry(text):
from collections import defaultdict
d = {}
wordList = text.split()
for word in wordList:
if word[0] == word[-1]:
d[word[0]] += 1
print(d)
print(symmetry(t))
You're trying to increase the value of an entry which has yet to be made resulting in the
KeyError. You could use
get() for when there is no entry for a key yet; a default of
0 will be made (or any other value you choose). With this method, you would not need
defaultdict (
although very useful in certain cases).
def symmetry(text): d = {} wordList = text.split() for word in wordList: key = word[0] if key == word[-1]: d[key] = d.get(word[0], 0) + 1 print(d) print(symmetry(t))
Sample Output
{'I': 3, 'd': 1, 't': 1} | https://codedump.io/share/sXjiwm8QLfa3/1/key-error-in-dictionary-how-to-make-python-print-my-dictionary | CC-MAIN-2016-50 | refinedweb | 265 | 74.53 |
it is suppose to be a constructer call because I want to be able to use the entire array. but i have no idea how to make that call :S
it is suppose to be a constructer call because I want to be able to use the entire array. but i have no idea how to make that call :S
so i should make it like this: when i call my method?
UsernameArrayHolder username = new UsernameArrayHolder();
PasswordArrayHolder password = new PasswordArrayHolder();...
hi there :)
i have this class here:
public class UsernameArrayHolder {
public String[] UsernameArrayHolder() { //need identifier
...
don't i do that with
login.addActionListener(new login());
or is that just me that is wrong? because i can make it work if i take it out of the login method there then it works butn when i put...
and what does that mean?
Hello there :)
i have this simple login function where i compare what you write with what is in the array and if it is the same it will open a new window else nothing will happen but it doesn't seem...
i'm pretty sure i have done that
Hello i'm trying to call my login class from my main to run the program, but i don't know what i'm doing wrong :/
i get this error here:
Bank.java:24: error: constructor testlogin in class...
okay :)
but how do i remove the frame from the code you gave me bacause I tried to cut it own, but the code wont work after that?
Thanks for that :)
but i have other objects which i change into when i press different buttons, would it be better if placed all them in my main and then called my method on how to do diffrent...
Hello i have this little program here, what i would like to happen is when i press the login button it makes that dialog dissapear and open a new frame. I can make that happen but i can't make the...
i have my first method
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class login implements ActionListener {
i have this code here:
import java.io.*
public class ReadLastLine {
public static void main(String[] args) throws Exception {
FileInputStream in = new FileInputStream("test.txt");
ok thanks :) but what should i do it to run? make a new public class where i call this method?
public class textAreaTest {
public final JTextArea Center = new JTextArea(400, 500);
public...
hello there i have a problem where my Center is out of scope of do i make it in scope? :)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class...
Thanks for the reply now i have been trying to make sense of it with that but with no luck :s
I have a Jframe and in that i have a JTextArea and two buttons and when i press one button it displays...
Hello there :)
i'm trying to make a button where i push that and it display what is in the text file on the JTextArea, but i can't not make it to work when i press the button i have no idea how to...
when i tried what part?
it don't need to be secure at all ^^ that is not my focus point at the moment now i just want a login system and be able to open you personal file ^^
--- Update ---
But i have onemore quiestion...
Hello there :)
i have question i wonder if it possible.
I have a simple GUI where i have a log-in system, but i want to know if it possible to keep the log-in information in a txt file. and when...
Thanks alot :)
Hello
i'm trying to make a simple program and when i press a button i open up a new window but how do i make the old one disappear?
can't find out how i'm doing :S
here is my code for the...
ye okay :/ but isn't there a way to do it without arrays? :S
Hello there :)
i have some names in a txt file that i put in jGrasp, then i want to make the names in alphabetically order in a other txt file.
is there a command to do that? i have been looking...
Thanks but i got it to work late but if you wanted to know what i tired to create here is the code :)
import java.util.*;
public class dicegame11_0_gruppe_5 {
public static void main... | http://www.javaprogrammingforums.com/search.php?s=3bd1edb0d414090e652349c57c31db0f&searchid=203431 | CC-MAIN-2016-30 | refinedweb | 760 | 76.96 |
?.
rinceWind wrote:
It would be helpful if you could give an example of an application or a pattern where such a technique of distinct routines to handle different arglists would be useful.
Curiosly, I'm working with a similar issue, so here's an example. Let's say I want to create a 'people' object and save it in the database.
my $person = People
->new
->first_name( 'Tommy' )
->last_name( 'Atkins' )
->save;
my $id = $person->get_id;
[download]
The above works if all mutators return the object (typically $self) instead of true.
Now let's say that later on I want resurrect poor Tommy Atkins from his database internment. Assuming I have his $id, I can do this:
my $person = People->new( $id );
print $person->first_name, ' ', $person->last_name;
[download]
In the first case we call the constructor with no argument and set all of the data by hand. In the second case we call the constructor with an ID and get what we need. This is method overloading (though I realize we're talking about function overloading, I think the point is the same). In many OO languages, you would code entirely different methods. Let's consider Java (I'm leaving a lot of stuff out here):
class People {
// Java constructors have the same name as the class
// People person = new People();
// People person = new People(id);
public People() {
// initialize empty object
}
public People( int id ) {
// we can now access an object by id
}
}
[download]
The line public People( int id ) is called the method signature. By allowing the code to dispatch to different methods based upon different signatures, you simplify the logic tremendously. For Perl, without using an external module to fake it, you wind up with something like this:
sub new {
my ($class,$id) = @_;
my %data;
%data = $class->_initialize($id) if $id;
bless \%data, $class;
}
[download]
That isn't too complicated, but many people will stick all of the logic in one method or try to do method dispatch based on the number and type of arguments. Further, the more argument types you have to deal with, the more complex this becomes. By forcing the programmer to use extra logic, you increase the chance for bugs. Method overloading on signatures reduces the amount of logic necessary and therefore reduces the amount of bugs and makes the code simpler.
As a side note, I generally prefere explicit 'get' and 'set' methods rather than overloading those methods. It makes the code easier to understand and doesn't confuse the programmer when they try to do something they shouldn't be able to do.
# no! If this is mapping to a database, you probably don't
# want them to be able to change the id
$person->id( $id );
[download]
With the above, it may silently fail. Instead, when the programmer tries to call set_id, they'll likely get a useful error message letting them know that this method is not available.
Cheers,
Ovid
New address of my CGI Course.
Silence is Evil (feel free to copy and distribute widely - note copyright text)
my $person = People->new()->etc...
...
my $himagain = People->restore($id);
[download]
It would be helpful if you could give an example of an application or a pattern where such a technique of distinct routines to handle different arglists would be useful.
Any time you have a sub that checks the passed parameters and then dispatches to different code depending on the type or quantity of the parameters you're a good candidate for this. It's much less error prone (and usually faster) if the language handles the dispatch.
#!/usr/bin/perl -w
use strict;
sub func (&@) {
my $func = shift;
foreach (@_) {
$func->($_);
}
}
sub func (@) {
foreach (@_) {
print $_;
}
}
my @list = ('bob', 'sally', 'joe');
func { print "!!!$_\n"; } @list;
func @list;
[download].
Mmmhhhh...
Not the java way for sure. If anything, I'd go the python way:
def foo(one,two=None,*args,**kwargs) :
pass
[download]
foo(1)
foo(1,2)
foo(two=3,one=4,'fubar',three=42)
[download]
Yes
No
Other opinion (please explain)
Results (102 votes),
past polls | http://www.perlmonks.org/?node_id=217417 | CC-MAIN-2015-40 | refinedweb | 681 | 65.46 |
Created on 2014-03-27 23:10 by vstinner, last changed 2017-06-28 01:31 by vstinner. This issue is now closed.
With the current asyncio API, it's not possible to implement the shell command "ls | wc -l" in Python: connect the stdin of a consumer to the stdin of a producer.
How do you do that with the subprocess module, and why doesn't that work with asyncio?
> How do you do that with the subprocess module
Something like that:
---
import subprocess
ls = subprocess.Popen(["ls", "-1"], stdout=subprocess.PIPE)
wc = subprocess.Popen(["wc", "-l"], stdin=ls.stdout)
ls.wait()
wc.wait()
---
> and why doesn't that work with asyncio?
It's possible with the two methods of an event loop, but I'm requesting this feature for the high-level API: asyncio.subprocess.
create_subprocess_shell("cat", stdout=subprocess.PIPE) starts immediatly to consume stdout, before I can connect the pipe to "wc" stdin. Currently, the asyncio.subprocess is designed to be able to write:
---
proc = yield from create_subprocess_exec("ls", stdout=subprocess.PIPE)
stdout, _ = yield from proc.communicate()
---
Oh, I see. Given that it is possible to do using event loop methods, why don't you write up a complete implementation and then propose to add that to the asyncio.subprocess module?
> Oh, I see. Given that it is possible to do using event loop methods, why don't you write up a complete implementation and then propose to add that to the asyncio.subprocess module?
I don't know that a whole new implementation is needed. I guess that a
simpler change can be done on SubprocessStreamProtocol to ask to not
consume the pipe (don't attach a StreamReader to the pipe transport).
I still want to use streams at the end, so use the "high-level API". Example:
---
ls = yield from create_subprocess_exec("ls", stdout=subprocess.PIPE)
grep = yield from create_subprocess_exec("grep", "-v", "-F", ".old",
stdin=ls.stdin, stdout=subprocess.PIPE)
stdout, _ = yield from grep.communicate()
---
But how is the first call supposed to know that you don't want a StreamReader? Or the second that you do want one? Maybe we need a new constant instead of PIPE that means "leave it hanging"?
I don't see how to implement this idea, not if it's doable. Anyway, I'm not interested anymore to implement the idea, so I just close this old issue. | https://bugs.python.org/issue21080 | CC-MAIN-2020-10 | refinedweb | 400 | 67.76 |
MQTT Library¶
This module contains an implementation of the MQTT protocol (client-side) based on the work of Roger Light <roger@atchoo.org> from the paho-project.
When publishing and subscribing, a client is able to specify a quality of service (QoS) level for messages which activates procedures to assure a message to be actually delivered or received, available levels are:
- 0 - at most once
- 1 - at least once
- 2 - exactly once
Note
Resource clearly explaining the QoS feature: mqtt-quality-of-service-levels
Back to the implementation Zerynth mqtt.Client class provides methods to:
- connect to a broker
- publish
- subscribe
- unsubscribe
- disconnect from the broker
and a system of callbacks to handle incoming packets.
MQTTMessage class¶
- class
MQTTMessage¶
This is a class that describes an incoming message. It is passed to callbacks as message field in the data dictionary.
- topic : String. topic that the message was published on.
- payload : String. the message payload.
- qos : Integer. The message Quality of Service 0, 1 or 2.
- retain : Boolean. If true, the message is a retained message and not fresh.
- mid : Integer. The message id.
Client class¶
- class
Client¶
This is the main module class. After connecting to a broker it is suggested to subscribe to some channels and configure callbacks. Then, a non-blocking loop function, starts a separate thread to handle incoming packets.
Example:
my_client = mqtt.Client("myId",True) for retry in range(10): try: my_client.connect("test.mosquitto.org", 60) break except Exception as e: print("connecting...") my_client.subscribe([["cool/channel",1]]) my_client.on(mqtt.PUBLISH, print_cool_stuff, is_cool) my_client.loop() # do something else...
Details about the callback system under
on()method.
__init__(client_id, clean_session=True)¶
- client_id is the unique client id string used when connecting to the broker.
- clean_session is a boolean that determines the client type. If True, the broker will remove all information about this client when it disconnects. If False, the client is a persistent client and subscription information and queued messages will be retained when the client disconnects. Note that a client will never discard its own outgoing messages if accidentally disconnected: calling reconnect() will cause the messages to be resent.
on(command, function, condition=None, priority=0)¶
Set a callback in response to an MQTT received command.
command is a constant referring to which MQTT command call the callback on, can be one of:
mqtt.PUBLISH mqtt.PUBACK mqtt.PUBREC mqtt.PUBREL mqtt.PUBCOMP mqtt.SUBACK mqtt.UNSUBACK mqtt.PINGREQ mqtt.PINGRESP
function is the function to execute if condition is respected. It takes both the client itself and a data dictionary as parameters. The data dictionary may contain the following fields:
- message: MQTTMessage present only on PUBLISH packets for messages with qos equal to 0 or 1, or on PUBREL packets for messages with qos equal to 2
condition is a function taking the same data dictionary as parameter and returning True or False if the packet respects a certain condition. condition parameter is optional because a generic callback can be set without specifying a condition, only in response to a command. A callback of this type is called a ‘low priority’ callback meaning that it is called only if all the more specific callbacks (the ones with condition) get a False condition response.
Example:
def is_cool(data): if ('message' in data): return (data['message'].topic == "cool") # N.B. not checking if 'message' is in data could lead to Exception # on PUBLISH packets for messages with qos equal to 2 return False def print_cool_stuff(client, data): print("cool: ", data['message'].payload) def print_generic_stuff(client, data): if ('message' in data): print("not cool: ", data['message'].payload) my_client.on(mqtt.PUBLISH, print_cool_stuff, is_cool) my_client.on(mqtt.PUBLISH, print_generic_stuff)
In the above example for every PUBLISH packet it is checked if the topic is cool, only if this condition fails, print_generic_stuff gets executed.
connect(host, keepalive, port=1883, ssl_ctx=None, breconnect_cb=None, aconnect_cb=None, sock_keepalive=None)¶
Connects to a remote broker.
- host is the hostname or IP address of the remote broker.
- port is the network port of the server host to connect to. Defaults to 1883.
- keepalive is the maximum period in seconds between communications with the broker. If no other messages are being exchanged, this controls the rate at which the client will send ping messages to the broker.
- ssl_ctx is an optional ssl context (Zerynth SSL module) for secure mqtt channels.
- breconnect_cb is an optional callback with actions to be performed before the client tries to reconnect when connection is lost. The callback function will be called passing mqtt client instance.
- aconnect_cb is an optional callback with actions to be performed after the client successfully connects. The callback function will be called passing mqtt client instance.
- sock_keepalive is a list of int values (3 elements) representing in order count (pure number), idle (in seconds) and interval (in seconds) of the keepalive socket option (default None - disabled).
Subscribes to one or more topics.
topis a list structured this way:
[[topic1,qos1],[topic2,qos2],...]
where topic1,topic2,... are strings and qos1,qos2,... are integers for the maximum quality of service for each topic
unsubscribe(topics)¶
Unsubscribes the client from one or more topics.
- topics is list of strings that are subscribed topics to unsubscribe from.
publish(topic, payload=None, qos=0, retain=False)¶
Publishes a message on a topic.
This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics.
- topic is the topic that the message should be published on.
- payload is the actual message to send. If not given, or set to None a zero length message will be used.
- qos is the quality of service level to use.
- retain: if set to true, the message will be set as the “last known good”/retained message for the topic.
It returns the mid generated for the message to give the possibility to set a callback precisely for that message.
reconnect()
Sends a disconnect message. | https://docs.zerynth.com/latest/official/lib.zerynth.mqtt/docs/official_lib.zerynth.mqtt_mqtt.html?highlight=mqtt | CC-MAIN-2019-30 | refinedweb | 992 | 56.96 |
With the release of IBM® WebSphere® Business Integration Server Foundation V5.1.1 comes the ability to put the Common Event Infrastructure (hereafter called CEI) to into full use. The technical preview in V5.1 provided developers with a glimpse into the potential of the CEI for creating, managing, and distributing event information.
This article provides an overview of the changes and added functionality of the Common Event Infrastructure from technical preview to production release. As well as giving a summary of the new features, it also looks at what changes a developer needs to be aware of having previously used the technical preview.
Developers who have used the technical preview and want infomation about the changes and new features contained in the production release will find this article particularly useful. It also provides an overview for anyone looking to use the Common Event Infrastructure.
Figure 1. Overview of the Common Event Infrastructure
Applications running in both J2EE and J2SE environments act as event sources to create and send events to the CEI server. When a significant business or system event occurs, the application creates a Common Base Event (hereafter called CBE) containing data describing the details of event. The CBE is then sent to the CEI server, using an event emitter, either synchronously or asynchronously. The CEI server may then persist and/or distribute the event to registered listeners. The production release adds:
- An Event Catalog component that can be used to store event definitions.
- An Event Access component that allows events to be retrieved from the CEI server using a subset of the XPath language for defining queries.
- An ECSEmitter that can be used within the Application Server environment for creating, correlating and sending events.
The rest of this document describes the differences and enhancements from the technical preview of the CEI to the production release in Version 5.1.1.
Using the CEI in a WebSphere Application Server environment
The production release of the CEI adds a new package,
com.ibm.websphere.cem (hereafter called Common Event Model), which combines event creation, correlation, and emission functions into a single class,
com.ibm.websphere.cem.ECSEmitter.
In the technical preview, CBE instances are created using an EventFactory. This has not changed, except of course that the class has moved to
org.eclipse.hyades.logging.events.cbe.EventFactory. In the technical preview, two event factories are bound in to the WebSphere JNDI namespace: a generic factory and a WebSphere-specific factory.
The generic event factory is unchanged. The code sample below demonstrates how to obtain the generic Event Factory and create a CBE instance:
Applications running inside the Application Server are recommended to use the ECSEmitter instead. The following code sample shows how to create a CBE instance using this method.
The parameters passed to create the ECS Emitter will be explained in the section entitled Emitting Events below.
Event instances in the technical preview are modelled by classes in the
com.ibm.events.cbe package. For example, the top-level CBE class is called
com.ibm.events.cbe.CommonBaseEvent. The location of these classes changes in the production release, due to use of the CBE classes in the Eclipse Tools Hyades Project. The classes may now be found in the
org.eclipse.hyades.logging.events.cbe package. Developers that have experimented with the technical preview and wish to reuse their code must therefore change their package imports:
The classes, methods and attributes in the Hyades package are virtually identical, with only some minor changes have been made to the XML serialization code known at time of writing. For more information on the CBE specification and the Hyades project, refer to the Resources section at the end of this article.
The way in which data in manually added to events is unchanged. However the manner in which business context data is created and automatically added by the Application Server to events is different.
In the technical preview, the Business Context Data Service (BCDS) enables users to define a collection of named contexts, each containing name-value pairs relevant to that context. This context data is then inserted in to the event via the WebSphere specific content handler on the event instance. The content handler may be invoked either by the user, calling the
complete(), method on the event instance, or at the point of emission where the emitter invokes the complete() method.
For example, a business with a BPEL business process used for capturing customer details via a website defines a business context instance for "completing customer details" and inserts context name-value pairs that are copied in to every CBE that is emitted within that process.
In the production release, the functionality of the BCDS used for event correlation is integrated in to the new
ECSEmitter class. The
ECSEmitter introduces the concept of an Event Correlation Sphere (hence ECS). The
ECSEmitter provides methods for setting the current and parent correlation sphere IDs.
An event correlation sphere is a string identifier that may be used to correlate events that belong to a particular business process or context. Events sent by the
ECSEmitter can contain two correlation sphere identities; a current sphere and a parent sphere.
The
ECSEmitter provides the following methods to get and set these IDs:
getParentEcsId(),
getCurrentEcsID(),
setCurrentEcsID(String currentID),
setParentEcsID(String parentID). The current ECS ID may also be set during the construction of an
ECSEmitter instance.
When the current correlation ID is set the previous current ID overwrites the parent ID. If the sphere IDs are set they will be inserted in to the event during the
sendEvent(...) method of the
ECSEmitter inside context data elements as follows:
To easily send reporting events containing extended data elements the
ECSEmitter also provides an
addUserDataEvent(java.util.Properties) method. This method emits an event to the CEI server with the properties set as extended data elements in the CBE. Figure 2 below shows other data that is set in the event when this method is used.
Table 1. Event data added when using ECSEmitter.addUserDataEvent(...) method
The following code snippet shows how you can use the
addUserDataEvent(Properties) method.
This code sends an event to the CEI server without the need to create a CBE first.
When a CBE instance has been populated, the event source can send the event to the CEI server using one of the
sendEvent(...) methods of a emitter instance:
com.ibm.events.emitter.Emitter.
The technical preview events only support sending events synchronously to the event server, using an EJB interface. The production release adds the ability to send events asynchronously via JMS. This, for example, allows the event source to continue processing after emitting an event rather than blocking until the event has been successfully transmitted and processed by the event server. Administrators configure the synchronization mode of each emitter to suit their own application requirements.
Figure 2. The emitter transmission modes
In addition to the
EventBusTransmissionProfile for synchronous transmission, there is now a
JMSTransmissionProfile containing the JNDI names for the JMS Queue and Queue Connection Factory to be used by the emitter. If asynchronous transmission is required, the application server must, of course, be configured with the appropriate JMS Queue and Queue Connection Factory. In addition to this, CEI server must be enabled to listen for events appearing in the specified JMS queue. A JACL script called
event-message.jacl is located in
/event/application/ and can be used to create an emitter and all the appropriate resources required to send events asynchronously.
Within the Application Server environment the
ECSEmitter removes the need to perform the lookup of a
CEI Emitter from JNDI. The
ECSEmitter class is illustrated below in Figure 3 and defines the constructor:
The ECSEmitter obtains the EmitterFactory from JNDI using the JNDI name passed in on the contructor. It creates the CBE and provides methods to populate it with data before sending it to the CEI server.
Figure 3 The ECSEmitter
The code snippet below shows how to create an
ECSEmitter instance:
If you do not want to have the event source set the current correlation sphere ID, you should pass null in as the second parameter. For further information on constructing the
ECSEmitter refer to the Infocenter and API documentation.
The production release enables administrators to configure emitters to filter events, that is, to discard events within the emitter so they are not sent to the event server. A Filter Factory Profile is created and configured with an XPath-like expression that is used to determine if the CBE should be sent to the CEI server. For example, setting the filter expression to
CommonBaseEvent[@severity = 50] would cause the emitter to only send events to the event server that have a severity of precisely 50.
To enable an emitter to use a filter factory profile, enter the JNDI name in the emitters FilterFactoryProfileJNDIName attribute as well configuring it to enabling filtering.
In addition to using the profile described above, users can create their own filter and bind it into JNDI. To create a custom event filter:
- Create a filter by implementing the com.ibm.events.filter.Filter interface.
- Create a filter factory by implementing the com.ibm.events.filter.FilterFactory.
- Bind a FilterFactory instance into JNDI.
- Enter this JNDI name into the emitter's Filter Factory JNDI Name attribute.
The factory is obtained by the emitter during initialization in the event source and is used to create an instance of a Filter. Notice that it is not possible for an event source to bypass a filter configured by an emitter.
The production release introduces a new concept called event consumers. Whereas applications that create and send events to the CEI server are called event sources, event consumers subscribe and listen for events. An administrator can configure event group profiles contained within an event group profile list. An event group profile object defines a selector string which determines which events belong to this group. These selector strings use the same XPath-like syntax as the filter configuration.
Each event group profile can be associated with a JMS topic and multiple JMS queues. When the CEI server receives an event (and provided that event distribution is enabled), it attempts to match the event to an event group. If the event matches a group, it then publishes the CBE to the JMS queue or topic configured for that event group. Consumers can listen for events on the appropriate JMS queue or subscribe to the JMS topic to process the event information.
Figure 4 shows the classes and concepts of an event group profile list that contains a list of event group profiles. Each event group profile can contain multiple distribution queues.
Figure 4 Overview of the event group profile lists classes
Example using distribution
Two event group profiles have been created:
Table 2. Event group profiles
EventGroupA contains two distribution queue definitions but EventGroupB contains none.
If the CEI server receives a CBE and distribution is enabled, it will check to see if the event matches any of the event groups configured in the EventGroupProfileList. If the CBE has a severity field with its value set to 70, then it will match 'EventGroupA' and send the CBE information to the any JMS resources configured for that Group (in this case the two JMS resources specified in the DistributionQueue resources).
If consumers wish to listen for events on a particular resource, then they can use an Message Driven Bean (MDB). The CEI provides a helper object, called the NotificiationHelper, that obtains the information from a JMS resource and converts it in to a CBE instance. The NotificationHelper is created from a NotificationHelperFactory object bound into JNDI under com/ibm/events/NotificationHelperFactory. When a message is received on the onMessage() method, the CBE can be obtained using the getCreatedMessage(javax.jms.Message message) method.
The full event access API has been delivered in the production release of the CEI. This provides a powerful API for retrieving events based on particular criteria.
The technical preview supports the retrieval of events via event group and GUID. The production release supports the use of event selectors that can be used to select events based on their contents. The event selector syntax is a subset of the W3C XPath (this is not a coincidence as the Common Base Event specification describes events in terms of their serialization as XML documents).
For example, given the following event, users could retrieve all events that came over IPv4 using the event selector string
CommonBaseEvent/sourceComponentId/locationTtype='IPv4'; or retrieve all events that happened after this using
CommonBaseEvent/@creationTime > '2004-07-25T11:53:59.403Z'.
Getting access to the Event Access API is very simple. The entry point is unchanged from the technical preview that is by using a stateless session bean bound with the JNDI name
/ibm/events/access/EventAccess. The interface returned will be
com.ibm.events.access.EventAccessHome. The object returned by the create method on this home interface provides all the methods required for the different types of querying. The example queries described above would be executed using the following code snippet:
The Event catalog is a repository of event meta-data and provides the user with the ability to specify event definitions. It defines a set of API's that the user can use to add, query and remove event definitions from the repository. An event definition consists of its name, the name of any parent event definition, the extended data elements, and event properties that it can contain. An event definition can also be bound to an event category that is used to define logical groupings of event definitions.
The Event Catalog is implemented using a stateless session bean and can be accessed by looking up the home interface from JNDI as shown below:
You can use the event definition to define what properties a particular event should contain. However, if you want your applications to use this information to validate events, then these applications must write their own validation logic. Each time an event definition is modified or added, an event will be sent to the CEI server.
This article can only provide a brief introduction as the Event catalog would on its own require a further article to describe how users can add, remove, and query event definitions and categories. For additional information, refer to the API documentation.
The production release adds some new command line utilities, JACL scripts, located in the
/event/bin directory that can be used to perform the following operations on the CEI
- Emit events
- Query the Event Catalog
- Query events persisted by the event server
- Purge persisted events from the event server
Each file lists the parameters needed to use the JACL scripts and provides examples. To run the scripts, use the WSAdmin command (
wsadmin.bat or wsadmin.sh depending on your platform of choice) line tool located in
/bin directory.
The production release of the CEI contained within WebSphere Business Integration Server Foundation builds substantially on the technical preview offering for providing a complete event infrastructure for both technical and business events.
This article provides a quick-reference guide for the new functionality offered in the technical preview. It is specifically targeted at developers who have previously experimented with the technical preview.
- Standardize messages with the Common Base Event model
- Common Base Event specification
- IBM WebSphere Developer Technical Journal: Using the Common Base Event in the Common Event Infrastructure
- WebSphere Business Integration zone
- IBM WebSphere Developer Technical Journal
Andy Brodie worked on the development of the Common Event Infrastructure, specifically on the design and implementation of the emitter component. He also contributed to the development of WebSphere Application Server Enterprise. | http://www.ibm.com/developerworks/websphere/library/techarticles/0504_brodie/0504_brodie.html | crawl-003 | refinedweb | 2,616 | 51.28 |
A bar chart or bar graph is a chart with rectangular bars whose lengths are proportional to the values they represent. They're commonly used for comparing two or more values that were taken over time or under different conditions, usually on small data sets.
In this tutorial, we'll create a bar graph generator using XML and AS3.
Step 1: Brief Overview
Using ActionScript 3, we will get the necessary graph data from an XML file, then display the converted data into animated bars and an info area.
Step 2: Starting
Open Flash and create a new Flash File (ActionScript 3).
Set the stage size to 600x300 and add a gray radial background (#E6E6E6, #CCCCCC).
Our graph generator will be created entirely by code, so this will be the only thing you will do in the Stage.
Step 3: XML
Open yout favorite XML editor (any text editor will work) and add the following lines:
<?xml version="1.0"?> <graphs width="50"> <graph name="Yellow" value="50" color="0xFDC13E"/> <graph name="Blue" value="80" color="0x25B7E2"/> <graph name="Green" value="30" color="0xB8CF36"/> <graph name="Red" value="10" color="0xE7473F"/> </graphs>
This is the XML that we'll use to get the data, we won't be using the childrens' names, but the attributes.
- width: The width of each bar.
- name: The name of the element, to be displayed in the info area.
- value: The value of that element, displayed at the top of the bars.
- color: The color of the bar, in Hexadecimal.
This is the file that the end user will need to edit to show their own data.
Step 4: ActionScript!
It's ActionScript time.
Create a new ActionScript File (Cmd + N) and save it as "Graph.as", in your classes directory.
Step 5: Package
package {
The package keyword allows you to organize your code into groups that can be imported by other scripts. It's recommended to name them starting with a lowercase letter and use intercaps for subsequent words for example: myClasses.
In the example, the class is stored in the same location as the Fla file.
Step 6: Importing Necessary Classes
These are the required classes, for a more detailed description about every class, please refer to the Flash Help (F1).
import fl.transitions.Tween; import fl.transitions.easing.Strong; import flash.display.Sprite; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFieldAutoSize; import flash.net.URLLoader; import flash.net.URLRequest; import flash.events.Event;
Step 7: Declaring and Extending the Class
The extends keyword defines a class that is a subclass of another class. The subclass inherits all the methods, properties and functions, that way we can use them in our class.
public class Graph extends Sprite {
In this example, the Graph class inherits all the methods and properties of the Sprite Class.
Step 8: Variables
These are the variables we will use, explained in the comments.
private var graphContainer:Sprite = new Sprite(); private var xmlFile:XML; //The XML Object to parse the XML file private var urlLoader:URLLoader = new URLLoader(); //The file loader private var totalBars:int; //Stores the number of bars of the graph private var tween:Tween; //A Tween object for animation private var tf:TextFormat = new TextFormat(); //TextFormat
Step 9: Constructor
The constructor is a function that runs when an object is created from a class. This code is the first to execute when you make an instance of an object, or runs using the Document Class.
public function Graph():void { /* Text Format */ tf.color = 0x666666; tf.size = 12; tf.font = "Helvetica"; createGraphContainer(); loadXML(); createBars(); }
Step 10: Graph Container
This function will create the x and y axis lines of the graph using the drawing API.
private function createGraphContainer():void { graphContainer.graphics.lineStyle(1, 0x9C9C9E); graphContainer.graphics.moveTo(30, 30); graphContainer.graphics.lineTo(30, 270); graphContainer.graphics.lineTo(570, 270); addChild(graphContainer); }
Step 11: Load XML Function
This is the function that handles the loading of the XML file. We specify a default paramenter to avoid calling the function using another .as file, instead we're going to call it from the Document Class.
private function loadXML(file:String = "graph.xml"):void //Your xml data file { urlLoader.load(new URLRequest(file)); //Loads the file in the parameter urlLoader.addEventListener(Event.COMPLETE, parseXML); Calls a function when the load is complete }
Step 12: Parse XML
This function sets the data loaded to the XML object and calls the functions to create the graph using that data.
private function parseXML(e:Event):void { xmlFile = new XML(e.target.data); totalBars = xmlFile.children().length(); createBars(); displayNames(); }
Step 13: Create Bars
This code handles the bar creation.
private function createBars():void { for (var i:int = 0; i < totalBars; i++)//This for checks the number of bars in the xml { var bar:Sprite = new Sprite(); //A sprite for every bar bar.graphics.beginFill(xmlFile.children()[i].@color); //Gets the color of the bar from the xml bar.graphics.drawRect(0, 0, xmlFile.@width, xmlFile.children()[i].@value); //Creates the bar according to the xml specified width bar.graphics.endFill(); bar.x = 40 + (xmlFile.@width * i) + (10*i); //Bar position bar.y = 270 - bar.height; var val:TextField = new TextField(); //A TextField to display the value val.defaultTextFormat = tf; val.autoSize = TextFieldAutoSize.RIGHT; val.text = xmlFile.children()[i]. @ value; //Gets the value from xml val.x = 55 + (xmlFile.@width * i) + (10*i); //Textfield position val.y = 255 - bar.height; tween = new Tween(bar,"height",Strong.easeOut,0,bar.height,1,true); //Animates the bar addChild(bar); //Adds the sprites to stage addChild(val); } }
Step 14: Info Area
Information about the graph will be displayed in the top-right corner, this function will take care of that.
private function displayNames():void { for (var i:int = 0; i < totalBars; i++) { var color:Sprite = new Sprite(); //Creates sprites and textfields for every bar var names:TextField = new TextField(); names.defaultTextFormat = tf; names.autoSize = TextFieldAutoSize.LEFT; names.text = xmlFile.children()[i]. @ name; /* Position */ names.x = 500; names.y = 30 + (20 * i); /* Color squares */ color.graphics.beginFill(xmlFile.children()[i].@color); color.graphics.drawRect(0, 0, 10, 10); color.graphics.endFill(); color.x = 490; color.y = 31 + (20 * i); addChild(names); addChild(color); } }
Step 15: Document Class
Go back to the .Fla file and in the Properties Panel add "Graph" in the Class field to make this the Document Class.
Conclusion
Test your movie and see your graph appear on stage.
You can customize your graphs in many ways, using the XML file, and also adding new features with ActionScript. Try it!
I hope you liked this tutorial, Thanks for reading.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/create-a-dynamic-bar-graph-generator-using-xml-as3--active-2639 | CC-MAIN-2019-13 | refinedweb | 1,125 | 59.7 |
mezzo: Typesafe music composition
A Haskell music composition library that enforces common musical rules in the type system.
Modules
- Mezzo
- Mezzo.Compose
- Mezzo.Model
- Mezzo.Render
Downloads
- mezzo-0.3.1.0.tar.gz [browse] (Cabal source package)
- Package description (as included in the package)
Maintainer's Corner
For package maintainers and hackage trustees
Readme for mezzo-0.3.1.0[back to package description]
Mezzo
Mezzo is a Haskell library and embedded domain-specific language for music description. Its novelty is in the fact that it can enforce various rules of music composition statically, that is, at compile-time. This effectively means that if you write "bad" music, your composition will not compile – think of it as a very strict spell-checker for music.
- Getting started
- Composing in Mezzo
- Scores
- Rendering and exporting
- Rule sets
- License
- Acknowledgments
Getting started
This section explains how to install Mezzo and start using the library.
Prerequisites
Mezzo is a Haskell library with only a few dependencies. The main requirement is GHC 8.0.2: the package uses the latest and greatest features of the Haskell type system so it needs the most up-to-date version of the compiler. If you're using
stack, use the
lts-8.5 resolver (or higher).
Installation
If using Cabal, run
cabal update cabal install mezzo
If using Stack, you will need to add the package to your
extra-deps in your
stack.yaml (as Mezzo is not part of Stackage yet), and then add it normally to your
.cabal file dependencies:
extra-deps: [ mezzo-0.3.1.0 ] build-depends: base >= 4.7 && < 5 , mezzo
Build the file, and you should be good to go.
First composition
Create a new project (e.g. with
stack new) with a
Main module. Type:
import Mezzo comp = defScore $ start $ melody :| c :| d :| e :| f :>> g main :: IO () main = renderScore "comp.mid" "First composition" comp
Save, build and execute (e.g. with
stack exec <project_name>). You should get a
.mid file in the project directory which looks something like this:
To test the correctness checking, change the
d note in
comp to a
b. You should see the following when you save the file:
• Major sevenths are not permitted in melody: C and B • In the first argument of ‘(:|)’, namely ‘melody :| c :| b’ In the first argument of ‘(:|)’, namely ‘melody :| c :| b :| e’ In the first argument of ‘(:>>)’, namely ‘melody :| c :| b :| e :| f_’
Composing in Mezzo
This section provides more detail on the syntax of Mezzo.
Basic concepts
Music description languages are textual representations of musical pieces, used for note input or transcription. Most MDLs provide ways of inputting notes, rests and ways to combine these into melodies or chords. Mezzo additionally lets users input chords in their symbolic representation, as well as chord progressions using a schematic description of functional harmony.
Literal vs. builder style
Mezzo provides two main ways of creating musical values:
- Literal style: create musical values with explicit constructors of literal values. For example a C natural in octave 4 is written as
pitch _c _na _o4and can be abbreviated to
_cn. A quarter note (pitch with duration) is then written as
noteP (pitch _c _na _o4) _quor
noteP _cn _qu. Literal values are prefixed with an underscore and can be combined using the constructors
pitchand
noteP.
- Builder style: create musical values by sequencing their attributes from left to right. This style is more concise, flexible and readable than literal style and is therefore preferred. Creating a middle C quarter note is
c qn, an F sharp dotted sixteenth note in the 5th octave is
fs sn'or
f sharp sn'. Similarly, a C major chord would be
c maj qc, a B flat diminished seventh in first inversion with dotted half duration would be
b flat dim7 inv hc'.
The rest of this guide uses the builder style.
Primitives
Notes
Notes are given by their pitch and duration. In builder style, every pitch has an explicit value, consisting of three parts:
- Pitch class: one of
c,
d,
e,
f,
g,
aor
b; determines the position of the note in the octave, a white key on the keyboard.
- Accidental: a suffix of the pitch class, one of
f(flat, e.g.
bf qn) or
s(sharp, e.g.
fs qn). Natural accidentals are not specified, so
cmeans C natural. Accidentals can also be written out as a separate attribute (
c sharp qn), or even repeated (for example, double sharps:
c sharp sharp qnor
cs sharp qn).
- Octave: the last component of the value. The default octave is 4, this is unmarked. Lower octaves are marked with
_,
__,
_3,
_4and
_5. Higher octaves are marked with
',
'',
'3and
'4. A C natural in octave 2 is therefore
c__ qn, a B flat in octave 7 is
bf'3 qn.
Durations are written after the pitch. For notes, the value is the first letter of the duration name (eighth, quarter, etc.) followed by
n for note, e.g.,
qn for quarter note. A dotted duration is specified by following the name with a
' (single quote):
hn' is a dotted half note, with the length of three quarters.
Rests
Rests are similar to notes, but with
r instead of the pitch and an
r instead of
n in the duration. A quarter rest is
r qr and a dotted whole rest is
r wr'.
Chords
Chords are given by their root (a pitch), type, inversion and duration: a C major quarter triad in first inversion is
c maj inv qc.
- Root: specified the same way as in a note (
c,
af'', etc.).
- Type: three classes of chords: dyads, triads and tetrads.
- Dyads: A harmonic interval consisting of 2 notes. 5 types possible: minor thirds (
min3), major thirds (
maj3), fourths (
fourth), fifths (
fifth) and octaves (
oct).
- Triads: 3 pitches separated by thirds. 4 types possible: major (
maj), minor (
min), augmented (
aug) and diminished (
dim), based on the size of the intervals between the pitches.
- Tetrads: 4 pitches separated by thirds (the top one is a seventh above the bottom one). 5 types possible: major seventh (
maj7), major-minor/dominant seventh (
dom7), minor seventh (
min7), half-diminished seventh (
hdim7), diminished seventh (
dim7).
- Doubling: dyads and triads can be doubled to become a triad and tetrad respectively. This is done by repeating the bottommost note an octave higher, so a doubled C major third would consist of a C, an E, and another C an octave above. Doubling is specified by a
Dafter the chord type, e.g.
fifthD,
majDor
augD.
- Inversion: all of the types can be followed by a
'and then a separate attribute
i0,
i1,
i2or
i3to specify zeroth, first, second or third inversion:
c maj' i2 qc. Alternatively, the
invattribute can be added (any number of times) to invert a chord once (or any number of times):
c maj inv inv qc.
Chord durations end with a
c and can be dotted, as before:
c min7 qc,
f sharp hdim inv wc'.
Composition
Mezzo has two ways of composing music, inspired by Haskore: sequential (melodic) and parallel (harmonic) composition. In addition, Mezzo provides a convenient shorthand input method for melodies.
Harmonic composition
Harmonic composition
(:-:) plays two pieces of music at the same time:
g qn :-: e qn :-: c qn
For consistency, pieces should be composed from top voice to the bottom: the above example would therefore play a C major triad. The composed pieces can be any musical composition, as long as the durations of the pieces matches. If this is not the case, the shorter voice has to be padded by rests where necessary.
When using
(:-:), both harmonic intervals and harmonic motion are checked for correctness, so it is mainly intended for contrapuntal compositions. For homophonic compositions (where the "voices" are not independent, the top one being the main melody and the bottom ones being the accompaniment), you can use the
hom function which does not enforce rules of harmonic motion. For example,
(g qn :|: a qn) :-: (c qn :|: d qn)
would not compile due to a parallel fifth (
(:|:) is melodic composition, described in the next section). However,
(g qn :|: a qn) `hom` (c qn :|: d qn)
compiles, as
hom only checks for harmonic dissonance.
Melodic composition
Melodic composition
(:|:) plays one piece of music after the other:
c qn :|: d qn :|: e qn
The pieces don't have to only be notes or single voices, but the number of voices in the two pieces must match. For example, the code
c qn :|: c maj qc
fails to compile (and unfortunately produces a very cryptic error message), as the first note is only one voice while the chord is three voices. We can remedy this either by explicitly adding rests, or padding the first piece with silent voices, using the functions
pad,
pad2,
pad3 or
pad4:
pad2 (c qn) :|: c maj qc
This adds empty voices below the existing voices, but in some cases (e.g. a contrapuntal composition), we might want to keep the upper and lower voice and keep the middle voice silent. In this case, we can use the
restWhile function to input a voice of the same length as the argument, but with no notes.
comp = (top :-: restWhile top :-: bottom) :|: c maj qc
This example also shows how melodic and harmonic composition works together – as these are just combinators of
Music values, there is no restriction on the order or nesting of the operators.
Melodies
Even with builder style, inputting a long melody (sequence of notes and rests) is long and repetitive: the main issue is that duration change in melodies is not very frequent, yet we still specify the duration for each note:
c qn :|: c en :|: d en :|: ef en :|: d en :|: c en :|: b_ en :|: c hn :|: c hn
Mezzo provides a more concise way of melody input, where only the duration changes are explicit:
start $ melody :| c :< c :| d :| ef :| d :| c :| b_ :> c :| c
Melodies are effectively lists of pitches with the constructors specifying the duration of the next pitch. All melodies have to start with the
melody keyword – which initialises the melody and set the "default" duration to a quarter note – and a melody can be converted into a playable
Music value with the
start function. The constructors can be used as follows:
(:|): the next note has the same duration as the previous one. For example,
melody :| c :| d :| ecreates a melody of 3 quarter notes (since
melodyinitialises the duration to a quarter note).
(:<<<),
(:<<),
(:<),
(:^),
(:>)and
(:>>): the next note is a thirty-second, sixteenth, eighth, quarter, half or whole note, respectively.
(:~|): the next rest has the same duration as the previous value (note or rest).
(:~<<<),
(:~<<),
(:~<),
(:~^),
(:~>)and
(:~>>): as above, but must be followed by a rest.
- All constructors that change the duration (except
(:<<<)and
(:~<<<)) can be followed by a
.to make the duration dotted. For example,
melody :^ c :^. d :> especifies a melody of a quarter note, a dotted quarter note and a half note.
Below is a table summarising the melody construction operators. (See the [](GitHub README) if the table is not formatted.)
| Duration | Note | Rest | Dotted note | Dotted rest |
|---------------|-------|-------|-------------|-------------|
| No change | <code>:|</code> | <code>:~|</code> | | |
| Thirty-second |
:<<< |
:~<<< | | |
| Sixteenth |
:<< |
:~<< |
:<<. |
:~<<. |
| Eighth |
:< |
:~< |
:<. |
:~<. |
| Quarter |
:^ |
:~^ |
:^. |
:~^. |
| Half |
:> |
:~> |
:>. |
:~>. |
| Whole |
:>> |
:~>> |
:>>. |
:~>>. |
Examples
- Frère Jacques:
fj1 = start $ melody :| g :| a :| b :| g fj2 = start $ melody :| b :| c' :> d' fj3 = start $ melody :< d' :| e' :| d' :| c' :^ b :| g fj4 = start $ melody :| g :| d :> g fj = defScore $ fj1 :|: fj1 :|: fj2 :|: fj2 :|: fj3 :|: fj3 :|: fj4 :|: fj4
- Jingle Bells:
p1 = start $ melody :< e :| e :^ e :< e :| e :^ e :< e :| g :<. c :<< d :>> e p2 = start $ melody :< f :| f :<. f :<< f :< f :| e :<. e :<< e :< e :| d :| d :| e :^ d :| g jb = defScore $ p1 :|: p2
Chord progressions
Mezzo implements a subset of the functional harmony grammar of Martin Rohrmeier and is inspired by HarmTrace. The idea is that chord progressions are described schematically using functional harmony, a harmonic system which assigns various roles or functions to different chords of a key. For example, the chord of the first degree (called the tonic) represents stability and "home", while the fifth degree chord (the dominant) creates harmonic tension which has to be resolved into the tonic. The Mezzo EDSL for creating progressions guarantees that harmonic functions are handled and constructed correctly. For example, the following is a I–IV–V–I–IV–V7–I progression, consisting of one tonic-dominant-tonic phrase and a cadence:
p = prog $ ph_IVI ton dom_V ton :+ cadence (full subdom_IV auth_V7_I)
Harmonic regions
Harmonic regions are one of more chords of a certain harmonic function. For example, a tonic region can consist of one or more tonic chords. The actual nature of the chords (e.g. key, mode, etc.) is determined by the key signature of the piece, described in the next section. The regions are either single values (e.g.
dom_ii_V7 generates a secondary dominant chord followed by a dominant chord) or combinators of regions (e.g.
dom_S_D creates a dominant region from a subdominant region and a dominant region). The chords generated are sequences of quarter chords in the third octave, with appropriate inversions so the progression sounds as conjunct as possible.
- Tonic regions
ton: one tonic chord.
ton_T_T t1 t2: two consecutive tonic regions.
- Dominant regions:
dom_V: a major fifth degree chord.
dom_V7: a dominant fifth degree chord.
dom_vii0: a diminished seventh degree chord.
dom_II_V7: a secondary dominant (second degree) followed by a dominant (fifth degree) chord.
dom_S_D sd d: a subdominant region followed by a dominant region.
dom_D_D d1 d2: two consecutive dominant regions.
- Subdominant regions:
subdom_IV: a fourth degree chord.
subdom_ii: a second degree minor chord.
subdom_iii_IV: a third degree minor chord followed by a fourth degree major chord.
subdom_S_S sd1 sd2: two consecutive subdominant regions.
Phrases
A chord progression is broken up into phrases, composed using the
:+ operator. The last phrase must always be a cadential phrase, which provides closure to the piece. Phrase constructors (such as
ph_VI) take tonic and dominant regions as arguments, which are described above. The cadential phrase is constructed using the
cadence keyword, and followed by a cadential region.
- Phrases:
ph_I t: a tonic phrase, consisting of a single tonic region.
ph_VI d t: a dominant-tonic phrase, consisting of a dominant and tonic region
ph_IVI t1 d t2: a tonic-dominant-tonic phrase, consisting of a tonic, dominant and tonic region.
- Cadential regions:
auth_V_I: an authentic V–I cadence.
auth_V7_I: an authentic dominant V7–I cadence.
auth_vii_I: an authentic leading tone vii–I cadence.
auth_64_V7_I: an authentic dominant cadence with a cadential 6-4.
decept_V_iv: a deceptive V-iv cadence.
full sd c: a full cadence, consisting of a subdominant region and a cadence.
end: empty cadence.
The example above therefore has a tonic-dominant-tonic region, followed by a full cadence with a fourth degree subdominant and authentic dominant cadence. The
prog keyword converts a schema into a
Music value.
p = prog $ ph_IVI ton dom_V ton :+ cadence (full subdom_IV auth_V7_I)
Scores
Music values cannot be immediately exported into MIDI files, as there are various attributes of the piece that need to be specified first (in particular, the rule set used to check the correctness of the composition, without which the pieces will not compile). This is accomplished by constructing a
Score out of a
Music value, and specifying the attributes of the piece such as the tempo, time signature or rule set. Scores can also be used to break a larger musical piece into multiple sections which are "pre-rendered": this significantly cuts down on rule-checking time, as the correctness of the sections is checked independently. This also allows tempo or key changes, since each section can have its own set of attributes.
Score building
Scores are built using the following syntax:
score [<attribute_name> <attribute_value>]* withMusic <music>
For example, the following creates a new score from a
Music value
m for the refrain section of a piece in A minor and quadruple (common) meter, with a tempo of 120 BPM and strict rule-checking:
comp = score section "refrain" setKeySig a_min setTimeSig quadruple setTempo 120 setRuleSet strict withMusic m
- The
scorekeyword starts building a score and must be followed by the keyword
withMusicwith zero or more optional attributes in-between.
- The score attributes are simple name-value pairs written one after the other, with no punctuation (line breaks, as above, are optional). Mezzo currently supports the following attributes:
| Attribute name | Attribute type | Default value | Description |
|----------------|----------------|-----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
section | string |
"Composition" | A brief description of the section of the piece that the score describes. This attribute is only for documentation purposes, to make it clear in the source code which section is where. |
|
setKeySig | key signature |
c_maj | The key signature of the score, e.g.
c_maj,
a_min,
fs_maj,
bf_min. This affects the key of the chord progressions. |
|
setTimeSig | time signature |
quadruple | The time signature of the score, one of
duple,
triple, or
quadruple. This affects the number of chords played in a bar of a progression (e.g. three chords for triple meter, four chords for quadruple meter). |
|
setTempo | integer | 120 | The tempo of the piece, in BPM. This affects the tempo of the MIDI file playback. |
|
setRuleSet | rule set |
classical | The rule set used to check the correctness of a piece. One of
free,
classical,
strict, or any other user-defined rule set. |
- The
withMusickeyword finishes building a score from its argument of type
Music.
- If no attributes are modified (i.e. the default score attributes are used), the shorthand function
defScore mcan be used instead of
score withMusic mto create a score from the piece
m.
Rendering and exporting
Once a score is created from a musical piece, it can be exported as a MIDI file using the
renderScore function:
renderScore :: FilePath -> Title -> Score -> IO ()
The function takes a file path (specified as a
String), the title of the MIDI track (also a
String) and the score to export. Upon successful rendering, you should see the message
Composition rendered to <filepath>..
If a piece is broken up into smaller scores (sections), all of them can be concatenated and rendered using the
renderScores function:
renderScores :: FilePath -> Title -> [Score] -> IO ()
This is similar to
renderScore, but takes a list of
Scores (in the desired order). Note that this allows for reuse of sections: for example, a refrain (or repeated section) only has to be described once, and the score created from it can be reused without any additional rule-checking. See the Für Elise example for a demonstration.
Mezzo compositions can be played live, from the terminal, using the function
playLive' :: Score -> IO ()
You can also use
playLive = playLive' . defScore to play a
Music value right away. Note that in order to play Mezzo compositions from the terminal, you need to have an appropriate MIDI device (e.g. synthesiser) configured. As the implementation uses Euterpea's playback features, you should set up the configuration following these instructions.
Rule sets
As different musical genres enforce different kinds of rules, Mezzo lets users select different levels of strictness (called rule sets) or even completely customise the musical rules that are checked. In particular, one rule set turns off correctness checking completely, allowing for complete creative freedom.
Mezzo predefines three rule sets of increasing strictness. These can be specified using the
setRuleSet score attribute, as described in Score building.
The
free rule set
No musical rules enforced, the music is free from restrictions.
The
classical rule set
Enforces the common rules of classical music without being too restrictive. In particular:
- Very dissonant harmonic intervals like minor seconds, major sevenths and augmented octaves are forbidden. For example,
c qn :-: b qnproduces a type error. Note that the rule only applies at harmonic composition and is not enforced for chords: that is, a major seventh chord (which contains a major seventh) is allowed, but only when constructed symbolically.
- Large melodic intervals such as major sevenths or compound intervals are forbidden. These break up the flow of a melody, making it sound disjunct.
- Rules of harmonic motion, such as parallel and concealed unisons, fifths and octaves, are forbidden for harmonic composition of voices. Two voices singing in parallel a perfect interval apart are very difficult to distinguish: the intervals are so consonant that the voices effectively fuse together, and this does not make for interesting music. These rules are only enforced for contrapuntal harmonic composition (the
(:-:)operator) of individual voices, so sequential composition of chords (the
(:|:)operator) or chord progressions are allowed: the independence of voices is not important in a sequence of chords.
The
strict rule set
Enforces most of the rules of strict contrapuntal compositions, which are often based around vocal performance. This rule set is the most restrictive and is generally leads to longer compile times, but is probably the most useful for students of composition.
- Dissonant harmonic intervals are disallowed, just as in the
classicalrule set. However, major seventh chords are also disallowed.
- Large melodic intervals (sevenths and compound intervals) are disallowed, and so are augmented and diminished melodic intervals. These are difficult to sing and don't sound good to the ear. Note that due to enharmonic equivalence, an interval might have several names, and some of these may be forbidden. For example, a distance of 3 semitones can be called a minor third (allowed) or an augmented second (disallowed). The reasoning behind this is that minor intervals often appear in music in minor mode, but an augmented interval is usually given with an accidental and is therefore more "out of place". A caveat is that Mezzo internally only has three accidentals so it interprets
a flat flat qnas a G natural. This means that the interval
c qn :|: a flat flat qnis allowed, even though it is technically a diminished sixth interval.
- Harmonic motion constraints are enforced for harmonic and melodic composition (
(:-:)and
(:|:)), as well as homophonic composition (
hom). Symbolic chord progressions are still allowed, even if they violate harmonic motion rules – however, motion rules between a progression accompaniment and a melodic line are enforced.
Custom rule sets
Users of Mezzo can define their own custom rule sets, albeit adding complex rules can require a closer understanding of the Mezzo internals and type-level computation. Rule sets are a collection of constraints (i.e. Haskell type class constraints), one for all of the ways a
Music value can be constructed: harmonic composition, melodic composition, homophonic composition, rests, notes, chords, progressions.
Any value can be used as a rule set, as long as its type is an instance of the
RuleSet type class:
class RuleSet t where type MelConstraints t (m1 :: Partiture n l1) (m2 :: Partiture n l2) :: Constraint type HarmConstraints t (m1 :: Partiture n1 l) (m2 :: Partiture n2 l) :: Constraint type NoteConstraints t (r :: RootType) (d :: Duration) :: Constraint type RestConstraints t (d :: Duration) :: Constraint type ChordConstraints t (c :: ChordType n) (d :: Duration) :: Constraint type ProgConstraints t (s :: TimeSignature) (p :: ProgType k l) :: Constraint type HomConstraints t (m1 :: Partiture n1 l) (m2 :: Partiture n2 l) :: Constraint
The various constraints take as input the arguments of the corresponding
Music constructor: for example,
HarmConstraints takes the two type-level composed musical pieces (of type
Partiture) as arguments, and returns a
Constraint (see ConstraintKinds extension) expressing whether the pieces can be harmonically composed.
Custom rule sets can be useful even if the exact details of Mezzo's type-level model are not understood. For example, suppose that we want to create a very restrictive rule set for first-species counterpoint: this species only allows for melodic lines containing whole notes and enforces most of the classic rules of harmony, melody and motion. To implement this rule set, we can restrict the constructors that are allowed and delegate the complex rule-checking to the existing Mezzo implementation. To start, we define a new type for our rule set:
data FirstSpecies = FirstSpecies
Now, we make
FirstSpecies an instance of the
RuleSet type class by defining the associated constraint synonyms. In this case, we want to:
- Use the same musical rule-checking methods as the
strictrule set
- Only allow whole note and rest durations
- Disallow chords and progressions.
To achieve this, we declare the following instance of the
RuleSet class for
FirstSpecies:
instance RuleSet FirstSpecies where type MelConstraints FirstSpecies m1 m2 = MelConstraints Strict m1 m2 type HarmConstraints FirstSpecies m1 m2 = HarmConstraints Strict m1 m2 type HomConstraints FirstSpecies m1 m2 = HomConstraints Strict m1 m2 type NoteConstraints FirstSpecies r d = ValidDur d type RestConstraints FirstSpecies d = ValidDur d type ChordConstraints FirstSpecies c d = InvalidChord type ProgConstraints FirstSpecies t p = InvalidProg
MelConstraints,
HarmConstraintsand
HomConstraintssimply delegate rule-checking to the constraints of the
Strictrule set.
NoteConstraintsand
RestConstraintsare defined using the
ValidDurclass, defined as follows:
class ValidDur (d :: Duration) instance ValidDur Whole instance {-# OVERLAPPABLE #-} TypeError (Text "First species counterpoint only have whole durations.") => ValidDur d
This makes use of GHC's custom type errors feature, with the correspoinding types available in the GHC.TypeLits module. We define the
ValidDur type class (restricting its argument to a type of kind
Duration) without any methods. The
Whole duration is made an instance of
ValidDur, expressing our intention to make whole durations valid. The overlappable instance for
ValidDur d is selected only if the previous instance does not fit (i.e. the duration is not
Whole): in this case, a custom type error is encountered and type-checking fails, displaying our custom error message.
ChordConstraintsand
ProgConstraintsare simply equal to the "constant" (nullary) type classes
InvalidChordand
InvalidProg, which are defined in a similar manner to
ValidDur:
class InvalidChord instance TypeError (Text "Chords are not allowed in counterpoint.") => InvalidChord class InvalidProg instance TypeError (Text "Progressions are not allowed in counterpoint.") => InvalidProg
In this case, the constraints always fail (since they have no arguments), displaying the corresponding error message.
Having defined this instance, we can expect to see our custom constraints any time we use the
FirstSpecies rule set. For example, the following composition fails to compile:
comp = score setRuleSet FirstSpecies withMusic (c maj qc :-: b qn)
The type error messages explain what the problem is, just as we defined them:
• Can't have major sevenths in chords: C and B • Chords are not allowed in counterpoint. • First species counterpoint only have whole durations.
The full file (with the necessary language extensions and module imports needed) can be found in the examples folder.
Other constraints
Mezzo "implicitly" enforces other rules, but these are only required to make the internal enforcement system work. These rules are enforced independently of the rule set selected.
- As discussed above, concatenation of pieces of music requires both to have the same vertical or horizontal dimensions: this can be achieved by padding the shorter one with voices or rests.
- The shortest possible duration is a thirty-second: this means that dotted thirty-second notes are not allowed.
- Progressions generally follow the key of the score, but some harmonic regions are only valid in one of the two modes. In particular, the subdominant regions
subdom_ii
subdom_iii_IVcan only appear in a major mode piece.
- The octave limits are -1 to 8 inclusive: the lowest pitch is
c_5, the highest pitch is
b'4. For example,
b'4 maj qcdoes not type-check, as the third and fifth are out of bounds.
License
This project is licensed under the MIT License - see the LICENSE.md file for details.
Note that this project is different from Mezzo, a research language for effectful concurrent programming.
Acknowledgments
- Michael B. Gale for constant support, good ideas and encouragement.
- Richard Eisenberg for always knowing what to do when I got hopelessly stuck using TypeInType...
- Simon Peyton Jones for a stimulating discussion about the project and valuable advice on future work. | http://hackage.haskell.org/package/mezzo | CC-MAIN-2018-43 | refinedweb | 4,587 | 52.49 |
Natural Language processing (NLP) is an area of computer science and artificial intelligence that is related to the interactions between computers and human (natural) languages. It deals with how computers are programmed to fruitfully process large amounts of natural language data in order to perform useful tasks. The National Language Tool Kit (NLTK) is a library that facilitates experimentation with data related to NLP.
It was in the beginning of the 21st century that Steven Bird, Edward Loper and Ewan Klein from the University of Pennsylvania released a Python natural language processing library suite – the Natural Language Toolkit (NLTK). This library provides a platform to play around with data related to natural language processing (NLP), and simplifies NLP tasks such as text classification, parts of speech tagging, syntactic parsing, tokenisation and stemming.
Installation
NLTK is available for use in Windows, Linux and Mac OS. Aptitude can be used for installation in Linux, as follows:
sudo apt install python-nltk
Pip, a package manager to install and manage packages written in Python, can also be used in all operating systems to install NLTK. The command:
sudo pip install nltk
…will do the job.
Once you have installed NLTK successfully, you need to import the modules to use the functions provided by it. The following command can be used for the task:
import nltk
All the packages and corpuses supplied by NLTK can be downloaded once for later use by running the following command in the Python interpreter:
nltk.download()
Calling the download() function will cause the popping-up of the NLTK downloader. All but those versions lower than 0.9.5 of NLTK will support this operation. Figure 1 shows the NLTK downloader. It helps to install packages or corpuses by selecting the package from the list and clicking on the ‘Download’ button.
If Tkinter is not available in the system, a text interface may be provided by the NLTK downloader. As you can see in Figure 1, NLTK Book is installed in my system. The following command will import all the downloaded books:
>>> from nltk.book import * *** Introductory Examples for the NLTK Book *** Loading text1, ..., text9 and sent1, ..., sent9 Type the name of the text or sentence to view it. Type: ‘texts()’ or ‘s
We can see that nine text books and nine sentences are imported with a single statement.
Creating NLTK Book
Users can create their own NLTK Book. The content of a text file, a.txt, is given below:
“Natural language processing (NLP) is an area of computer science and artificial intelligence concerned with the interactions between computers and human (natural) languages, in particular how to program computers to fruitfully process large amounts of natural language data. Challenges in natural language processing frequently involve speech recognition, natural language understanding and natural language generation.”
This can be generated as an NLTK text book using the statements given below:
>>> f1=open('a.txt','rU') >>> txt=f1.read() >>> token = nltk.word_tokenize(txt) >>> nlp = nltk.Text(token) >>> nlp <Text: Natural-language processing ( NLP ) is an area...>
A text with the name ‘nlp’ is generated. Here, the file a.txt is opened in the rU mode, i.e., reading in universal newline mode. By opening a file in this mode, we make sure that newline characters in other platforms can also be supported by the platform on which Python is running. The use of the word_tokenize() function will be described later in this article.
The type of an NLTK Book can be obtained with the following statement:
>>>type(nlp) <class ‘nltk.text.Text’>
One article is not enough to explain everything about NLTK. Some of the NLP tasks that can be performed with it are explained below.
Tokenisation
The input text needs to be broken down into basic linguistic units before applying some transformations. Tokenisation is the process of splitting a stream of characters into meaningful entities, called tokens. This splitting can be done sentence-wise or word-wise. A sentence boundary can be detected with the help of the sent_tokenize tool in NLTK. An example is shown below:
>>> a=’hi sharon. how are you? revert me to sharon@gmail.com’ >>> nltk.sent_tokenize(a) [‘hi sharon.’, ‘how are you?’, ‘revert me to sharon@gmail.com’]
It is a sophisticated task to distinguish between the ‘.’ (the full stop) at the end of sentences and the one that appears in the mail ID!
Word boundaries can be detected easily with the help of word_tokenize(). The result after word tokenisation of ‘a’ is given below:
>>> b=nltk.word_tokenize(a) >>> b [‘hi’, ‘sharon’, ‘.’, ‘how’, ‘are’, ‘you’, ‘?’, ‘revert’, ‘me’, ‘to’, ‘sharon’, ‘@’, ‘gmail.com’]
Parts of speech tagging
Identifying the parts of speech associated with each word is a natural language processing task. Once the input is tokenised, POS tagging can be done on it. If the input is not tokenised before POS tagging, each character in the input will be POS tagged, which may not be an acceptable output.
>>> nltk.pos_tag(b) [(‘hi’, ‘NN’), (‘sharon’, ‘NN’), (‘.’, ‘.’), (‘how’, ‘WRB’), (‘are’, ‘VBP’), (‘you’, ‘PRP’), (‘?’, ‘.’), (‘revert’, ‘VB’), (‘me’, ‘PRP’), (‘to’, ‘TO’), (‘sharon’, ‘VB’), (‘@’, ‘NNP’), (‘gmail.com’, ‘NN’)]
Here, NN stands for noun, WRB for wh-adverb and VBP for present tense verb. Explaining the meaning of all POS tags is beyond the scope of this article. The following command will give details about all the Pen TreeBank POS tags:
>>> nltk.help.upenn_tagset()
Stemming and lemmatisation
Words take different inflections in different contexts; e.g., ‘wonder’, ‘wonderful’ and ‘wondering’ are inflections of the word ‘wonder’. Words can also take derivational forms like ‘diplomacy’, ‘diplomatic’, etc. Stemming is the process of reducing inflected or sometimes derived words to their root form, which can be used to generate words by suffix concatenation. The stemming algorithm works by removing common prefixes and suffixes from the given input. NLTK provides interfaces for the Porter stemmer, Snowball stemmer, Lancaster stemmer, etc. The following statements illustrate the use of the Porter stemmer:
>>> from nltk.stem.porter import * >>> stemmer = PorterStemmer() >>> stemmer.stem(‘wondering’) u’wonder’
Lemmatisation is the process of converting input into its dictionary form called lemma. It involves morphological analysis of the input. NLTK’s lemmatiser works on the basis of WordNet, a database of English. The use of the WordNet lemmatiser is shown below:
>>> from nltk.stem import WordNetLemmatizer >>> lemmatizer = WordNetLemmatizer() >>> lemmatizer.lemmatize(‘wolves’) u’wolf’ >>> lemmatizer.lemmatize(‘is’) ‘is’ >>> lemmatizer.lemmatize(‘are’) ‘are’
We can see in the above example that ‘is’ and ‘are’ are not lemmatised to their base form ‘be’. This is because the default POS argument of lemmatize() is ‘n’ ( ‘n’ stands for noun). To change the output, specify the POS argument ‘v’.
>>> lemmatizer.lemmatize(‘are’,pos=’v’) u’be’ >>> lemmatizer.lemmatize(‘is’,pos=’v’) u’be’
We can see that result after stemming and lemmatisation are in Unicode format, which is indicated by ‘u’.
Other data processing tasks
Apart from tasks like tokenisation, lemmatisation, etc, NLTK can also be used in tasks like finding words that are longer than a specified value, the frequency of characters, searching text, sorting the contents of a book, etc. Some of these tasks are explained below.
Frequency of occurrences: The FreqDist() function accepts iterable tokens. Since character-by-character iteration is possible in strings, the application of this function on strings yields the frequency distribution of all characters in that string. An example is shown below:
>>>a=’hi this is sharon’ >>> nltk.FreqDist(a) FreqDist({‘ ‘: 3, ‘i’: 3, ‘h’: 3, ‘s’: 3, ‘a’: 1, ‘o’: 1, ‘n’: 1, ‘r’: 1, ‘t’: 1})
You can see that the result is a dictionary. The frequency distribution of a particular character can be easily retrieved from this as shown below:
>>> nltk.FreqDist(a)[‘s’] 3
If you wish to find the frequency of each word in a string, tokenise the string first and then apply FreqDist()
>>> nltk.FreqDist(nltk.word_tokenize(a)) FreqDist({‘this’: 1, ‘sharon’: 1, ‘is’: 1, ‘hi’: 1})
Searching text: The concordance() function provided by NLTK searches for a keyword and returns phrases containing it. Users have the facility to set the length of the phrase and the number of phrases to be displayed at a time. The command given below will search for ‘earth’ in text3 which is in the NLTK text book corpus:
>>> text3.concordance(‘earth’,40,5) Displaying 5 of 112 matches: earth . And the earth earth . And the earth was without form led the dry land Earth ; and the gather d said , Let the earth bring forth gras was so . And the earth brought forth gr
We can see that five phrases of length 40 characters are displayed on the screen.
Bigrams: Bigrams in the given input string can be obtained using nltk.bigrams(). This function actually returns a generator object. The code fragment given below illustrates the same:
>>> s=”open source for you” >>> nltk.bigrams(s) <generator object bigrams at 0x7fc49a8025f0>
Output can be obtained as a list by casting this generator to list as shown below.
>>> list(nltk.bigrams(s)) [(‘o’, ‘p’), (‘p’, ‘e’), (‘e’, ‘n’), (‘n’, ‘ ‘), (‘ ‘, ‘s’), (‘s’, ‘o’), (‘o’, ‘u’), (‘u’, ‘r’), (‘r’, ‘c’), (‘c’, ‘e’), (‘e’, ‘ ‘), (‘ ‘, ‘f’), (‘f’, ‘o’), (‘o’, ‘r’), (‘r’, ‘ ‘), (‘ ‘, ‘y’), (‘y’, ‘o’), (‘o’, ‘u’)]
You may feel that the output is not in the form desired because you were expecting word bigrams. In that case, the desired result can be obtained by tokenising or splitting the input into words before passing it to bigrams().
>>> list(nltk.bigrams(nltk.word_tokenize(s))) [(‘open’, ‘source’), (‘source’, ‘for’), (‘for’, ‘you’)]
Now the result seems perfect.
Collocations: nltk.collocations() lists bigrams occurring frequently in the input. The statement given below illustrates its result when applied to text1 in the NLTK corpus:
>>> text1.collocations(num=5) Sperm Whale; Moby Dick; White Whale; old man; Captain Ahab
The parameter num specifies the number of results that should be displayed. In the above example, as specified, the output contains only five bigrams. If we call the function without any parameter, all the frequent bigrams will be displayed.
Vocabulary of a given input: set() in NLTK will do the job. The output of this function preserves the property of a set, i.e., duplicates are not allowed in a set. An example is given below:
>>> s=”open source for you serves you open source related news” >>> set(nltk.word_tokenize(s)) set([‘for’, ‘related’, ‘source’, ‘serves’, ‘news’, ‘you’, ‘open’])
If you do not tokenise ‘s’ before applying set(), the character set in ‘s’ will be the result.
Feature structures
Constraints on natural language input can be better represented by exploiting features. NLTK provides the feature structure to map between feature identifiers and feature values, i.e., it represents a set of feature-value pairs. Feature identifiers are also called feature names. Feature values can be a simple string, int or nested feature values. It is useful when we wish to apply a similar treatment to feature-value pairs.
The general form of a feature structure is [feature1=value1, feature2=value2, ……]. Before use, it should be imported.
>>> from nltk.featstruct import FeatStruct
The statements given below will generate three feature structures — feat1, feat2 and feat3.
>>> feat1 = FeatStruct(number=’singular’, person=3) >>> feat2=FeatStruct(agr=feat1) >>> feat3=FeatStruct(cat=’VP’,agr=feat1, head=feat2) >>> feat3 [agr=(1)[number=’singular’, person=3], cat=’VP’, head=[agr->(1)]]
Here, feat1 contains two attributes — number and person. We can see that feat3’s attribute, head, has nested value.
A feature structure can be a feature list or a feature dictionary, which is automatically decided by FeatStruct depending on the type of argument passed to it. In a feature list, the feature identifier will be an integer. An example is shown below:
>>> type(FeatStruct([1,2,3])) <class ‘nltk.featstruct.FeatList’> >>> type(FeatStruct(sent=feat3)) <class ‘nltk.featstruct.FeatDict’>.
A lot more can be done with NLTK. This article is just an introduction to it. A complete reference to natural language processing using Python can be found in the book ‘Natural Language Processing with Python’ by Steven Bird, Ewan Klein and Edward Loper. | https://opensourceforu.com/2018/08/exploring-natural-language-processing-with-an-introduction-to-nltk/ | CC-MAIN-2020-10 | refinedweb | 1,993 | 57.57 |
Type: Posts; User: chiragrr
Also teaches you debugging ;)
Dude read up on loops for. Put the for (;;){ before cout<<"please enter.... " and then put the ending brace before System Pause call
Hey Guys,
I am looking for some help on how to get a HMAC hash for a string s using key k.
I found this() but I have no idea how to use it. Any pointers...
I think you need to understand .doc headers as mentioned by 7sutd
1) Put "sleep 300" in the perl file and run it infinitely
2) Use shell script and use that
These two are easier than C program. C++ - Never reinvent the wheel
A few problems
1) You have created an integer array of 150 and but if I chose a number between 0 and 1000000 it could take me more tries. This is assuming I do not use binary search
2) You never...
Depends on the firewall config on the server. You can do a TCP open on a known port but other than that I am not sure how to check whether the server is up and running.
If you are on a broadcast...
My recommendation is that you are wasting too much space for the unused characters.
1) Switch to using string instead of char array
2) At the end of each entry put in a special character. seekg...
Just use
ifstream infile ("Filename");
string name[10];
int marks[10],i;
if (! infile.is_open())
{
Sorry about being less ignorant while posting. Anyways I figured out the issue and thanks for taking the time out to respond. Henceforth I will make sure that I follow the guidelines
In short there is not optimal way of doing things here ;)
I agree with Lindley here. You can read the file with the censored words into an array or a Vector (safer option)
You can actually create a Vector of a struct
struct words
{
string word;
int pos;
};
I am trying to compile my program but am getting what I think are linker/compiler issues
chiragr@irrawaddy uname -a
Linux irrawaddy 2.6.23.8 #6 SMP Wed Nov 21 14:18:12 PST 2007 i686 AMD...
Start redoing your Java stuff in C++ nothing different nothing new. This would mean you would end up spending less time defining and understanding the problem and more time on C++
You can do the same by the following
//GLOBAL DEFINITION
int ast_length=0;
char *ast;
//WITHIN THE LOOP
{
read up on how to read and write binary files reading seekp/seekg and tellp/tellg
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string x;
ditto and close to the same time as well :D
Its going to be easier to debug this using gdb or any other tool that you use. I would say the worst case once you have read both the strings print them to check the contents. This would then give...
I agree but what about the case where two distinct entries have the same number of votes which is equal to max votes.
If its only about printing values then it can be void function. If you need...
I think you can achieve this in the same function as read.
Initialize two more variables
int maxvotes=0;
string max;
while(!inStream.eof())
{
inStream >> name;
If its a \0 terminated string you could use send (socket, array,strlen (array),...)
I would like to add that instead of
#include "/usr/include/sys/types.h"
#include "/usr/include/sys/socket.h"
I originally had
#include <sys/types.h>
#include <sys/socket.h> | http://forums.codeguru.com/search.php?s=f70ae27c0af86c1627643fad02d4aac3&searchid=4872789 | CC-MAIN-2014-35 | refinedweb | 602 | 79.3 |
.'"
Unix (Score:5, Insightful)
Can you imagine if Bell Labs had sued for control of the Unix APIs? We'd never have GNU, Linux, or many other projects that rely on those.
It would be a different world.
Re: (Score:2)
But just to play Devil's Advocate here I'd say there is a downside in that no corp that doesn't expressly make their living using the GPL "Blessed Three" which is 1.-Selling Services/Support, 2.- Selling Hardware or 3.- The tin cup will touch a GPLed company with a 50 foot pole because this ruling as far as the corps will be concerned makes any and all code of that company public domain and thus worthless if you don't use the blessed three.
Now some may consider that a good thing, after all Red hat has been
Re: (Score:2)
WTF does public domain have to do with the GPL?
Re:Unix (Score:5, Interesting)
We just had a test of this on a major GPL company. Trolltech was sold to Nokia for $153m. Their product was GPL / commercial and profitable, though $150m was grossly overpaying. Nokia LGPLed it which killed the 2 distribution model and thus Trolltech's way to make money on software. When Nokia sold Trolltech to Digia I think it was about $5m total.
Re:Unix (Score:4, Interesting)
Even though we rarely agree i have to give you credit is that is a GREAT example of what happens when a company that doesn't make their living using the GPL model tries to buy a GPL company, it ends up in a mess.
And I have taken shit over the years for pointing out that the GPL works best (and I would argue ONLY) with what I call the blessed three...what is wrong with that? Red Hat has made a billion dollar business out of the blessed three so it obviously works, it simply doesn't work with all kinds of software. for example I'd have a hard time seeing how you could make a profitable business out of desktops or video games using the blessed three model, which is probably why we have seen no serious competition from GPL software on those fronts. It simply doesn't fit into the methods of making money with GPLed software.
Personally i think in the long run this may turn out to be a good thing, companies that get bought for insane amounts of money usually end up getting turned into a mess by the buyer if they can't see a quick enough ROI and as companies like Red Hat have shown you have to be in it for the long haul with the GPL, you can't just flip companies for quick cash it just doesn't work that way. So maybe this will bring some sanity into the market and the only ones that will buy GPL companies will be those already making money using the GPL that will know how to treat the purchases right, not bring a mess of uncertainty like Oracle did with Sun.
Re: (Score:3)
If it is any consolation Oracle has had problems with companies like Peoplesoft as well. They don't do well with merges it ain't just the GPL. If I had to guess I'd assume that primarily Oracle doesn't care about making the money directly. I think they were buying Sun's customer base a huge percentage of whom were Sun/Oracle so that they could switch them gradually to x86/Oracle rather than potentially losing them to x86/Postgres or AIX/DB2. I think the complexity of Sun caught them off guard.
But no qu
Re: (Score:2, Interesting)
They effectively did, by suing BSDI at the time and by their descendants suing Linux. They even claimed certain things in K&R's book on C programming were "AT&T Trade Secrets" and "encumbered". Indeed, that was a major thing with AT&T at the time. If you knew how to program in C, you were "encumbered" by AT&T trade secrets and they (sometimes) would try to claim anything you did or developed as a result really belonged to them.
That was a common attitude at the time, which is why compilers of
Re: (Score:2)
Re:Unix (Score:5, Funny)
While I agree with the ruling, Oracle didn't sue for control of Android.
No, their motive was simply the same as every lawyer in the copyright business: "All your moneys are belong to us".
Re:Unix (Score:5, Interesting)
One note on this idea that lawyers are about taking everyone's money - it is akin to saying that software developers are out to take money from anyone who is a client of their development skills. Lawyers are proxies - they themselves don't do anything at all.
They are like paid soldiers on the legal battlefield. Lawyers don't have standing to sue anyone themselves, nor can they bring suits without a client. The client is the one who is suing, and the client is the one who has a claim. Lawyers can be paid hourly, or flat fee, or contingency percentage. In other words, if the client is asking the lawyer to bring suit, and will pay 10% of the damages in fees, then the client has agreed to that.
The real question is: why are you so indignant that lawyers get paid to represent clients? Do you hate the adversarial court system? Then legislate to change it. Do you hate lawsuits? Them legislate change to how lawsuits are brought. The idea that lawyers get PAID (heaven forbid) to represent someone's interests should not be a shock to you. We pay for all kinds of services from waiters to janitors to tax accountants to represent our interests, but if it is a legal representative, OH NOES!
I have family members in the legal profession, and they are good people - I get very tired of hearing about how evil lawyers are. If anyone is evil it is the CLIENTS.
Re:Unix (Score:5, Insightful)
There are too many lawyers that are too willing to say or do ANYthing for money. At least whores have limits.
That's not to say all lawyers are that way (I know a few who I believe to be good people doing good things), but too many are. As officers of the court, it is their duty to keep crap out of the courtroom.
As for the rest, nobody ever lost their house because someone hired a waiter but they couldn't afford one so they got their own sandwich.
Lawyers are hardly the only problem, but they (collectively) have the power to stop it and don't. They are also the public face of the very troubles system.
Re:Unix (Score:4, Insightful)
Its not the getting paid. Its the creating ways of getting paid by raping and pillaging society. Patent Trolls, Divorce Ninjas, Ambulance Chasers, Corporate Mercenaries, Political Lobbyists, and a whole zoo of lower life form crawling a full kilometer below the most disgusting social muck, all in the name of wealth and power. I'd take the dignity and straight up honesty of a hard working whore over such human toxic waste any day of the week and twice on Sunday.
I don't have a problem with the majority of lawyers who are honest, hard working people many who believe in what they do. I have a problem with people whose morality is tied to personal expedience, and whose personal interests transcend any and all moral value. We hung people at Nuremberg, for committing atrocities, but at least they were in fact following orders or following some ideology albeit abhorrent. These people commit atrocities, sell future generations down the stream, gut civil rights, sell their soul and intellect to the highest bidder and remake our system of jurisprudence into a perpetual fart joke (an endless stinking noise we can all share in.)
I would gladly double all their wages if they would just grow a soul.
Re: (Score:2)
Have you been killed dead by pencil sharpeners? If so, please dial our number immediately, you may be entitled to reasonable compensation for your death. We here at Dewey, Cheatem, and Howe are trained in keeping your interest and payout for the pain and agony your death has caused. Pencil sharpeners have been shown to be virtual harbingers of death, cruelly subjecting innocent people to the business end of sharpened pencils. The FDA has issued a ruling requiring pencil sharpener manufacturers to fund a fun
Lawyers (Score:4, Insightful)
Lawyers are proxies - they themselves don't do anything at all.
But they do. They perpetuate a system where you *have* to use an *expensive* lawyer in order to get justice or to protect yourself from legal attacks (which are usually more harmful than physical ones).
They are like paid soldiers on the legal battlefield.
No. Lawyers are akin to mafiosi operating a protection racket.
Lawyers don't have standing to sue anyone themselves, nor can they bring suits without a client. The client is the one who is suing, and the client is the one who has a claim.
Many countries have socialized medicine. Most countries have a socialized education system. As long as you must pay, often a sum that will bankrupt the average person, to defend yourself in court, justice is only for the rich. (Preemptive note: the "public defender" option is a fig leaf, it does not work, on purpose).
Lawyers can be paid hourly, or flat fee, or contingency percentage.
Guido can break your kneecaps, burn your house or rape your sister. I guess it's OK, as long as you have a choice.
The real question is: why are you so indignant that lawyers get paid to represent clients?
As a Canadian, I know that my basic health-care does not depend on the thickness of my wallet, and yet, doctors here still get paid. Plus, I do have an option to use a private clinic if I want to. I trust you're intelligent enough to compare and contrast.
Do you hate the adversarial court system? Then legislate to change it.
Legislators are lawyers. Good luck making them legislate against their own interests.
Campaign contributors and lobbyists are big businesses, who want to have an unfair legal advantage against those less wealthy. Good luck making legislators legislate against those who pay them.
Do you hate lawsuits? Them legislate change to how lawsuits are brought.
See above. Similarly: Do you hate the mob? Then change how it operates.
The idea that lawyers get PAID (heaven forbid) to represent someone's interests should not be a shock to you. We pay for all kinds of services from waiters(1) to janitors(2) to tax accountants(3) to represent our interests
1) I face no adverse consequences for choosing not to go to a restaurant. Everybody can cook a passable meal.
2) I am not forced to use the services of a janitor. The janitor union does not try to make maintenance as difficult and incomprehensible as possible to lay people.
3) I pay $20/year for a piece of software to do my taxes for me. I could use a free one which is no less good, but I find the paid version more convenient.
I have family members in the legal profession
So you are biased.
and they are good people
In your opinion. I am sure that many family members of the RIAA/MPAA/BSA feel the same (organizations chosen to avoid Godwining this thread).
I get very tired of hearing about how evil lawyers are.
The truth hurts.
Wrong in quite a few ways. (Score:5, Insightful)
1. You have to obey the rules to get the Java license, but your compiler, if it isn't being called java, doesn't have to obey them. dalvik.
2. The license doesn't require you implement at least one java standard. You have to implement a minimal functionality and can place your own in a different namespace. But you don't have to implement at least one java standard. But see #1 as to why this doesn't apply
3. dalvik was written because Google didn't want to implement java to their license, not because they couldn't.
Your assertion of google's jerkness is predicated on incorrect assertions.
Re: (Score:2)
Consider the many security problems Java has had wherever a browser plugin exposes it to the real world. Now consider how much more exposed an app on a phone can be.
Then you'll see why Google needed more freedom to maneuver than Oracle was willing to give them.
Re: (Score:2)
That's just dumb. The security problem is that the sandbox has too large of an attack surface. If you're using the OS to contain untrusted code, rather than the sandbox, Java is just as secure or insecure as C or Perl.
Re: (Score:2)
Who said anything about the OS? Java is supposed to support a sandbox well, but in practice it didn't work out that way.
To have a prayer of making it work, Google needed to be free to modify the spec in a few critical places.
Re: (Score:3)
Or don't use the sandbox. It's an added feature that most languages do not have.
Re: (Score:2)
if your system has any local user to root exploit then exploiting it from a dalvik application is trivial. there's no separate permission for running local native code(as the sandboxed user created for the application).
I think you would be better off comparing dalvik to the numerous j2me implementations, which are often more secure and more transparent about which data the application is accessing - actually to the point that on most phones several API's are totally unusable because the user is bombarded wi
Re: (Score:2)
Consider how much worse it would be if it was vanilla Java.
But most of that malware is of the Trojan type. It claims to be one thing, but does another with the unwitting permission of the user. That is quite different from circumventing a security mechanism to do something that was forbidden.
Re: (Score:3, Informative)
I wish people would stop thinking this is about Java. Its about Java Mobile Edition.
Now Oracle (or Sun, whatever) released Java with a permissive licence that said you can use it pretty much freely, but they kept the Java ME version to themselves, if you wanted the phone edition, then you had to buy a licence form Oracle. Google didn't feel they wanted to give Oracle a percentage of each Android sale so made their own very-compatible version.
Much as I dislike Oracle, I don't feel Google played fair on this,
Re:Wrong in quite a few ways. (Score:5, Insightful)
How exactly did any technology got stolen?
1) Dalvik is completely different from the usual Java VMs (Dalvik is register-based, while Java VMs are stack-based). That's how they got away with a VM that interprets (modified) Java bytecode without infringing any patents related to Java (as was confirmed by the "Oracle vs Google" case).
2) Android uses the exact same interfaces than Java, but that has been standard practice for decades (Unix, for example). No code between Android and Sun/Oracle's Java is the same, except for the stuff that must be the same to implement the same interfaces. The "Oracle vs Google" confirmed that's OK (as the summary says).
In the end, what happened is that Google didn't want to pay Sun/Oracle for a license to use Java mobile, so they implemented their own Java-compatible system (or rather, bought it from other people). That's how technology evolves. As someone else said here a few posts back: imagine if anyone wanting to do a Unix-like OS had to pay a license to someone. Where would we be now?
Re: (Score:3)
AFAIK, Dalvik was created before Google purchased Android. And the developers of Android developed Dalvik because Sun had screwed them over before when they were using the JVM on their previous projects.
Re: (Score:2)
I've built java apps without either. Not sure exactly why you're having trouble with it....
Re: (Score:3)
Let me quote RMS on that one
Re:Wrong in quite a few ways. (Score:5, Informative)
Stallman has defended right to fork long after XEmacs. At the time what he said was:
Re:Wrong in quite a few ways. (Score:4, Insightful)
Implementing your own system that meets your needs is not being a jerk. Asserting rights that you do not have is jerky behavior. Oracle is being the jerk in this instance.
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
Yes, it is about being a jerk.
Sun was the jerk because they kept misrepresenting what Java was and what they were going to do with it in order to get industry support. They pulled out of standardization efforts and bullied other companies with outrageous legal threats, all the while running Java into the ground technically and having an army of contributors fix their problems for them under exploitative licensing terms. They had everybody by their balls.
Android Inc decided to implement their own version of
Re: (Score:2)
I'm not being dense I don't think Google was being a jerk. Google was doing what they thought was best. Google doesn't work for Sun. Just because Sun wants something doesn't mean Google is being for not doing it. I'm sure Microsoft wasn't fond of Open Office, that doesn't mean that Sun was being a jerk for not canceling the project because Sun objected.
I'm hard pressed to see what the difference is between what Google did when they created Davlik and what Sun did when they made Java from Oak.
Re: (Score:3)
Uh, sun praised google for the creation of android. You know that, right? [theblitzbit.com] . Anything following Oracle's acquisition at that point is entirely moot. Note the date, as well.
You are incredibly biased and either accidentally or intentionally missing both a: facts and b: cognitive arguments being made by everyone else. Were you a sun developer or something?
Re:Wrong in quite a few ways. (Score:4, Informative)
Re: (Score:2)
Re:Wrong in quite a few ways. (Score:4, Interesting)
If you'd done any research at all, you'd find that Google refers to it as Java all over the place.
The word "java" is all over the place in the name of the methods (e.g. java.lang.Number). Thus the "Java all over the place" doesn't play any role.
Dalvik is the VM, not the language.
I haven't followed the suit very closely, but in previous legal cases, Sun/Oracle not once tried to blur the line between "Java as implementation" (aka JVM and Java runtime library) and "Java as API or language."
Do not buy into it: there are two different things commonly referred to as Java: Java as language and APIs and Java as implementation of the language and APIs.
Implementation is copyrightable - language and APIs are not.
Re:Wrong in quite a few ways. (Score:5, Informative)
You're getting your facts wrong. Sun *approved* of Google's efforts, publicly and officially, in the forum of their CEO's blog.
Search (e.g., Groklaw [groklaw.net]) [groklaw.net] for more factual background and generally reasoned commentary on the Oracle suit.
Larry
Re: (Score:2)
I'll check out the info, thanks.
Re: (Score:2)
The jerkiness of Google is they went against the direct wishes of the creator of the project. Sun wanted to make sure that Java was compatible with Java anywhere, which is why they sued Microsoft for adding incompatibilities. Sun decided they wanted to make Java open source, but took measures to make sure any new implementation would be compatible. They did whatever they could to make sure it would be. Then Google decided to make an incompatible version, apparently to avoid the J2ME license issues, but for whatever reason, they made it incompatible. Not cool.
The creator of the Mp3 player probably never intended other companies like apple to add a bunch of DRM and make their Media Player incompatible with everything else.
Re: (Score:2)
you're quite wrong (Score:5, Informative)
The creator of the project (Sun) had promised to make Java an open ISO and ECMA standard. That's why people initially adopted it.
After several years, all of that turned out to have been a lie.
Just because Sun decides they own or control something doesn't mean they do.
Google didn't decide to make an incompatible version, Android Inc. did.
Android Inc did this before Sun released Java under an open source license.
Android Inc decided to do this because Sun had already screwed them once before on J2ME
Making Android compatible with J2ME would have made no sense; J2ME was a lousy design.
The only thing that's been "not cool" is Sun's long string of lies, their technical ineptness and mismanagement, and Oracle's attempt to establish API copyrights. Everybody else is just trying to dig out from under the consequences of their mess, deceptions and trolling.
Re:Unix (Score:5, Insightful)
Google couldn't get JSE to work on a phone, but could have implemented JME with little effort.
Not true. Google didn't implement JSE because many of the libraries in that standard don't make sense on a touch screen phone. They cut out a bunch of libraries and they changed the I/O library. JME has different rules than JSE. Oracle was protecting its mobile business and wanted a cut of app revenue.
Re: (Score:2)
License for what? What exactly do you think Sun/Oracle owns that Android should have licensed?
That requires them to pay money to Oracle. Furthermore, the original promise of Java was that it was going to be an open standard; Sun kept reneging on that promise.
Re:Unix (Score:5, Interesting)
They wanted control of what Android has become. They would have had it: Google tried to negotiate terms that would have given them that. But they wouldn't grant the licence necessary to let Android become what it has become. So Google had to do something else. It worked out for us. Android would not have been accepted as fast, nor progressed as fast, nor been as lightweight, if Sun had taken that deal. We wouldn't have as many of these amazing new things.
Personally after having followed the case and read through what Oracle has claimed here I am unwilling to use anything from their company ever again - no matter how indirectly derived or loosely controlled. It truly is despicable.
Re: (Score:2)
Re: (Score:3, Insightful)
I am unwilling to use anything from their company ever again - no matter how indirectly derived or loosely controlled. It truly is despicable.
- I came to that realisation probably in 2007-8, when I saw the proliferation of their drones disguised as 'contractor architects', whose only real mission was to push Oracle solutions into every single aspect of every business they managed to stick their tentacles into.
It's too bad Oracle bought Sun, it should have been Google or IBM. The fact that Oracle is the owner of Java TM and the reference implementation of JVM is extremely unfortunate (and it's part of the reason there is so much misinformation o
Re:Unix (Score:4, Informative)
Apropos misinformation. The reference implementation of Java 7 is now OpenJDK: [oracle.com]
OpenJDK is under the GPLv2. So I don't know how Orcale "own[s]" the reference implementation of the JVM.
Re:Unix (Score:5, Informative)
I don't care if Oracle released it under the BSD license. They claimed in this suit to have copyrights on max() and min() as if they invented that shit. It took a judge who was a programmer also to call them out on it or that stupid shit would have gone to a jury ignorant of the technology history. "I could implement that in 15 minutes" or some such he said. They claim to have various patents to prevent all of Java, Unix, Linux, Windows and every other thing involving technology everywhere in this universe and any alternates that subordinate all of the open source licenses they grant.
A company like that, their output is toxic. The safest course is not to deal with them or anything claiming to be derived from them at all. That means nothing from Solaris (not even ZFS or its derivatives), no MySQL (forks should be safe for now), No BTRFS, no Java - or anything even in the most remote sense related to Java. If they would sue over the API, what wouldn't they sue over?
It's a shame as Oracle has bought up some of the greatest stuff in IT - but perhaps that's the point. Uncle Larry isn't and has never been in the giving stuff away business and has no respect for the folks who are. He's found great success in the selling stuff business so when he finds givers in dire straits he takes their scalps and then scalps their customers too.
I have no interest in buying him another island. I've got useful stuff to do.
Re: (Score:2)
Re: (Score:2)
Re: (Score:2, Informative)
You mean, can you imagine of Bell Lab's hadn't sued for controll of UNIX. Bell did (well, it's parent, AT&T did).
No, Bell Labs didn't sue for control of UNIX.
BSD was sued by USL (UNIX Systems Laboratory, which at that time was a spinoff from AT&T) because there was UNIX code in BSD UNIX.
It turned out there was more BSD code in USL UNIX so BSD countersued and the matter was settled out of court.
Although that was a setback to BSD UNIX, it's questionable if that was Linux's most significant advantage.
Re: (Score:2, Insightful)
According to Linus Torvalds, it is the whole reason Linux even exists.
Re:Unix (Score:4, Interesting).
Re: (Score:3).
That like your opinion, man.
There's a million different ways to argue this, from "Stallman poisioned the well by using propaganda techniques to make people into GPL zealots" to "The Linux community had a structure that was better able to scale development and evangelization". The truth is that there were many different causes, and we'll almost certainly never know how important each was, and how much of this was basically random chance.
I can counterfact some of your hypotheses above, in case you're interes
Re: (Score:3)
Well written counter argument.
"Stallman poisioned the well by using propaganda techniques to make people into GPL zealots
That's very different than the lawsuit. And I think no question that Stallman, had a huge impact on making people believe in the GPL and changing people's mind. But if you look at the LAMP stack:
GPL: Linux, MySQL
BSD/MIT style: Apache, Perl
So at least by the early 1990s were it the case that the BSD/MIT licenses were far superior there were ways people could have seen it. Looking back
Reading between the lines (Score:5, Insightful)
Re: (Score:2, Insightful)
Because it's very difficult to legally distinguish between a troll and a tiny operation with genuine innovation that has gotten screwed over by a large corporation with lots of lawyers, especially for the non-expert patent officer whose job it is to grant the patent.
Does it have a product? (Score:3)
it's very difficult to legally distinguish between a troll and a tiny operation with genuine innovation
Does it develop and license significant know-how related to its patent portfolio? If so, it's genuine innovation (cf. ARM).
Re: (Score:2)
Does it develop and license significant know-how related to its patent portfolio? If so, it's genuine innovation (cf. ARM).
That's a fairly good negative proof, but the absence is hardly a good positive proof. After all, most companies are in the business of using their own innovations not licensing them to third parties. Nor do small companies have a patent portfolio, they may have patented one or a few key innovations that their business model revolves around that would be their unique selling point. And demanding it be in actual use it is a lot harder for small innovators that are looking for funding/production/partners/custo
Re: (Score:2)
How about "No, it doesn't, because before they finished development MegaResourcedCorp had been selling their unlicensed product for 6 months, and had been given other patents that prevent anyone (including the original inventor) from producing a competing product."
Re: (Score:3)
Their are penalties for frivolous lawsuits. The problem is there is a huge range between bad lawsuits and frivolous. The bar is high for frivolous.
As an American I'd like to see more suits have to pass a quick summary judgement on viability. And much stronger restrictions on changing the initial fillings.
Google should have bought Sun (Score:5, Interesting)
Google worst decision was to let Oracle buy and cannibalize Sun. It would have saved us and them from all these nonsense. Also Google's philosophy is so much closer to Sun's: great engineering and giving back to open source. The only thing Google is different than Sun is that they know how to profit from their products.
Heck, if they didn't want to spend all the money on their own they could lead a group of companies to buy out the IP of Sun.
It's really a pity that Oracle got a chance to buy Sun. I couldn't have imagined a worst end for such a great company.
Re:Google should have bought Sun (Score:5, Insightful).
I expect Ellison to join Ballmer in the stupid executive's retirement home. Both have fucked up hugely.
Re: (Score:2)
Sure wish I could fuck up as rich^H^H^H^Hbadly as them.
Re: (Score:3)
Sure wish I could fuck up as rich^H^H^H^Hbadly as them.
Royalties from legacy products. Innovation? Oracle & Microsoft are in the same boat, scrambling for a life preserver. People aren't going to keep paying for Oracle and Windows if they're replaced by something that everyone else adopts (like they did Oracle and Windows...)
Re: (Score:2)
What is competitive with Oracle for large relational databases other than DB2? Oracle financials, Peoplesoft, Siebel, JD Edwards...
I think they are fine for now.
Re: (Score:3)
PostgresSQL. If you're using the non-standard PL/SQL stuff in Oracle you're never getting out though.
Re: (Score:2)
Postgres is a comparable to about Oracle 8 in terms of features, there are still very good reasons to use Oracle. Besides my point was that even if the database business does die they have many many more products now.
Re: (Score:2)
From what I've seen, the rest of their products are quite poor. I always joked that they should stick to databases, but even that has significant competition now.
Re: (Score:2)
No. There is nothing like Peoplesoft or Siebel. Oracle financials is excellent. I would never describe those as poor.
Re: (Score:2)
Sure wish I could fuck up as rich^H^H^H^Hbadly as them.
Royalties from legacy products. Innovation? Oracle & Microsoft are in the same boat, scrambling for a life preserver.
Yeah, maybe Oracle and MS are scrambling for a life preserver, but Ellison and Ballmer certainly aren't. Sure, their companies woes might mean that there will be an upper limit on how many Gulfstreams they can buy, but I'm sure that 99.9% of Americans wouldn't mind the difficulties of going into the "stupid executive's retirement home."
Re: (Score:2).
Not to mention with this case they pretty much settled it if Google starts going after desktop java with an enhanced Dalvik for laptop/desktop replacements. What would be nice though is if the Linux devs could get their hands on a GPL-compatible version of Solaris so they could integrate ZFS and some various other goodies, but I suspect you'd have to pay dearly for that.
Re: (Score:2)
ZFS is open source. Turns out it sucks on inexpensive (x86 quality) hardware, in ways that are unfixable even by smart people. Apple lost years proving that.
But [zfsonlinux.org]
But Oracle's BTRFS plays the same role and is even better.
Re: (Score:2)
The suposed problem you are referring to (ZFS reliability on cheap USB hardware which ignores cache flushes) was in fact well known, and easily fixed. It just took a long time, as no one sane would run ZFS on USB hardware to start with. All Apple proved was that their engineers had a very shallow understanding of ZFS.
Re: (Score:2)
All Apple proved was that their engineers had a very shallow understanding of ZFS.
I wouldn't say that - they have an independent company now continuing the project and many people like it.
Steve Jobs killed the project because Jonathan Schwartz blabbed to the press that Apple was going to embrace it, and nobody punks Steve Jobs, or ELSE!
Re: (Score:2)
Apple doesn't have a filesystem strategy today. They have had this problem since OSX 10.5. Steve Jobs might have an ego about getting punked, but he wasn't crazy.
Re: (Score:2)
Apple supposedly had problems with their internal drives, where it mattered. As for shallow understanding of ZFS they hired several of the world's leading experts on it for their port.
Re: (Score:2)
But Oracle's BTRFS plays the same role and is even better.
Wow, you haven't deployed either of them at scale, have you?
There's still frequent data corruption going in btrfs land and you'll be in for major pain if you try to host a VM storage file on it. They did recently fix the abysmal fsync performance, which is good, and a cursory fsck is available now. The kernel folks are still figuring out how to do cache devices in the dm stack and send/receive are still experimental.
The benefits to btrfs being what
Re: (Score:2)
Wow, you haven't deployed either of them at scale, have you?
Nope, parroting other's opinions.
Since Oracle is still selling ZFS, it would be hard to see why they would put significant resources into creating a free alternative at this point.
AFAIK BTRFS is better for Oracle and more feature rich. Ultimately it is not to Oracle's advantage that Z-OS, I-OS (the IBM one) and AIX are the OSes for very large storage. That's how they could lose to DB2 / Netezza.
Re: (Score:2)
Re: (Score:2)
Maybe if Sun and Motorola had merged, and made a good Solaris/Java-based phone/tablet platform?
Re: (Score:2)
Of course they could spend their money on any number of products that they want to keep out of competitors hands. Now, I'm the farthest thing you can be from a businessperson, but even I find it hard to imaging that it's a good practice to do this. Wasting tons of money on something just so the other guys don't get it just seems... wasteful.
Of course, even Google has succumbed to wasting large sums of cash on patents and the like, so perhaps they're not as smart as we hoped....
Touch down for common sense! (Score:2)
And, while the Android method and class names could have been different from the names of their counterparts in Java and still have worked, copyright protection never extends to names or short phrases as a matter of law.
That's it. Who disagrees?
Re:Touch down for common sense! (Score:5, Informative)
"Droid" is a valid Trademark vs. "GetCurrentTime()" being an invalid Copyright.
Re: (Score:2, Informative)
Trademark's not the same as copyright derp.
Try again.
Ann Droid vs technical documentation (Score:4, Insightful)
Oracle kicks off its legal arguments with the tale of a mythical writer, Ann Droid who copies the titles and some sentences from a Harry Potter book and publishes her book. Oracle then argues that we would not accept that.
BUT, API's should rather be compared with writing an anatomy book. We all would have chapters like 'Introduction, digestive tract, neural system etc.'. So if the argument of Oracle hold, no_one_can write another anatomy book (or most technical books).
Dictionary (Score:3)
Re: (Score:2)
A glimpse into the world as seen by Larry Ellison
If I were Daniel Webster, I'd be kicking myself for not trying to copyright English....
Re: (Score:2)
The BBC [wikia.com] should sue Oracle.
Looks like a win for progress (Score:2)
Re: (Score:2)
Does this mean... (Score:2)
Does this mean that mono is protected from Microsoft's
.net in the same way? Not trolling, just seriously asking.
Re: (Score:2)
doubt it, Microsoft never asserted copyright claims to the
.NET API words, they do however claim to have a shed-load of patents that they won't use against mono should be become successful, honest.
Patent law being a lot more screwed than copyright law is, I wouldn't count on it.
Trademark (Score:2)
Why didn't Oracle sue over the Trademark instead? It worked for Sun against Microsoft.
Re: (Score:2)
Why didn't Oracle sue over the Trademark instead? It worked for Sun against Microsoft.
Google was careful to not call it Java.
oracle can't see the future (Score:3)
Re: (Score:3)
Don't despair. All the lawyers got paid a few metric assloads of loot. That's trickle-down economics in action. Working for the people.
Re: (Score:2)
Perhaps to the standards of ordinary people. However the real metric assloads of loot come from settlements in class action suits.
Re:Oracle is based on copyright violations then... (Score:4, Informative)
Just in case anyone believes this:
Oracle founded 1977
DB2 first version 1983
Re: (Score:2)
R was a research application it wasn't commercial. Oracle was very very different. There wasn't any code in common. | https://developers.slashdot.org/story/13/03/31/162230/oracle-clings-to-java-api-copyrights | CC-MAIN-2017-43 | refinedweb | 6,463 | 71.95 |
Created on 2004-05-02 12:51 by wrobell, last changed 2006-02-20 11:59 by georg.brandl. This issue is now closed.
Python adds magically directory of sys.argv[0] into
sys.path, i.e.
>>> import sys
>>> sys.path
['', '/usr/lib/python23.zip', '/usr/share/python2.3',
'/usr/share/python2.3/plat-linux2',
'/usr/share/python2.3/lib-tk',
'/usr/lib/python2.3/lib-dynload',
'/usr/lib/python2.3/site-packages',
'/usr/lib/python2.3/site-packages/gtk-2.0',
'/usr/share/python2.3/site-packages']
where '' (or /usr/bin when executed script is in
/usr/bin directory, etc.) is added automatically.
It is useful in many circumstances but fails when name
conflict occurs.
For example, create getpass.py or pdb.py scripts which
import getpass and pdb modules. Script names conflict
with modules names and modules
are not going to be imported because path to the
scripts is appended
into sys.path, so a script is imported instead of a module.
The solutions:
1. User of script with conflicting name (i.e.
getpass.py or timeit.py)
can set PYTHONPATH to system library path, i.e.
/usr/lib/python2.3.
2. User can modify the script to delete site.path[0].
3. User can rename the script.
4. Python can be modified to not add magically
directory of sys.argv[0].
The 1. is a tricky and not intuitive and quite funny:
set PYTHONPATH to system library path to import system
module (and only in
specific circumstances). ;-P
The 2. is a dirty hack: hey, we gonna import system
module, ain't it?
The 3. is, IMHO, not acceptable because there is more
than 200 python system modules, more in the future and
user cannot be forced to maintain script names blacklist.
The 4. is only acceptable, IMHO. It makes python more
inconvenient
but gives no trouble when names conflict occurs.
Moreover, fourth
solution makes python more standard with other languages
behaviour, i.e. one has to set CLASSPATH to load Java
classes.
Maybe there is another solution, but...
Patch attached.
Logged In: YES
user_id=971153
Would not this cause serious backward compatibility problems??
Logged In: YES
user_id=29957
I've been bitten by this before. See e.g. the shtoom.py
script clashing with the shtoom package. I used the hacky
approach of moving '' to the end of sys.path. While it would
be nice if this wasn't needed, I can't see this being
anything other than a backwards compatibility nightmare. It
will absolutely break a lot of things to change it.
Logged In: YES
user_id=341410
This "problem" will be fixed in Python 2.4 with the
introduction of absolute and relative import semantics as
given in PEP 328:
As stated in the PEP, to use the obviously backwards
incompatible semantics, the future import will be used for
2.4 and 2.5, where in 2.6 it will become the default.
from __future__ import absolute_import
Logged In: YES
user_id=469548
wrobell, would you be willing to produce a version of the
patch which implements PEP 328? I'll close this patch if not.
Logged In: YES
user_id=387193
i will not provide the patch for 328, so closing this issue
Logged In: YES
user_id=387193
I am opening it again to discuss it a little more...
Question to Josiah Carlson or anybody who can answer:
How PEP 328 is going to solve problem I have described?
If I name my script email.py, which will try to import email
standard Python
package. Then run the script, it will import itself instead
of Python package,
because directory where email.py is installed is added to
sys.path.
Logged In: YES
user_id=341410
If the entirety of PEP 328 made it into Python 2.4 (I don't
have an installation of 2.4, so don't know), to import your
'email.py' module, you would use 'from . import email' after
enabling the absolute import semantics with 'from __future__
import absolute_import'. You would then import the standard
Is this not clear by reading PEP 328?
Logged In: YES
user_id=387193
But the problem is not with naming of my modules/packages
(part about relative import of modules I do understand, of
course), but with script naming.
For example consider script:
#!/usr/bin/python
import email
print 1
And name the script email.py, then run it, please. Python
tries to be too smart (IMHO) and variable sys.path is
polluted with directory of email.py script, therefore
standard email Python package will not be imported.
Logged In: YES
user_id=341410
If you were to make your 'email.py' file contain the
following...
#!/user/bin/python
from __future__ import absolute_import
import email
print 1
It should import the email package.
Logged In: YES
user_id=92689
That doesn't follow at all. The script email.py will _still_ be found first instead
of the email module. Like wrobell, I don't see what this has _anything_ to do
with relative vs. absolute imports.
While a common newbie gotcha, I don't think it's worth the trouble to try to
"fix" this. Recommending "won't fix".
Logged In: YES
user_id=113328
Another point - given a program which comprises a couple of
.py files in the same directory (say main.py and support.py)
it would be quite normal (at least for me!) to do "import
support" from main.py. This patch would break this - and I'd
find it difficult to accept what I'm doing as "a mistake".
Fixing this would involve adding something like
sys.path.insert(0,
os.path.dirname(os.path.abspath(sys.argv[0]))
at the top of my main script. I'd hate to try to explain
that to a beginner...
The use case here seems to be when a script itself has the
same name as a standard library module. I'd have to say that
this seems a fairly unlikely case - and easy to fix when it
happens.
Logged In: YES
user_id=387193
I do understand that the patch will not be accepted. :-)
That's ok. Too much fight with people's habits for me. :]
But, let's see what common script names are forbidden now
(among others):
array.py, binascii.py, bz2.py, collections.py, crypt.py,
datetime.py, math.py, md5.py, mmap.py, parser.py, pwd.py,
regex.py, resource.py, select.py, sha.py, syslog.py,
time.py, timing.py, timeit.py, binhex.py, calendar.py,
cgi.py, chunk.py, cmd.py, code.py, commands.py,
compileall.py, compiler.py, copy.py, csv.py, decimal.py...
And in the future there can be even more depending on the
new modules in Python itself and third party modules (i.e.
spread.py, dbus.py, eca.py, etc.). If new module or package
appears, then you will have to change your name of the
script. I do understand that it is not frequent situation,
but we should not to be forced to avoid certain
_common_ words for script naming.
IMHO, it is a problem and should be fixed. The question is
"How?".
Maybe page listed below should be discussed (again I think):
I would set Resolution to "Remind" if you agree to discuss
it later and fix the problem somehow in the future. If not,
then "Won't fix".
Logged In: YES
user_id=341410
I'm sorry, the bit I quoted shouldn't go into your email.py
file, it should go into the module that wants to import
Python's email package, and not your email.py module (my
brain was fuzzy on the 16th).
Standard library name masking is exactly what the absolute
imports PEP was seeking to fix. You use "from __future__
import absolute_imports", and from then on, you can do
relative imports via "import .modulename" (note the leading
period), and stdlib imports via "import modulename" (note
the lack of a leading period). It also allows you to go
higher up in paths via additional leading periods.
This /does/ in fact fix the problem mentioned, at the cost
of having to change the import lines because of the changed
import semantic. This allows users to choose names that
they desire, even if it mirrors a standard library module name.
It also doesn't require any patches.
Logged In: YES
user_id=92689
> Standard library name masking is exactly what
> the absolute imports PEP was seeking to fix
Only in the context of submodule imports within packages. Which is _not_ at
_all_ what is being described here. There is a main _script_ called email.py
which wants to import the email module (that email happens to be a package
is not relevant). There is _no_ relative import going on here, it just so
happens that the script's parent dir is in sys.path before the std lib.
Logged In: YES
user_id=341410
Absolute imports will also fix that. A bare "from
__future__ import absolute_imports;import email" will import
the email package, at the cost of changing the semantics of
relative imports. What is the problem? Why cannot it be
used? What in this entire problem is not solved by absolute
imports with its changed import semantic that already exists
in Python 2.4?
Logged In: YES
user_id=6656
> Absolute imports will also fix that.
No it won't! The directory containing email.py is on sys.path, at the front.
So "import email" will find it.
> What in this entire problem is not solved by absolute
> imports with its changed import semantic that already exists
> in Python 2.4?
Nothing at all is solved by a change that isn't in Python 2.4!
I still think this bug should be closed won't fix.
Logged In: YES
user_id=341410
A literal reading of "Guido's Decision" in PEP 328 says that
if absolute imports were implemented, then the only thing
missing is a future import, and an __init__.py file in the
same path as email.py.
I finally got around to installing 2.4, and (unfortunately)
it seems as though absolute_import is not offered in the
__future__ module. What happened? I thought PEP 328 was
accepted for inclusion in 2.4. Did someone not have the
time to write the import hook?
Logged In: YES
user_id=6656
> A literal reading of "Guido's Decision" in PEP 328 says that
> if absolute imports were implemented, then the only thing
> missing is a future import, and an __init__.py file in the
> same path as email.py.
I don't think this __init__.py file had been mentioned before. However,
even if it is there, THE DIRECTORY CONTAINING email.py IS ON
sys.path! What's hard to understand about this?
> I finally got around to installing 2.4, and (unfortunately)
> it seems as though absolute_import is not offered in the
> __future__ module. What happened?
It's awaiting an implementation, AFAIK.
Logged In: YES
user_id=341410
It's not hard to understand, but I could have sworn that in
the discussion about absolute imports from the spring of
last year that it wasn't just a package thing, it was
supposed to functionally do-away with "" being in sys.path
for all modules in which the future import had been performed.
It seems as though I was mistaken as to the reasons behind
the PEP, but can you blame me? A single mechanism for
handling stdlib vs. non-stdlib imports would be great (I
would say should be the one true solution), and would solve
the 10/week questions about imports in comp.lang.python.
Logged In: YES
user_id=971153
Seems like the main motivation for the original patch was to
prevent accidental conflicts between user's and standard
module names
Would emitting a warning (with an easy way to explicitly
suppress it) in such a case solve the original problem?
I am not sure whether such a warning should be limited to
user/system name conflicts or to any module name conflicts?
Logged In: YES
user_id=849994
This is too problematic to change the behavior. Closing as
"Won't fix", the consensus of the comments. | https://bugs.python.org/issue946373 | CC-MAIN-2019-30 | refinedweb | 2,022 | 75.91 |
Contents
Rationale and Goals
Python allows for a variety of stream-like (a.k.a. file-like) objects that can be used via read() and write() calls. Anything that provides read() and write() is stream-like. However, more exotic and extremely useful functions like readline() or seek() may or may not be available on every stream-like object. Python needs a specification for basic byte-based I/O streams to which we can add buffering and text-handling features.
Once we have a defined raw byte-based I/O interface, we can add buffering and text handling layers on top of any byte-based I/O class. The same buffering and text handling logic can be used for files, sockets, byte arrays, or custom I/O classes developed by Python programmers. Developing a standard definition of a stream lets us separate stream-based operations like read() and write() from implementation specific operations like fileno() and isatty(). It encourages programmers to write code that uses streams as streams and not require that all streams support file-specific or socket-specific operations.
The new I/O spec is intended to be similar to the Java I/O libraries, but generally less confusing. Programmers who don't want to muck about in the new I/O world can expect that the open() factory method will produce an object backwards-compatible with old-style file objects.
Specification
The Python I/O Library will consist of three layers: a raw I/O layer, a buffered I/O layer, and a text I/O layer. Each layer is defined by an abstract base class, which may have multiple implementations. The raw I/O and buffered I/O layers deal with units of bytes, while the text I/O layer deals with units of characters.
Raw I/O
The abstract base class for raw I/O is RawIOBase. It has several methods which are wrappers around the appropriate operating system calls. If one of these functions would not make sense on the object, the implementation must raise an IOError exception. For example, if a file is opened read-only, the .write() method will raise an IOError. As another example, if the object represents a socket, then .seek(), .tell(), and .truncate() will raise an IOError. Generally, a call to one of these functions maps to exactly one operating system call.
.read(n: int) -> bytesRead up to n bytes from the object and return them. Fewer than n bytes may be returned if the operating system call returns fewer than n bytes. If 0 bytes are returned, this indicates end of file. If the object is in non-blocking mode and no bytes are available, the call returns None.
.readinto(b: bytes) -> intRead up to len(b) bytes from the object and stores them in b, returning the number of bytes read. Like .read, fewer than len(b) bytes may be read, and 0 indicates end of file. None is returned if a non-blocking object has no bytes available. The length of b is never changed.
.write(b: bytes) -> intReturns number of bytes written, which may be < len(b).
.seek(pos: int, whence: int = 0) -> int
.tell() -> int
.truncate(n: int = None) -> int
.close() -> None
Additionally, it defines a few other methods:
.readable() -> boolReturns True if the object was opened for reading, False otherwise. If False, .read() will raise an IOError if called.
.writable() -> boolReturns True if the object was opened for writing, False otherwise. If False, .write() and .truncate() will raise an IOError if called.
.seekable() -> boolReturns True if the object supports random access (such as disk files), or False if the object only supports sequential access (such as sockets, pipes, and ttys). If False, .seek(), .tell(), and .truncate() will raise an IOError if called.
.__enter__() -> ContextManagerContext management protocol. Returns self.
.__exit__(...) -> NoneContext management protocol. Same as .close().
If and only if a RawIOBase implementation operates on an underlying file descriptor, it must additionally provide a .fileno() member function. This could be defined specifically by the implementation, or a mix-in class could be used (need to decide about this).
.fileno() -> intReturns the underlying file descriptor (an integer)
Initially, three implementations will be provided that implement the RawIOBase interface: FileIO, SocketIO (in the socket module), and ByteIO. Each implementation must determine whether the object supports random access as the information provided by the user may not be sufficient (consider open("/dev/tty", "rw") or open("/tmp/named-pipe", "rw")). As an example, FileIO can determine this by calling the seek() system call; if it returns an error, the object does not support random access. Each implementation may provided additional methods appropriate to its type. The ByteIO object is analogous to Python 2's cStringIO library, but operating on the new bytes type instead of strings.
Buffered I/O
The next layer is the Buffered I/O layer which provides more efficient access to file-like objects. The abstract base class for all Buffered I/O implementations is BufferedIOBase, which provides similar methods to RawIOBase:
.read(n: int = -1) -> bytesReturns the next n bytes from the object. It may return fewer than n bytes if end-of-file is reached or the object is non-blocking. 0 bytes indicates end-of-file. This method may make multiple calls to RawIOBase.read() to gather the bytes, or may make no calls to RawIOBase.read() if all of the needed bytes are already buffered.
.readinto(b: bytes) -> int
.write(b: bytes) -> intWrite b bytes to the buffer. The bytes are not guaranteed to be written to the Raw I/O object immediately; they may be buffered. Returns len(b).
.seek(pos: int, whence: int = 0) -> int
.tell() -> int
.truncate(pos: int = None) -> int
.flush() -> None
.close() -> None
.readable() -> bool
.writable() -> bool
.seekable() -> bool
.__enter__() -> ContextManager
.__exit__(...) -> None
Additionally, the abstract base class provides one member variable:
.rawA reference to the underlying RawIOBase object.
The BufferedIOBase methods signatures are mostly identical to that of RawIOBase (exceptions: write() returns None, read()'s argument is optional), but may have different semantics. In particular, BufferedIOBase implementations may read more data than requested or delay writing data using buffers. For the most part, this will be transparent to the user (unless, for example, they open the same file through a different descriptor). Also, raw reads may return a short read without any particular reason; buffered reads will only return a short read if EOF is reached; and raw writes may return a short count (even when non-blocking I/O is not enabled!), while buffered writes will raise IOError when not all bytes could be written or buffered.
There are four implementations of the BufferedIOBase abstract base class, described below.
BufferedReader
The BufferedReader implementation is for sequential-access read-only objects. Its .flush() method is a no-op.
BufferedWriter
The BufferedWriter implementation is for sequential-access write-only objects. Its .flush() method forces all cached data to be written to the underlying RawIOBase object.
BufferedRWPair
The BufferedRWPair implementation is for sequential-access read-write objects such as sockets and ttys. As the read and write streams of these objects are completely independent, it could be implemented by simply incorporating a BufferedReader and BufferedWriter instance. It provides a .flush() method that has the same semantics as a BufferedWriter's .flush() method.
BufferedRandom
The BufferedRandom implementation is for all random-access objects, whether they are read-only, write-only, or read-write. Compared to the previous classes that operate on sequential-access objects, the BufferedRandom class must contend with the user calling .seek() to reposition the stream. Therefore, an instance of BufferedRandom must keep track of both the logical and true position within the object. It provides a .flush() method that forces all cached write data to be written to the underlying RawIOBase object and all cached read data to be forgotten (so that future reads are forced to go back to the disk).
Q: Do we want to mandate in the specification that switching between reading and writing on a read-write object implies a .flush()? Or is that an implementation convenience that users should not rely on?
For a read-only BufferedRandom object, .writable() returns False and the .write() and .truncate() methods throw IOError.
For a write-only BufferedRandom object, .readable() returns False and the .read() method throws IOError.
Text I/O
The text I/O layer provides functions to read and write strings from streams. Some new features include universal newlines and character set encoding and decoding. The Text I/O layer is defined by a TextIOBase abstract base class. It provides several methods that are similar to the BufferedIOBase methods, but operate on a per-character basis instead of a per-byte basis. These methods are:
.read(n: int = -1) -> str
.write(s: str) -> int
.tell() -> objectReturn a cookie describing the current file position. The only supported use for the cookie is with .seek() with whence set to 0 (i.e. absolute seek).
.seek(pos: object, whence: int = 0) -> intSeek to position pos. If pos is non-zero, it must be a cookie returned from .tell() and whence must be zero.
.truncate(pos: object = None) -> intLike BufferedIOBase.truncate(), except that pos (if not None) must be a cookie previously returned by .tell().
Unlike with raw I/O, the units for .seek() are not specified - some implementations (e.g. StringIO) use characters and others (e.g. TextIOWrapper) use bytes. The special case for zero is to allow going to the start or end of a stream without a prior .tell(). An implementation could include stream encoder state in the cookie returned from .tell().
TextIOBase implementations also provide several methods that are pass-throughs to the underlaying BufferedIOBase objects:
.flush() -> None
.close() -> None
.readable() -> bool
.writable() -> bool
.seekable() -> bool
TextIOBase class implementations additionally provide the following methods:
.readline() -> strRead until newline or EOF and return the line, or "" if EOF hit immediately.
.__iter__() -> IteratorReturns an iterator that returns lines from the file (which happens to be self).
.next() -> strSame as readline() except raises StopIteration if EOF hit immediately.
Two implementations will be provided by the Python library. The primary implementation, TextIOWrapper, wraps a Buffered I/O object. Each TextIOWrapper object has a property named ".buffer" that provides a reference to the underlying BufferedIOBase object. Its initializer has the following signature:
.__init__(self, buffer, encoding=None, errors=None, newline=None, line_buffering=False)
buffer is a reference to the BufferedIOBase object to be wrapped with the TextIOWrapper.
encoding refers to an encoding to be used for translating between the byte-representation and character-representation. If it is None, then the system's locale setting will be used as the default.
errors is an optional string indicating error handling. It may be set whenever encoding may be set. It defaults to 'strict'.
newline can be None, '', '\n', '\r', or '\r\n'; all other values are illegal. It controls the handling of line endings.. (In other words, translation to '\n' only occurs if newline is None.)
-. (Note that the rules guiding translation are different for output than for input.)
line_buffering, if True, causes write() calls to imply a flush() if the string written contains at least one '\n' or '\r' character. This is set by open() when it detects that the underlying stream is a TTY device, or when a buffering argument of 1 is passed.
Further notes on the newline parameter:
- '\r' support is still needed for some OSX applications that produce files using '\r' line endings; Excel (when exporting to text) and Adobe Illustrator EPS files are the most common examples.
- If translation is enabled, it happens regardless of which method is called for reading or writing. For example, f.read() will always produce the same result as ''.join(f.readlines()).
- If universal newlines without translation are requested on input (i.e. newline=''), if a system read operation returns a buffer ending in '\r', another system read operation is done to determine whether it is followed by '\n' or not. In universal newlines mode with translation, the second system read operation may be postponed until the next read request, and if the following system read operation returns a buffer starting with '\n', that character is simply discarded.
Another implementation, StringIO, creates a file-like TextIO implementation without an underlying Buffered I/O object. While similar functionality could be provided by wrapping a BytesIO object in a TextIOWrapper, the StringIO object allows for much greater efficiency as it does not need to actually performing encoding and decoding. A String I/O object can just store the encoded string as-is. The StringIO object's __init__ signature takes an optional string specifying the initial value; the initial position is always 0. It does not support encodings or newline translations; you always read back exactly the characters you wrote.
Unicode encoding/decoding Issues
We should allow allow changing the encoding and error-handling setting later. The behavior of Text I/O operations in the face of Unicode problems and ambiguities (e.g. diacritics, surrogates, invalid bytes in an encoding) should be the same as that of the unicode encode()/decode() methods. UnicodeError may be raised.
Implementation note: we should be able to reuse much of the infrastructure provided by the codecs module. If it doesn't provide the exact APIs we need, we should refactor it to avoid reinventing the wheel.
Non-blocking I/O
Non-blocking I/O is fully supported on the Raw I/O level only. If a raw object is in non-blocking mode and an operation would block, then .read() and .readinto() return None, while .write() returns 0. In order to put an object in non-blocking mode, the user must extract the fileno and do it by hand.
At the Buffered I/O and Text I/O layers, if a read or write fails due a non-blocking condition, they raise an IOError with errno set to EAGAIN.
Originally, we considered propagating up the Raw I/O behavior, but many corner cases and problems were raised. To address these issues, significant changes would need to have been made to the Buffered I/O and Text I/O layers. For example, what should .flush() do on a Buffered non-blocking object? How would the user instruct the object to "Write as much as you can from your buffer, but don't block"? A non-blocking .flush() that doesn't necessarily flush all available data is counter-intuitive. Since non-blocking and blocking objects would have such different semantics at these layers, it was agreed to abandon efforts to combine them into a single type.
The open() Built-in Function
The open() built-in function is specified by the following pseudo-code:
def open(filename, mode="r", buffering=None, *, encoding=None, errors=None, newline=None): assert isinstance(filename, (str, int)) assert isinstance(mode, str) assert buffering is None or isinstance(buffering, int) assert encoding is None or isinstance(encoding, str) assert newline in (None, "", "\n", "\r", "\r\n") modes = set(mode) if modes - set("arwb+t") or len(mode) > len(modes): raise ValueError("invalid mode: %r" % mode) reading = "r" in modes writing = "w" in modes binary = "b" in modes appending = "a" in modes updating = "+" in modes text = "t" in modes or not binary if text and binary: raise ValueError("can't have text and binary mode at once") if reading + writing + appending > 1: raise ValueError("can't have read/write/append mode at once") if not (reading or writing or appending): raise ValueError("must have exactly one of read/write/append mode") if binary and encoding is not None: raise ValueError("binary modes doesn't take an encoding arg") if binary and errors is not None: raise ValueError("binary modes doesn't take an errors arg") if binary and newline is not None: raise ValueError("binary modes doesn't take a newline arg") # XXX Need to spec the signature for FileIO() raw = FileIO(filename, mode) line_buffering = (buffering == 1 or buffering is None and raw.isatty()) if line_buffering or buffering is None: buffering = 8*1024 # International standard buffer size # XXX Try setting it to fstat().st_blksize if buffering < 0: raise ValueError("invalid buffering size") if buffering == 0: if binary: return raw raise ValueError("can't have unbuffered text I/O") if updating: buffer = BufferedRandom(raw, buffering) elif writing or appending: buffer = BufferedWriter(raw, buffering) else: assert reading buffer = BufferedReader(raw, buffering) if binary: return buffer assert text return TextIOWrapper(buffer, encoding, errors, newline, line_buffering) | http://www.python.org/dev/peps/pep-3116/ | crawl-002 | refinedweb | 2,737 | 56.25 |
Stateful Movie object (a special kind of sprite) More...
#include <SWFMovie.h>
Stateful Movie object (a special kind of sprite)
The tasks of the Movie include: 1. Keep a 'dictionary' of parsed characters. This is a container of characters defined in previous frames. It acts like a genuine runtime dictionary of characters, although Gnash actually stores the definitions in the SWFMovieDefinition as it is parsed.
Add a character to the list of known characters.
This makes the character known to ActionScript for initialization. Exported characters must both be in the definition's list of exports and added with this function before they are available. If a duplicated character is added, it will not be marked uninitialized, as SWF::DoInitAction tags are only executed once for each id.
Reimplemented from gnash::Movie.
Advance to the next frame of the MovieClip.
Actions will be executed or pushed to the queue as necessary.
Implements gnash::Movie.
References gnash::MovieClip::get_current_frame(), gnash::MovieClip::get_frame_count(), IF_VERBOSE_MALFORMED_SWF, and _.
Handle a top-level movie on stage placement.
This method will just ensure first frame is loaded and then call MovieClip::construct
It's intended to be called by movie_root::setLevel().
Reimplemented from gnash::MovieClip.
References gnash::DisplayObject::saveOriginalTarget(), IF_VERBOSE_MALFORMED_SWF, _, and gnash::MovieClip::get_frame_count().
Reimplemented from gnash::Movie.
Get an exported character definition by its symbol name.
The character is only available after the ExportAssets tag has been executed.
Reimplemented from gnash::Movie.
Attempt to mark a character as initialized.
A character can be initialized once, but only after it is known to this Movie.
Reimplemented from gnash::Movie.
References IF_VERBOSE_MALFORMED_SWF, and _.
Get the URL of the SWFMovie's definition.
Implements gnash::Movie.
Get the version of the SWFMovie.
Implements gnash::Movie. | https://www.gnu.org/software/gnash/manual/doxygen/classgnash_1_1SWFMovie.html | CC-MAIN-2021-25 | refinedweb | 287 | 53.17 |
I noticed in the TortoiseSVN interface that there is a
"switch" repository command. What about using that? I
don't know what the command line equivalent would be,
but that should be able to let him do what he wants,
no? E.g. The following:
- Do work on repo
- Commit to repo
- Make release
- switch to alternate repo
- Make release
- switch back to primary repo
I think the only issue would be that the alternate
repo would have to have the same layout as the primary
repo. But you should be able to get that if you (a)
exported a release and made that the import of the
alternate's trunk, and (b) committed to the trunk of
the alternate and then made a release from the
alternate.
The process might get a little more muddy depending on
how well the tools handle the merging and such. At
worse case, you might have to check out your release
into a separate directory before doing the switch
process.
FYI - I am not 100% sure this will work - more like
25-50% sure. And wouldn't try it unless someone else
confirmed my line of thought; at least, not in your
normal WC with anything important.
The other alternative of just doing the export and
import into a branch on a separate repo will likely be
cleaner and easier to do though.
Just a thought & 2 cents for the pot.
BRM
--- Steve Greenland <steveg@lsli.com> wrote:
> On Mon, Jan 31, 2005 at 04:00:06PM +0000, abcd
> wrote:
> > --- Petr Smr??ka <smrcka@1sig.cz> wrote:
> > > There will be a trunk of the project accessible
> to
> > > your client
> >
> > That's precisely what I don't want to happen. The
> > client does not (and should not and will never)
> have
> > the visibility of my machines. Is your procedure
> > applicable even in the case of a completely
> > independent repository i.e., one residing on a
> remote
> > machine?
>
> In that case, I think you're stuck with the
> following model:
>
> - In your repo, on the trunk, hack hack hack.
>
> - Create a release for you client by copying to tag.
> (Or merge into
> client branch, or whatever is appropriate.)
>
> - Export the tag.
>
> - Import the export into client repo.
>
> Of course, by doing this, not much is gained by them
> having their own
> repo; you might as well give a tarball. Hmmm, I
> suppose them having a
> repo might make it easier to preview changes,
> revert, etc.
>
> Ahhh, the other approach might be SVK, which does
> support merging
> between repositories. But all I know about SVK I
> read on the web:
>
>
> 31 18:24:31 2005
This is an archived mail posted to the Subversion Users
mailing list. | https://svn.haxx.se/users/archive-2005-01/1948.shtml | CC-MAIN-2019-39 | refinedweb | 451 | 71.44 |
11335/npm-hfc-0-6-2-not-properly-installing
how to solve this problem.
I run this commands make node-sdk on hyperledger/fabric folder (with sudo or without), still i am getting the same errors.
npm WARM hfc@0.6.2 license should be a valid SPDX license expression log file
this is harmless, the hfc module should still work despite the warning. By the way, if you are still developing with Hyperledger Fabric, there's a v1.0 release now. Checkout the details at hyperledger-fabric.readthedocs.io/en/latest/
The answer is
let a=web3.personal.newAccount('!@superpassword')
Ho ...READ MORE
You have to first install nodejs and ...READ MORE
You need root access to install truffle, ...READ MORE
Are you running this command from the ...READ MORE
Summary: Both should provide similar reliability of ...READ MORE
The Hyperledger Composer pre-requisites can be installed ...READ MORE
This will solve your problem
import org.apache.commons.codec.binary.Hex;
Transaction txn ...READ MORE
Meet the lib sodium fails. You're using
node ...READ MORE
The bluemix service was using an older ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/11335/npm-hfc-0-6-2-not-properly-installing?show=11341 | CC-MAIN-2019-47 | refinedweb | 193 | 62.85 |
Say I'm given n=32. I want to know what log_2(n) is.
In this case, log_2(32) = 5.
What is the fastest way in general to compute the log of a 2^k number?
I.e.
Given n = 2^k.
log_2(n) = b.
Find b.
Bitwise operations are permitted.
This page gives a half-dozen different ways to do that in C; it should be trivial to change them to C#. Try them all, see which is fastest for you.
However, I note that those techniques are designed to work for all 32 bit integers. If you can guarantee that the input is always a power of two between 1 and 2^31 then you can probably do better with a lookup table. I submit the following; I have not performance tested it, but I see no reason why it oughtn't to be pretty quick:
static int[] powers = new[] {0, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4, 7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5, 20, 8, 19, 18}; static int Log2OfAPower(int x) { return powers[((uint)x) % 37] }
The solution relies upon the fact that the first 32 powers of two each have a different remainder when divided by 37.
If you need it to work on longs then use 67 as the modulus; I leave you to work out the correct values for the array.
Commenter LukeH correctly points out that it is bizarre to have a function that purportedly takes the log of a negative number (
1<<31 is a negative signed integer.) The method could be modified to take a uint, or it could be made to throw an exception or assertion if given a number that doesn't meet the requirements of the method. Which is the right thing to do is not given; the question is somewhat vague as to the exact data type that is being processed here.
CHALLENGE:
Hypothesis: The first n powers of two each have a different modulus when divided by p, where p is the smallest prime number that is larger than n.
If the hypothesis is true then prove it. If the hypothesis is false then provide a counter-example that demonstrates its falsity.
I think that if you guarantee that
n will be a power of 2, a quick way to find
b would be by converting
n to a binary string and finding the index of 1. Special consideration for case when
n = 0
using System.Linq; ... var binaryStringReversed = Convert.ToString(value, 2).Reverse(); var b = binaryStringReversed.IndexOf("1");
EDIT:
var b = Convert.ToString(value, 2).Length - 1; | http://m.dlxedu.com/m/askdetail/3/a594edb86fb807971d72c28a6a78c981.html | CC-MAIN-2018-30 | refinedweb | 452 | 69.62 |
How to Determine Total Returns from Bonds or Bond Fund Investments
Total return is the entire pot of money you wind up with after an investment period has come and gone. Bonds or bond funds involve your interest and any changes in the value of your original principal. Ignoring for the moment the risk of default (and losing all your principal), here are other ways in which your principal can shrink or grow.
Figuring in capital gains and losses on your bond investment
In the case of a bond fund, your principal is represented by a certain number of shares in the fund multiplied by the share price of the fund. As bond prices go up and down (usually in response to prevailing interest rates), so will the share price of the bond fund go up and down.
Because of bond volatility, the share price of a bond fund may go up and down quite a bit, especially if the bond fund is holding long-term bonds, and doubly-especially if those long-term bonds are of questionable quality (junk bonds).
In the case of individual bonds, your principal will come back to you whole — but only if you hold the bond to maturity or if the bond is called. If, on the other hand, you choose to sell the bond before maturity, you’ll wind up with whatever market price you can get for the bond at that point.
If the market price has appreciated (the bond sells at a premium), you can count your capital gains as part of your total return. If the market price has fallen (the bond sells at a discount), the capital losses will offset any interest you’ve made on the bond.
Factoring in reinvestment rates of return on bonds — will probably be the most important of the three! That’s because of the amazing power of compound interest.
Allowing for inflation adjustments
Your truest total rate of return needs to account for inflation. To account for inflation when determining the real rate of return on an investment, you can simply take the nominal rate of return (perhaps 5 or 6 percent) and subtract the annual rate of inflation (which has been about 3 percent in recent years). That will give you a rough estimate of your total real return.
Weighing pre-tax versus post-tax bond returns
Taxes almost always eat into your bond returns..) | http://www.dummies.com/how-to/content/how-to-determine-total-returns-from-bonds-or-bond-.navId-323658.html | CC-MAIN-2015-18 | refinedweb | 403 | 63.32 |
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
7 years, 4 months ago.
HW implementation of SPI, I2C, Serial in mbed
Hello all,
I am new to the mbed compiler. I've noticed that with mbed library it is really easy to setup and use SW implementation of SPI, I2C and Serial.
I'd like to go further and use HW resources as those are there just for using them. I know that usage of HW resources is device-specific, but if we have certain set of mbed enabled devices we could implement libraries for each board separately.
Is it the only way for me to write my own lib for that HW interfaces or there is something already out there I haven't found yet?
Does anybody prepared such a library (any of mentioned IF) already so I could see it for reference?
best regards
1 Answer
7 years, 4 months ago.
These are all hardware implementations, which is why it only works on specific pins. The mbed library only adds an abstraction layer on top of it to use the same API for different devices. Of course this won't be as efficient as a direct implementation for your specific device. There are examples of such implementations on the site, but they also generally use some form of abstraction to simplify using them.
For SPI and Serial there are btw real software implementations which can work on any pin. I don't think there is one for I2C.
So as I understand mbed library implements SW interfaces without use of HW resources - right? If I am able to specify any of the pin in Serial pc(pX_a, pX_b, ...) it means that it is pure bit banging. If I would use for example Serial pc(MBED_SPI0) defined in PeripheralNames.h then i would think it might be implementation which uses HW resources because of well defined pins...
Do I understand it correctly?posted by 08 Jul 2014
The standard mbed library is only ever a HW implementation. If you try to enter
#include <mbed.h> Serial pc(p1,p20);
then it will compile but crash on start up and output an error message indicating invalid pins on the USB serial port. (unless your target device happens to have a hardware serial port on those pins)
If you wish to use a software implementation then you need to use a different library e.g. is an SPI interface which is pure SW and will work on any pins.posted by 08 Jul 2014
In addition to Andy's post, on the cookbook there are a bunch of software implementations for different peripherals:, but this is not the standard one.
If you look at the platform page for your target, for example:, you see that you can only do Serial, SPI, etc on a limitted number of pins, because it is a real hardware implementation.
What the mbed library does is map the pins you supply to a hardware peripheral. If that is not possible it will return an error. This is also required since pretty much every ARM microcontroller has several pinmap options for a single peripheral. So just defining the peripheral would not be enough to know which pins it should use, but defining which pins it should use is enough to define the peripheral it should use.posted by 08 Jul 2014 | https://os.mbed.com/questions/4004/HW-implementation-of-SPI-I2C-Serial-in-m/ | CC-MAIN-2021-49 | refinedweb | 584 | 63.09 |
/*************************************************** This ****************************************************/// this works, but needs copying to .../Arduino/libraries//#include <GTFT_IO.h>//#include <Adafruit_GTFT_ILI9341.h>// this does not compile with my Arduino 1.6.10//#include "GTFT_IO/GTFT_IO.h"//#include "Adafruit_GTFT_ILI9341/Adafruit_GTFT_ILI9341.h"// this does also not compile with my Arduino 1.6.10#include "GTFT_IO\GTFT_IO.h"#include "Adafruit_GTFT_ILI9341\Adafruit_GTFT_ILI9341.h"GTFT_IO_SPI9 GTFT_IO(D4);// For the Adafruit shield, these are the default.#define TFT_DC D4#define TFT_CS D8// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DCAdafruit_GTFT_ILI9341 tft(TFT_CS, TFT_DC, -1, >FT_IO);
Example:#include "mysubdir\mylibrary,h"
#include "src/BlinkLib/BlinkLib.h"
In recent versions of the Arduino IDE(including 1.6.10) if you want to include libraries from the sketch folder you need to put them in a src subfolder. For example:Blink|_Blink.ino|_src |_BlinkLib |_BlinkLib.hCode: [Select]#include "src/BlinkLib/BlinkLib.h"
Since you clearly didn't write the libraries that you are using, why are they not in the libraries folder?
It seems .cpp files don't get added.
They do if the header file is included in your sketch. Sounds to me like you are trying to hide the use of a library. THAT is not allowed. | https://forum.arduino.cc/index.php?topic=445230.0 | CC-MAIN-2020-10 | refinedweb | 200 | 68.87 |
With Python there's always a lot of libraries and options for solving any particular problem and running scheduled or recurring jobs is no exception. Whether you want to run simple deferred task, bunch of scheduled jobs or manage cron tabs, there's specialized library for that in Python. So, in this article I will give you an overview of all the options available to help you choose the right tool for the task at hand, as well as their use cases, including intro and basic examples to get you started quickly!
The Builtin Solution
Before exploring any external libraries, let's first check what we have in Pythons standard library. Most of the time, Python standard library will contain solution to whatever problem you might have and if the problem is running deferred jobs like with Linux
at command, then grabbing
sched module might be the way to go.
sched is a very simple module, which can be used to schedule one-off tasks for some specified time - so, it's important to realise, that this is not recurring job (like cron job). It works on all platforms, which might seem obvious, but will not necessarily be the case with all the libraries shown later.
One of the use cases for such deferred task can be scheduled shutdown or if you are're working with network connections or firewall you can create one-time job to revert changes in case you mess up and lock yourself out of the system.
Enough talking, let's see an example:
import sched import threading import time scheduler = sched.scheduler(time.time, time.sleep) def some_deferred_task(name): print('Event time:', time.time(), name) print('Start:', time.time()) now = time.time() # delay in seconds -----v v----- priority event_1_id = scheduler.enter(2, 2, some_deferred_task, ('first',)) event_2_id = scheduler.enter(2, 1, some_deferred_task, ('second',)) # If first 2 events run at the exact same time, then "second" is ran first event_3_id = scheduler.enter(5, 1, some_deferred_task, ('third',)) # Start a thread to run the events t = threading.Thread(target=scheduler.run) t.start() # Event has to be canceled in main thread scheduler.cancel(event_2_id) # Terminate the thread when tasks finish t.join() # Output: # Start: 1604045721.7161775 # Event time: 1604045723.718353 first # Event time: 1604045726.7194896 third
The code above defines scheduler, which is used to create (
.enter) events to be executed at later time. Each event (call to
.enter) receives 4 arguments, which are - delay in seconds (in how many seconds will the event happen?), priority, name of the function to be called and optional function arguments. The priority argument doesn't matter most of the time, but can be very important if 2 events are scheduled to happen at exactly the same time, yet they have to be executed sequentially. In that case, the event with highest priority (lowest number) goes first.
In this code snippet we can also see that
.enter method returns event ID. These IDs can be used to cancel events as demonstrated with
scheduler.cancel(event_2_id).
To not block the main thread of the program, we also used
threading.Thread to start the scheduler and called
.join() on it to gracefully terminate when it's done with all the tasks.
Full Power of Crontab
There's quite a few libraries for running recurring jobs using Python, but let's start with the one that gives you the full cron "experience". This library is called
python-crontab and can be installed with
pip install python-crontab.
python-crontab, unlike other libraries and modules listed here, creates and manages actual real crontabs on Unix systems and tasks on Windows. Therefore, it's not emulating behavior of these operating system tools, but rather leveraging them and using what's already there.
For an example here, let's see some practical use case. Common reason for running recurring tasks can be checking of status of database server. This can be generally done by connecting to and logging into database and running dummy query like
SELECT 1, just like so:
from crontab import CronTab # user=True denotes the current user cron = CronTab(user=True) job = cron.new(command='PGPASSWORD=test psql -U someuser -d somedb -c "SELECT 1" -h localhost') job.setall("*/5 * * * *") if cron[0].is_valid(): # If syntax is valid, write to crontab cron.write() # crontab -l # Check real crontab from shell # */5 * * * * PGPASSWORD=test psql -U someuser -d somedb -c "SELECT 1" -h localhost
As I previously mentioned,
python-crontab provides the real cron "experience", which includes the generally disliked cron syntax. To set the schedule, one uses
.setall method to set all the fields. Before setting the schedule however, we need to create the crontab using
CronTab() and specify the owning user. If
True is passed in, ID of user executing the program will be used. We also have to create an individual job (
.new()) in this crontab passing in
command to be executed and optionally also a
comment.
When we have the crontab and its job ready we need to write it, but it's good idea to check its syntax using
.is_valid() before we do so.
Another basic database admin task is creation of periodic backups, that can be also done easily with
python-crontab, this time with little different syntax:
with CronTab(user='root') as cron: # with context manager cron.write() is called automatically job = cron.new( command='PGPASSWORD=test pg_dump -U someuser -d somedb -h localhost --column-inserts --data-only > backup.sql', comment="Perform database backup" ) job.every(2).days() job.hour.on(1) # job.every_reboot() # job.hour.every(10) # job.month.during('JAN', 'FEB') # Powerful but confusing/hard to parse syntax # job.minute.during(15, 45).every(5) # crontab -l # 0 1 */2 * * PGPASSWORD=test pg_dump -U someuser -d somedb -h localhost --column-inserts --data-only > backup.sql # Perform database backup
If you're not super comfortable with cron syntax, this library also provides declarative syntax, which is shown in the example above. This syntax is in my opinion very confusing and even harder to read and use than normal cron syntax, so I'd recommend to stick with cron syntax or choose different library (see next section).
Apart from different syntax we can also see usage of Python context manager, which allows us to omit the
.write method shown previously. One more thing to keep in mind is, that if you decide to run cron jobs as
root user (not recommended), as shown above, then you will have to run the program with
sudo.
This library has also other useful features apart from basic creation and management of crontabs. One of them being listing and inspecting both user and system crontabs, as well as lookup based on criteria like command or comment of the specific job:
from crontabs import CronTabs for cron in CronTabs(): # Get list of all user and system crontabs if cron.user: print(f'{cron.user} has following cron jobs:') else: print(f'{cron.filen} has following cron jobs:') for job in cron.crons: print(f' {job.command}') # martin has following cron jobs: # PGPASSWORD=test psql -U someuser -d somedb -c "SELECT 1" -h localhost # PGPASSWORD=test pg_dump -U someuser -d somedb -h localhost --column-inserts --data-only > backup.sql # /etc/cron.d/anacron has following cron jobs: # [ -x /etc/init.d/anacron ] && if [ ! -d /run/systemd/system ]; then /usr/sbin/invoke-rc.d anacron start >/dev/null; fi # /etc/cron.d/popularity-contest has following cron jobs: # test -x /etc/cron.daily/popularity-contest && /etc/cron.daily/popularity-contest --crond # ... jobs = CronTabs().all.find_command('psql') # lookup for all jobs running specific command for job in jobs: print(job) # */5 * * * * PGPASSWORD=test psql -U someuser -d somedb -c "SELECT 1" -h localhost
As I mentioned in previous section, not all libraries shown here work exactly the same way on all platforms.
python-crontab works on Linux and Windows, but on Windows only user crontabs (Windows tasks) are supported.
If You Really Hate Cron Syntax
We've seen how to schedule job with declarative syntax with
python-crontab in previous section, but it wasn't really readable or user friendly. If you're looking for the most user friendly, most popular library with very simple interface, then
schedule is library for you.
schedule is based on an article Rethinking Cron which describes some of the cron problems and weaknesses and this library does a good job at solving them.
The biggest complaint with cron is definitely its terse and hard to write syntax, so let's see how
schedule addresses that:
import schedule def task(): return ... def task_with_args(value): return ... schedule.every(2).hours.do(task) schedule.every().sunday.at("01:00").do(task) schedule.every().hour.at(":15").do(task) schedule.every(15).to(30).seconds.do(task) # Randomly between every 15 to 30 seconds schedule.every().minute.do(task_with_args, "some value") # Grouping jobs with tags schedule.every().day.at("09:00").do(task).tag('daily', 'morning') schedule.every().day.at("18:30").do(task).tag('daily', 'evening') schedule.every().hour.do(task).tag('hourly') schedule.clear('daily-tasks') # No explicit "month" schedule # No explicit "range" (during 10-14h; from Jan to Mar) schedule
The first 5 scheduled jobs above don't really need much of an explanation. The code is very human-readable a quite self-explanatory. The interface only contains a few function for days (
.monday()) and times (
.seconds(),
.hours(), ...), which makes it very easy to use.
Apart from the simple scheduling, the interface contains also
.tag() method for grouping the jobs by tag. This can be useful for example for cancelling whole groups of jobs (with
.clear()).
One downside of having such simple interface is the lack of explicit month or range scheduling, e.g. scheduling jobs during 10-14h or from Jan to Mar isn't really possible.
Aside from recurring jobs, you can also use
schedule to run one-off tasks and achieve the same effect as with
sched, but with nicer syntax:
# Execute one-off (deferred job) def deferred_job(): # Do stuff... return schedule.CancelJob schedule.every().day.at('01:00').do(deferred_job) while True: schedule.run_pending() time.sleep(1) # To run in background -
Apart from the deferred job, this code snippet also shows that we need to keep the thread alive for the jobs to run. That's because this library doesn't create actual
cron or
at jobs. If you don't want to block the main thread of your program like in the example above, you can also run it in background as shown here.
All The Features You Might Ever Need
All the previously mentioned tools have their pros and cons, some specific features and design that makes them good for some specific use cases. If you, however need to run both deferred and periodic jobs, need to store jobs in database, need builtin logging features, etc., then most likely none of the above mentioned tools are going to cut it.
The most feature rich and powerful library for scheduling jobs of any kind in Python is definitely APScheduler, which stands for Advanced Python Scheduler.
It ticks all the boxes, when it comes to features mention above and these kind of features require extensive configuration, so let's see how APScheduler does it:
jobstores = { 'mongo': MongoDBJobStore(), # MongoDBJobStore requires PyMongo installed - `pip install pymongo` 'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite') # SQLAlchemyJobStore requires SQLAlchemy installed, Recommended to use PostgreSQL } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': False, 'max_instances': 3 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc, daemon=True) # Without daemonic mode, the main thread would exit. You can also keep it alive with infinite loop.
This code snippet shows sample configuration, which can be used to setup SQLite and MongoDB job stores, which house the scheduled jobs. It shows configuration of executors which handle running of jobs - here we specify the size of our pools. We also specify some job defaults, such as number of job instances that can run in parallel. All the configs are passed to scheduler, which is used to manage jobs.
def task(): return ... # trigger -> can also be 'cron' or 'date' # misfire_grace_time -> seconds after the designated runtime that the job is still allowed to be run # max_instances -> max number of concurrent instances scheduler.add_job(task, trigger='interval', seconds=5, misfire_grace_time=600, max_instances=5) # 'interval' trigger can take any args from scheduler.add_job(task, trigger='cron', month='jan-apr', day_of_week='mon-fri', hour=15, minute=30, end_date='2021-01-30') scheduler.add_job(task, CronTrigger.from_crontab('0 17 * * sat,sun')) # 'cron' trigger can take any args from # Simulates 'at' - deferred jobs scheduler.add_job(task, trigger='date', run_date=datetime(2020, 12, 24, 17, 30, 0)) # 'date' trigger can take any args from scheduler.print_jobs(jobstore="default") scheduler.start() # Pending jobs: # task (trigger: interval[0:01:00], pending) # task (trigger: cron[month='jan-apr', day_of_week='mon-fri', hour='15', minute='30'], pending) # task (trigger: cron[month='*', day='*', day_of_week='sat,sun', hour='17', minute='0'], pending) # task (trigger: date[2020-12-24 17:30:00 UTC], pending)
Next comes the creation of our jobs using
.add_job() method. It takes quite a few arguments, first of them being function to be ran. Next is the trigger type, which can be interval, cron or date. Interval schedules jobs to run periodically in said interval. Cron is just good old cron-like scheduler, which allows for classic and keyword argument-based scheduling arguments. Finally, date trigger create onetime jobs at specific date and time.
One more important argument to
.add_job() is
misfire_grace_time, which provides
anacron-like feature, or in other words - in case your job doesn't run because scheduler is down, scheduler will try to run it when it's back up, as long as the
misfire_grace_time hasn't been exceeded.
Scheduled jobs are generally annoying to debug. APScheduler tries to alleviate that with ability to easily configure logging levels as well an ability to add listeners to scheduler events - e.g. when job is executed or when job fails. You can see such listener and log sample log output below:
# Catching scheduler events: import logging logging.basicConfig(level=logging.INFO) def my_listener(event): if event.exception: logging.warning('Job failed...') else: logging.info('Job was executed...') scheduler.add_listener(my_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) # ... # INFO:apscheduler.scheduler:Scheduler started # INFO:apscheduler.executors.default:Running job "task (trigger: interval[0:00:05], next run at: 2020-10-30 09:51:11 UTC)" (scheduled at 2020-10-30 09:51:11.222311+00:00) # INFO:apscheduler.executors.default:Job "task (trigger: interval[0:00:05], next run at: 2020-10-30 09:51:16 UTC)" executed successfully # INFO:root:Job was executed...
For The Gevent Users
Last and maybe actually the least (desirable solution) is to use Gevent. Not because Gevent is bad, but because it isn't really built for running scheduled tasks. If you're, however already using Gevent in your application, it might make sense to use it to schedule jobs too.
If you aren't familiar with Gevent, then Gevent is a concurrency library based on coroutines. It uses Greenlets to provide pseudo-concurrency for running multiple tasks in single OS thread. For a better understanding, let's see a basic example:
# Plain Gevent without scheduler import gevent from gevent import monkey # patches stdlib (including socket and ssl modules) to cooperate with other greenlets monkey.patch_all() import requests # Note that we're using HTTPS, so # this demonstrates that SSL works. urls = [ '', '', '' ] def head_size(url): print(f'Starting {url}') data = requests.get(url).content print(f'{url}: {len(data)}') jobs = [gevent.spawn(head_size, _url) for _url in urls] gevent.wait(jobs) # Output: # Starting # Starting # Starting #: 14381 #: 50202 #: 42702
This example shows how we can query multiple URLs in parallel using Gevent and its
gevent.spawn. In the output above, you can see that all 3 jobs that were created started at the same(-ish) time and returned data later.
To perform the same task, but scheduled in the future, we can do the following:
# deferred job (one-off) def schedule(delay, func, *args, **kw_args): gevent.spawn_later(0, func, *args, **kw_args) gevent.spawn_later(delay, schedule, delay, func, *args, **kw_args) schedule(30, head_size, urls[0]) # periodic job # this will drift... def run_regularly(function, interval, *args, **kwargs): while True: gevent.sleep(interval) function(*args, **kwargs) run_regularly(head_size, 30, urls[0]) # Output: # Starting #: 14449 # 30 sec later... # Starting #: 14435 # ...
Above we can see both example for running one-off jobs as well as periodic ones. Both of these solutions are kind of a hack/trick and should only be considered if you're already using Gevent in your application. It's also important to mention that above
run_regularly function will slowly start to drift, even if we account for runtime of tasks. Therefore, you should preferably use
GeventSchedule available in APScheduler library instead, as it's a more robust solution.
Conclusion
Running deferred or periodic jobs is very general task and you won't find one library or tool that does it all perfectly, but I hope this article gave you a decent overview of what is available. Regardless of whichever tool you choose for your particular use case, it's important to keep in mind the more general best practices, like for example: add comments to your cron jobs for clarity, avoid using
root user (principle of least privilege), don't put passwords into your crontabs, etc. Also, if you're are going to use actual cron jobs, you might also want to leverage
/etc/cron.daily,
/etc/cron.weekly and
/etc/cron.mothly to keep things organized and tidy. Last but not least, looking into
anacrontab might also be useful if you need to ensure that your jobs will run even when the machine goes offline for a bit.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/martinheinz/scheduling-all-kinds-of-recurring-jobs-with-python-l74 | CC-MAIN-2021-17 | refinedweb | 2,960 | 55.44 |
Find the best tutors and institutes for C Language
Asked by Ishwari Prashant sidwadkar Last Modified
28 Answers
The basic structure of a C program is :
Preprocessor directives to include libraries required for execution of the program
Declaration of global variables and macros
main() function{
code ;
}
other function definitionsread less
The basic structure of a C program is :
Preprocessor directives to include libraries required for execution of the program
Declaration of global variables and macros
main() function{
code ;
}
other function definitions
1. math.h is a header file that is to be include in the program if functions like sqrt(), pow(), abs() sin() etc. are to be called.
2. string.h is a header file that includes various funcitons for working on strings. These include strlen(), strcmp(), strcat(), etc.read less
General form of c program is...
Global declarations
int main(parameter list)
{
statement sequence
}
return-type f1(parameter list)
{
statement sequence
}
return-type f2(parameter list)
{
statement sequence
}...
return-type fN(parameter list)
{
statement sequence
}
This form is mainly concerned with Functions and Declarations.
Significance of math.h file
math.h header files drives hundreds of maths functions along with one macro. This header file returns result as double and takes double as an argument.
Significance of string.h file
string.h header file drives string related functions . This header file defines any one variable type, one macro, and number of functions.
Basically header file contains Declarations, Definitions, and Macro of related number of functions which is defined in that particular header file.
Thanks
Regards
Mahesh v Kondawar
read lessread less
Following is the basic structure of a C program.
Documentation Consists of comments, some description of the program, programmer name and any other useful points that can be referenced later.
Link Provides instruction to the compiler to link function from the library function.
Definition Consists of symbolic constants.
Global declaration Consists of function declaration and global variables.
main( )
{
} Every C program must have a main() function which is the starting point of the program execution.
Subprograms User defined functions.
Lets explore the sections with an example.
Write a program to print area of a circle.
In the following example we will find the area of a circle for a given radius 10cm.
Formula
The formula to compute the area of a circle is πr2 where π is PI = 3.1416 (approx.) and r is the radius of the circle.
Lets write the C code to compute the area of the circle.
#include <stdio.h>
#define PI 3.1416
float area(float r);
int main(void)
{
float r = 10;
printf("Area: %.2f", area(r));
return 0;
}
float area(float r) {
return PI * r * r;
}
The above code will give the following output.
Area: 314.16
Different sections of the above code
Documentation
This section contains a multi line comment describing the code.
In C, we can create single line comment using two forward slash // and we can create multi line comment using /* */.
Comments are ignored by the compiler and is used to write notes and document code.
Link
This section includes header file.
#include <stdio.h>
We are including the stdio.h input/output header file from the C library.
Definition
This section contains constant.
#define PI 3.1416
In the above code we have created a constant PI and assigned 3.1416 to it.
The #define is a preprocessor compiler directive which is used to create constants. We generally use uppercase letters to create constants.
The #define is not a statement and must not end with a ; semicolon.
Global declaration
This section contains function declaration.
float area(float r);
We have declared an area function which takes a floating number (i.e., number with decimal parts) as argument and returns floating number.
main( ) function
This section contains the main() function.
int main(void)
{
float r = 10;
printf("Area: %.2f", area(r));
return 0;
}
This is the main() function of the code. Inside this function we have created a floating variable r and assigned 10 to it.
Then we have called the printf() function. The first argument contains "Area: %.2f" which means we will print floating number having only 2 decimal place. In the second argument we are calling the area() function and passing the value of r to it.
Subprograms
This section contains a subprogram, an area() function that is called from the main() function.
float area(float r) {
return PI * r * r;
}
This is the definition of the area() function. It receives the value of radius in variable r and then returns the area of the circle using the following formula PI * r * r.
The math.h header defines various mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result.
string.h is the header in the C standard library for the C programming language which contains macro definitions, constants and declarations of functions and types used not only for string handling but also various memory handling functions;read less
#include<stdio.h> //header file
main() // entry point for a program
{
// variables declaration
//logic which you want to achieve
}
math.h is a header file for working with mathmatical functions like abs() sum() etc..
string.h is also header file for working with string functions like strupr(),strlwr() etc..
without writing any manual code you can use these functions in your program for your purpose
ex: strlwr("nani") is automatically converted to "NANI" which is the outputread less
Hello Ishwari
We know we have already defined data types like int, char, float, double.
Let's take int
When we declare
int i ;
It simply means an area of 2 Bytes(architecture dependent) gets allocated and the area is named as i and as our houses get some address in a street, in the same manner, this area will also have an address.
Now if we want some area which must contain say some 5 Bytes and that area has to be divided into 3 areas.
we want to give the first division to an int , the 2nd division to a char, the 3rd division to another int.
So this type of data type is not already defined.
So we need to make a data type like this on our own.
How to do that?
We use structure.
struct datatype
{
int i;
char c;
int j;
};
Now if we declare
datatype x;
Then x will have our desired memory allocation.
Math.h
has function definitions of the mathematical functions that we use.
example : pow()
Similarly, string.h has functions that we use t manipulate strings.
A C program basically consists of the following parts −
Let find a simple code that would print the words "Hello World" :
.
significance of math.h and string.h header files.
math.h is a header file in the standard library of the C programming language designed for basic mathematical operations. Most of the functions involve the use of floating point numbers. C++ also implements these functions for compatibility reasons and declares them in the header
string.h is the header in the C standard library for the C programming language which contains macro definitions, constants and declarations of functions and types used not only for string handling but also various memory handling functions
For details study please contact me.read less
First of all, let me correct the person to ask the question. What is correct according to a computer programming language is that its #include<math.h> And not just #math. H, which is programmatically wrong.
Anyway, as the question comes, well.
In a C program, #include<math.h> is a header file in the standard library of the C programming language designed for basic mathematical operations. Most of the functions imply the use of floating point numbers. C++ also implements these functions for congeniality reasons and declares them into the header file. One can hence use functions of math.h in a C program to calculate the absolute value of a number, calculating logarithms, using trigonometric functions to calculate sine, the cosine of an angle, etc.
The math.h header thus defines various mathematical functions and one macro. All the features available in this library take double as an argument and return double as a result.
View 26 C Language Classes?
Find best C Language Classes in your locality on UrbanPro.
Are you a Tutor or Training Institute?Join UrbanPro Today to find students near you | https://www.urbanpro.com/c-language/give-the-structure-of-c-programming-also | CC-MAIN-2019-26 | refinedweb | 1,408 | 66.64 |
The 0.1 DEB packages might be a bit out of sync, they should be fixed soon. MSI and RPM packages (as well as the source tarball of course) are OK. The source tarball can be downloaded from: And other packages as usual from: New features in this release include (from the NEWS file): #v+ 0.1.3, May 30 2004 This is an incremental release before 0.2.0, it has some more .NET connectivity features, although a few things are still missing (before we can call Nemerle a CLS extender). New language features in this release: * Properties and events can be now defined. Syntax is mostly the same as in C#. * Basic custom attribute support has been added. We do not support attribute targets nor attributes on parameters yet. * Enums can be now defined. * +=, -=, *= etc operator on numbers. * Delegates can be now invoked like d() (not only d.Invoke()). += and -= operators are overloaded for events and delegates to do The Right Thing(tm). * Macros can be now defined on declarations (types, methods, fields etc). They are run using attribute syntax. * Preprocessor supporting conditional compilation has been added. It shares semantics with one from C#, -define (aka -D) flag is also supported. * Methods can be now defined inside variants. Thus a few library changes, like addition of ToString and + operator to list type. * Operators can be now overloaded (in addition to adding new). * Fields in classes can now have initializers (these are added to ctor). Other stuff: * External types are now stored in a specially crafted tree. All types are loaded on startup, but this saves time later. * Syntax extensions tied to macros are now activated only within namespace of given macro. * -pkg-config switch has been added, so external libraries (like Gtk#) can be easily linked, using -pkg:gtk-sharp. * -no-stdlib option now prevents mscorlib.dll and System.dll from being loaded, -library-path now works for them too. * ncc can now handle @response files. * Matching is being reworked, matching on variants is now a lot faster than it used to be. * Some hacks to allow mono GAC usage (available in mono 0.91+, we do *not* require this beta version though). * There is new [Record] macro that adds record like constructor to given class, there is no automatic constructor creation except for variant options now. * API for changing types from macros is being constantly reworked and improved. * List.Member and the like instead of physical == equality use Equals() method. * Several bugfixes, some critical, as usual. #v- Have a nice testing! -- : Michal Moskal :: :: GCS !tv h e>+++ b++ : ::: Logic is a nice contrast to the Real World. :: UL++++$ C++ E--- a? | http://nemerle.org/mailman/pipermail/devel-en/2004-May/000054.html | crawl-001 | refinedweb | 444 | 69.38 |
0
I would like the user to be able to see the sales total for any given month when they input a valid month. Everything works other than what I stated above. I am completely stumped on how to store the salesTotal values inputted by the user into an array (monthSalesTotal). Here is what i have so far, any help will be greatly appreciated.
#include <iostream> using namespace std; int main() { int i; int salesTotal[12]; double average = 0.0; double sum = 0.0; int choice; int monthSalesTotal[12]; for (i = 1; i < 13; i++) { cout << "Please enter the monthly sales total for month " << i << ":> "; cin >> salesTotal[i]; sum += salesTotal[i]; average = sum / i; } cout << "The average monthly sales for the year is:> " << average << endl; cout << "For what month would you like to see a sales value? "; cin >> choice; switch(choice) { case 1: choice = 1; break; case 2: choice = 2; break; case 3: choice = 3; break; case 4: choice = 4; break; case 5: choice = 5; break; case 6: choice = 6; break; case 7: choice = 7; break; case 8: choice = 8; break; case 9: choice = 9; break; case 10: choice = 10; break; case 11: choice = 11; break; case 12: choice = 12; break; default: cout << "This is an invaid choice, please re-enter:> "; cin >> choice; } cout << "The sales total for the month " << choice << " is:> " << salesTotal[i] << endl; system("pause"); return 0; } | https://www.daniweb.com/programming/software-development/threads/415070/storing-values-in-an-array | CC-MAIN-2017-26 | refinedweb | 229 | 69.04 |
The Client
———
The client side first. We import the necessary stuff needed for this program. The java.net.* contains all
the necessary packages for the networking part. The swing and awt packages are for the GUI.
import java.io.*; import java.util.*; import javax.swing.*; import java.net.*; import java.awt.*; import java.awt.event.*; public class Client {
The JTextArea will be used to display all the chat proceedings in real time. The objective of this program is to have mutiple clients connect to a server and receive the information passed to them in real time. We make use of threads in this case.
JTextField is used for passing the chat comments.
JButton is ofcourse used for sending the message.
JTextArea incoming; JTextField outgoing; JButton sendbutton;
BufferedReader is used to buffer the inputstream from another source.
We use the PrintWriter to print to the socket. It is similar to using the system println function.
BufferedReader reader; PrintWriter writer;
Sockets
——–
Sockets form the important part of this program. Simply put, it is an IP addreass with a port number. Now, port numbers vary from about 0 to 65535. It should be noted that the port numbers from 0 to 1023 are reserved and should not, unless for a reason, be used. In this example we will be using the port number 5000 to connect to the server.
Socket sock;
The function go()
—————–
This is the first method to be called. This does the following:
1. Sets up a GUI environment like I mentioned in previous posts.
2. Calls the setUpNetworking() function which will be explained later. Basically, it sets up the networking environment.
3. Most importantly, we start the threads, which I will explain.
public void go(){ JFrame frame = new JFrame("Client"); JPanel mainpanel = new JPanel(); incoming = new JTextArea(15,50); incoming.setLineWrap(true); incoming.setWrapStyleWord(true); incoming.setEditable(false); JScrollPane qScroller = new JScrollPane(incoming); qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); outgoing = new JTextField(20); sendbutton = new JButton("Send"); sendbutton.addActionListener(new SendButtonListener()); mainpanel.add(qScroller); mainpanel.add(outgoing); mainpanel.add(sendbutton); setUpNetworking();
Now what this does is set up a mainpanel which is JPanel. On it we add a JTextArea, which itself is added onto a JScrollPane as seen from the code. The different paramenters of this are set accordingly. The JButton is added and ofcourse, the ActionListener() for the button.
Thread readerThread = new Thread(new IncomingReader()); readerThread.start();
This is how a thread is created. Here we pass a new object of the class IncomingReader which implements the Runnable class, which I will explain in a moment.
frame.getContentPane().add(BorderLayout.CENTER, mainpanel); frame.setSize(400, 400); frame.setVisible(true);
}
These are just basic frame housekeeping stuff.
public static void main(String[] args){ Client client = new Client(); client.go(); }
The program begins here ofcourse. An object of the type client is created and the go() function is called.
private void setUpNetworking(){ try{ sock = new Socket("127.0.0.1", 5000);
This step creates a socket at the address “127.0.0.1” which is the localhost, ie, the same computer. And we select arbitary socket number of 5000. This number is known to the server.
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
The InputStreamReader reads the bytes of data coming from the socket inputstream.
reader = new BufferedReader(streamReader);
This is then passed on to the BufferedReader object.
writer = new PrintWriter(sock.getOutputStream());
The PrintWriter object is finally responsible for putting the message onto the output stream.
System.out.println("Networking established!!"); }catch(IOException e){ e.printStackTrace(); } }
Before I mention about the networking function, I will explain the concept of the try — catch block of code. Now, while running a code block, exceptions are bound to happen. If we know in advance, that a particular error is likely to happen at a place, we can place it in a try block. So what happens is that if any error occurs in this part will be caught by the catch() statement and then the housekeeping stuff inside the catch block executes. The whole idea of this is to make the program stop gracefully in case of an error.
We make the exception object print out the StackTrace in this case.
public class SendButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e){ try{ writer.println(outgoing.getText()); writer.flush();
We push the content typed into the JTextField into the outputstream of the socket using the writer and
clear the buffer after every step.
}catch(Exception ex){ ex.printStackTrace(); } outgoing.setText(""); outgoing.requestFocus(); } }
Once you send the message, you clear the JTextField and then give the focus back to the JTextfield so that the user can type in agagin.
This is the ActionListener for the JButton Send.
public class IncomingReader implements Runnable{ public void run(){ String message; try{ while((message = reader.readLine()) != null){ System.out.println("read" + message); incoming.append(message + "\n"); } }catch(Exception e){ e.printStackTrace(); } } } }
This is an important part of the program. This class is passed into the thread as an object. This class implements the Runnable interface. Now, each time a thread is created, this class is called. For each Client object created, new copies or threads of execution of this same program is spawned from the existing main thread, which is the only case in a sequential program and they run independently of each other till they complete or the mother thread stops.
Here what we do is to read from the BufferedReader as and when it is not empty and then post in onto the console as well as onto the JTextField using the append function. | https://linuxjunkies.wordpress.com/2011/03/10/a-simple-chat-server-in-java-using-threads-part-1/ | CC-MAIN-2017-51 | refinedweb | 929 | 59.4 |
An “Oops” is what the kernel throws at us when it finds something faulty, or an exception, in the kernel code. It’s somewhat like the segfaults of user-space. An Oops dumps its message on the console; it contains the processor status and the CPU registers of when the fault occurred. The offending process that triggered this Oops gets killed without releasing locks or cleaning up structures. The system may not even resume its normal operations sometimes; this is called an unstable state. Once an Oops has occurred, the system cannot be trusted any further.
Let’s try to generate an Oops message with sample code, and try to understand the dump.
Setting up the machine to capture an Oops
The running kernel should be compiled with
CONFIG_DEBUG_INFO, and
syslogd should be running. To generate and understand an Oops message, Let’s write a sample kernel module,
oops.c:
#include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> static void create_oops() { *(int *)0 = 0; } static int __init my_oops_init(void) { printk("oops from the module\n"); create_oops(); return (0); } static void __exit my_oops_exit(void) { printk("Goodbye world\n"); } module_init(my_oops_init); module_exit(my_oops_exit);
The associated
Makefile for this module is as follows:
obj-m := oops.o KDIR := /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) SYM=$(PWD) all: $(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules
Once executed, the module generates the following Oops:
BUG: unable to handle kernel NULL pointer dereference at (null) IP: [<ffffffffa03e1012>] my_oops_init+0x12/0x21 [oops] PGD 7a719067 PUD 7b2b3067 PMD 0 Oops: 0002 [#1] SMP last sysfs file: /sys/devices/virtual/misc/kvm/uevent CPU 1 Pid: 2248, comm: insmod Tainted: P 2.6.33.3-85.fc13.x86_64 RIP: 0010:[<ffffffffa03e1012>] [<ffffffffa03e1012>] my_oops_init+0x12/0x21 [oops] FS: 00007fb79dadf700(0000) GS:ffff880001e80000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 000000008005003b CR2: 0000000000000000 CR3: 000000007a0f1000 CR4: 00000000000006e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400 Process insmod (pid: 2248, threadinfo ffff88007ad4a000, task ffff88007a222ea0) Code: <c7> 04 25 00 00 00 00 00 00 00 00 31 c0 c9 c3 00 00 00 00 00 00 00 RIP [<ffffffffa03e1012>] my_oops_init+0x12/0x21 [oops] RSP <ffff88007ad4bf08> CR2: 0000000000000000
Understanding the Oops dump
Let’s have a closer look at the above dump, to understand some of the important bits of information.
BUG: unable to handle kernel NULL pointer dereference at (null)
The first line indicates a pointer with a NULL value.
IP: [<ffffffffa03e1012>] my_oops_init+0x12/0x21 [oops]
IP is the instruction pointer.
Oops: 0002 [#1] SMP
This is the error code value in hex. Each bit has a significance of its own:
bit 0== 0 means no page found, 1 means a protection fault
bit 1== 0 means read, 1 means write
bit 2== 0 means kernel, 1 means user-mode
[#1]— this value is the number of times the Oops occurred. Multiple Oops can be triggered as a cascading effect of the first one.
CPU 1
This denotes on which CPU the error occurred.
Pid: 2248, comm: insmod Tainted: P 2.6.33.3-85.fc13.x86_64
The
Tainted flag points to
P here. Each flag has its own meaning. A few other flags, and their meanings, picked up from
kernel/panic.c:
P— Proprietary module has been loaded.
F— Module has been forcibly loaded.
S— SMP with a CPU not designed for SMP.
R— User forced a module unload.
M— System experienced a machine check exception.
B— System has hit bad_page.
U— Userspace-defined naughtiness.
A— ACPI table overridden.
W— Taint on warning.
RIP: 0010:[<ffffffffa03e1012>] [<ffffffffa03e1012>] my_oops_init+0x12/0x21 [oops]
RIP is the CPU register containing the address of the instruction that is getting executed.
0010 comes from the code segment register.
my_oops_init+0x12/0x21 is the <symbol> + the offset/length.
This is a dump of the contents of some of the CPU registers.
The above is the stack trace.
The above is the call trace — the list of functions being called just before the Oops occurred.
Code: <c7> 04 25 00 00 00 00 00 00 00 00 31 c0 c9 c3 00 00 00 00 00 00 00
The
Code is a hex-dump of the section of machine code that was being run at the time the Oops occurred.
Debugging an Oops dump
The first step is to load the offending module into the GDB debugger, as follows:
[root@DELL-RnD-India oops]# gdb oops.ko GNU gdb (GDB) Fedora (7.1-18.fc13) Reading symbols from /code/oops/oops.ko...done. (gdb) add-symbol-file oops.o 0xffffffffa03e1000 add symbol table from file "oops.o" at .text_addr = 0xffffffffa03e1000
Next, add the symbol file to the debugger. The
add-symbol-file command’s first argument is
oops.o and the second argument is the address of the text section of the module. You can obtain this address from
/sys/module/oops/sections/.init.text (where
oops is the module name):
(gdb) add-symbol-file oops.o 0xffffffffa03e1000 add symbol table from file "oops.o" at .text_addr = 0xffffffffa03e1000 (y or n) y Reading symbols from /code/oops/oops.o...done.
From the
RIP instruction line, we can get the name of the offending function, and disassemble it.
(gdb) disassemble my_oops_init Dump of assembler code for function my_oops_init: 0x0000000000000038 <+0>: push %rbp 0x0000000000000039 <+1>: mov $0x0,%rdi 0x0000000000000040 <+8>: xor %eax,%eax 0x0000000000000042 <+10>: mov %rsp,%rbp 0x0000000000000045 <+13>: callq 0x4a <my_oops_init+18> 0x000000000000004a <+18>: movl $0x0,0x0 0x0000000000000055 <+29>: xor %eax,%eax 0x0000000000000057 <+31>: leaveq 0x0000000000000058 <+32>: retq End of assembler dump.
Now, to pin point the actual line of offending code, we add the starting address and the offset. The offset is available in the same
RIP instruction line. In our case, we are adding
0x0000000000000038 + 0x012 = 0x000000000000004a. This points to the
movl instruction.
(gdb) list *0x000000000000004a 0x4a is in my_oops_init (/code/oops/oops.c:6). 1 #include <linux/kernel.h> 2 #include <linux/module.h> 3 #include <linux/init.h> 4 5 static void create_oops() { 6 *(int *)0 = 0; 7 }
This gives the code of the offending function.
References
The kerneloops.org website can be used to pick up a lot of Oops messages to debug. The Linux kernel documentation directory has information about Oops —
kernel/Documentation/oops-tracing.txt. This, and numerous other online resources, were used while creating this article.
Anonymous-OS
I Love Linux and I Hate Windows….
Anonymous-OS is the best Operating Sistem for haking
Backtrack is the best for hacking :-p
know programming, know hacking
no programming, no hacking
pre-compiled tools == shit
self made tools == awesome
OS == no matter
I use Ubuntu and I crashed my college linux server in mere 15 lines of Perl ;)
try anonymous’s OS ;)
Great
post my friend, very nice. congrats! if you have some time, take a look on my
page, is linked to my name.
I was very over the moon to find this site.I wanted to offer
you on this great presume from!! I obviously enjoying every bantam speck of it
and I suffer with you bookmarked to monitor elsewhere novel pieces you post.
patient group direction
Hi Thanks for the post…but i would like to know the cases where we use the other log details (also) like stack/call trace/Code: ..etc…what is the purpose of them to have in log detail..can you please explain..
Nice article, thanks!
YOU JUST COPIED IT FORM THIS WEBSITE AND ALL OF A SUDDENT IT IS YOURS. FUCKING INDIANS.
Oh my, aren’t you a racist bastard. Plagiarism is a pretty serious thing. Is the part he stole the “*(int *)0 = 0;”? I don’t see any substance to your claim.
Hi,
I want to know the meaning of “(OF)” or “(OF+)” in kernel trace.
Eg: Here is one of the kernel trace i got.
general protection fault: 0000 [#1]
Modules linked in: cxgb4(OF+) toecore(OF) ip6table_filter ip6_tables
ebtable_nat ebtables nf_conntrack_ipv4 nf_defrag_ipv4 xt_state nf_conntrack
…..
….
Thanks a lot
I’m curious how you get the address of the text section of the module? If you load this module, then the kernel oops. How you read the file /sys/module/oops/sections/.init.text?
my_oops_init+0x12/0x21 is the + the offset/length :
In this what is length???
we have to put this —–>static void create_oops(void)
instead——>static void create_oops()
If your function does not take any parameters, you must specify that it is (void).
Then only we can avoid error. | http://www.opensourceforu.com/2011/01/understanding-a-kernel-oops/ | CC-MAIN-2022-33 | refinedweb | 1,413 | 74.39 |
FinniversKit holds all the UI elements of the FINN iOS app, the main reference for our components is our design system. This framework is composed of small components that are meant to be used as building blocks of the FINN iOS app.
In order to develop our components in an isolated way, we have structured them so they can be used independently of each other. Run the Demo project for a list of all our components.
Add to your Podfile:
pod "FinniversKit", git: ""
You can also add FinniversKit using SPM.
github "finn-no/FinniversKit" "master"
Import the framework to access all the components.
import FinniversKit
bundle install(dependencies will be installed in
./bundler)
FINNIVERSKIT_GITHUB_ACCESS_TOKEN.
repo.
.envfile or adding it to
.bashrc/
.bash_profile). Don't forget to run
source .env(for whichever file you set the environment variables in) if you don't want to restart your shell.
bundle exec fastlane verify_environment_variableto see if it is configured correctly.
bundle exec fastlane verify_ssh_to_githubto see if ssh to GitHub is working.
bundle exec fastlaneand choose appropriate lane. Follow instructions, you will be asked for confirmation before all remote changes.
Sourcesfolder contains Swift and Objective C files, grouped by relevant category/feature if needed
Assetsfolder contains fonts, images, sounds, generated constants and other resources used in the framework
UnitTestsfolder is used for snapshot tests and other files related to testing
Demofolder is a place for files that belong to
Demotarget. It is good practice to have corresponding demo view for every component, fullscreen or recycling view.
In order to maintain consistency we have opted for using data sources for giving data to our recyclable views and using delegates to interact for actions inside views.
If the view isn't recyclable then we use ViewModels. There are tradeoffs when you choose to be consistent instead of pragmatic but we hope that by having a clear pattern it reduces the discussion points and let's us focus on improving the UI and adding value to our users.
Our Demo project has been setup in a way that every component is isolated, we initially started by using Xcode's playgrounds but we quickly outgrew it's capacity, reloading times weren't quicker than making the change and running the project again, also it wasn't possible to debug and set breakpoint on things and we couldn't use many of Xcode's useful utilities such as View hierarchy inspector. Finally, the fact that we had to rebuild the project after making any change in the framework meant that we weren't as efficient as using plain Xcode projects (where rebuilding isn't necessary after making a change).
This project has a
Gemfile that specify some development dependencies, one of those is
pr_changelog which is a tool that helps you to generate changelogs from the Git history of the repo. You install this by running
bundle install.
To get the changes that have not been released yet just run:
$ pr_changelog
If you want to see what changes were released in the last version, run:
$ pr_changelog --last-release
You can always run the command with the
--help flag when needed.
Everything we do we aim it to be accessible, our two main areas of focus have been VoiceOver and Dynamic Type.
When making UI changes it's quite common that we would request an screenshot of the before and after, adding Snapshot testing made this trivial, if there was UI changes you would get a failure when building through the CI.
FinniversKit uses SnapshotTesting to compare the contents of a UIView against a reference image.
When you run the tests FinniversKit will take snapshot of all the components and will look for differences. If a difference is caught you'll be informed in the form of a failed test. Running the tests locally will generate a diff between the old and the new images so you can see what caused the test to fail.
To test a new component go to UnitTests and add a new
func with the name of your component under the section that makes sense, for example if your component is a Fullscreen component and it's called RegisterView then you'll need to add a method to FullscreenViewTests.swift your method should look like this:
func testRegisterView() { snapshot(.registerView) }
Note that the
snapshot method is a helper method that will call
SnapshotTesting under the hood.
There can be instances where the snapshot test pass on your machine but don't on circle ci, when that happens, circle CI will fail and inform the presence of the test results in a
.xctestresult file. To debug this, re-run the workflow with ssh access, then you will get a command to connect through ssh to circle ci, like:
ssh -p PORT IP
Then given the path of the results file circle ci reported, you can run the following command to copy it to your machine, so you will be able to inspect the failed snapshots
scp -v -r -P PORT -i PATH_TO_SSH_KEY distiller@IP:"/Users/distiller/Library/Developer/Xcode/DerivedData/FinniversKit-fblxjfyrnvejgxdktracnzlelvsi/Logs/Test/Run-Demo-2019.10.03_00-14-16--0700.xcresult" .
Make sure to replace the file path correctly to the one that circle ci reported.
If you make changes to any components you'll have to run the test for that component after changing
recordMode to
true. Doing this will generate a new reference image that will be used later to verify for changes that affect your component. After you've generated the reference image change
recordMode back to
false.
FinniversKit is available under the GNU General Public License v3.0. See the LICENSE file for more info.
The FINN.no branding, icons, images, assets, sounds and others are solely reserved for usage within FINN.no, the main purpose of this library is for internal use and to be used as reference for other teams in how we do things inside FINN.no.
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics | https://swiftpack.co/package/finn-no/FinniversKit | CC-MAIN-2021-39 | refinedweb | 1,001 | 58.01 |
Fokke, thankyou very much for the response.
Advertising
On 10 August 2017 at 10:07, Fokke Dijkstra <f.dijks...@rug.nl> wrote: > We use the spank-private-tmp plugin developed at HPC2N in Sweden: > > > See also: > for a presentation about the plugin. > > > 2017-08-10 9:31 GMT+02:00 John Hearns <hear...@googlemail.com>: > >> I am sure someone discussed this topic on this list a few months ago... >> if it rings any bells please let me know. >> I am not discussing setting the TMPDIR environment variable and crateing >> a new TMPDIR directory on a per job basis - though thankyou for the help I >> did get when discussing this. >> >> Rather I would like to set up a new namespace when a job runs such that >> /tmp is unique to every job. /tmp can of course be a directly uniquely >> created for that job and deleted afterwards. >> This is to cope with any software which writes to /tmp rather than using >> the TMPDIR variable. >> If anyone does this let me know what your techniques are please. >> >> > > > -- > Fokke Dijkstra <f.dijks...@rug.nl> <f.dijks...@rug.nl> > Research and Innovation Support > Center for Information Technology, University of Groningen > Postbus 11044, 9700 CA Groningen, The Netherlands > +31-50-363 9243 <+31%2050%20363%209243> > | https://www.mail-archive.com/slurm-dev@schedmd.com/msg10753.html | CC-MAIN-2017-34 | refinedweb | 211 | 73.78 |
To change the computer name, to join a domain, or to add a computer description for a Windows XP-based computer, use the Computer Name tab in the System Properties dialog box. To locate this tab, use one of the following methods:
* Click Start, right-click My Computer, and then click Properties.
* Click Start, click Run, type sysdm.cpl, and then click OK.
* Click Start, click Control Panel, double-click Performance and Maintenance, and then click System.
Change the computer name and join a domain or a workgroup. For more information, click the following article number to view the article in the Microsoft Knowledge Base:
317049 ( ) You cannot log on after you remove the computer from the domain
1. Click the Computer Name tab, and then click Change.
2. Type the new computer name in the Computer name dialog box.
3. Type the new domain or workgroup in either the Domain dialog box or the Workgroup dialog box.
4. Click More to change the primary Domain Name System (DNS) suffix.
Note Windows XP Home Edition is not designed to join domains. Windows XP Home Edition is only designed to join workgroups. Therefore, use Windows XP Professional to join domains.
5. Click OK three times, and then restart the computer.
Add a computer description
To add a computer description, type a name or a description in the Computer description box on the Computer Name tab, and then click Apply.
Network ID Wizard
If you do not know how to complete these tasks, you can use the Network Identification (ID) Wizard to help you. To start the Network ID Wizard, follow these steps:
1. In the System Properties dialog box, click Network ID.
Note This wizard is new to Windows XP. With this wizard, you can add the computer to a workgroup or to a domain.
2. Move backward and forward in the wizard by using the Back and Next buttons.
The first set of options in the Network ID Wizard is as follows:
* Option 1
“This computer is part of a business network, and I use it to connect to other computers at work.”
* Option 2
“This computer is for home use and is not part of a business network.”
If you select option 1, the following options appear:
* Option 1a
“My company uses a network with a domain.”
* Option 1b
“My company uses a network without a domain.”
If you select option 1a, a dialog box appears that requests the following information:
* User name
* User account domain
* Computer name
* Computer domain
If you select option 1b, you can also configure the computer as a “Workgroup Member,” and you can type the name of the workgroup.
If you select option 2, you are prompted to click Finish to restart the computer. If you follow this step, the computer is configured as a “Workgroup Member.” By default, the name of the workgroup is “Workgroup.”
Then, the next page requires the domain name to which the computer is to be added. Also, the next page requires the username and the password of an account that has the rights to add a computer to the domain. Additionally, the next page enables the user account from the previous page to be added to this computer. Finally, the next page enables the new that has security accounts. These security accounts only pertain to that computer. To change domains at the logon screen, press CTRL+ALT+DELETE. If the Domain box does not appear, click the Options button to display the Domain box, and then select the required domain from the menu.
Note Generally, you must have Administrator credentials on the computer to complete the tasks that are mentioned in this article.
For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
246804 ( ) How to enable/disable Windows 2000 Dynamic DNS registrations
255913 ( ) Integrating Windows 2000 DNS into an existing BIND or Windows NT 4.0-based DNS namespace
Back to the top
Windows Server 2003
To change the computer name, to join a domain, or to add a computer description for a Windows Server 2003-based computer, use the Computer Name tab in the System Properties dialog box. To locate this tab, use one of the following methods:
* Right-click My Computer, and then click Properties.
* Click Start, click Run, type sysdm.cpl, and then click OK.
* Click Start, click Control Panel, and then click System.
Change a computer name and join a domain or a workgroup
To change a computer name and to join a domain or a workgroup, follow these steps:
1. Click the Computer Name tab, and then click Change.
2. Type the new computer name in the Computer name dialog box.
3. Type the new domain or a workgroup in either the Domain dialog box or the Workgroup dialog box.
4. Click More to change the primary Domain Name System (DNS) suffix.
5. Click OK three times, and then restart the computer.
Add a computer description
Type a name or a description in the Computer description box on the Computer Name tab, and then click Apply to add a computer description.
Introduction to the Networking Changes in Windows XP
Windows XP is the first major change in interface since the step from Windows 3.1 (aka Windows for Workgroups) to Windows 95. In some ways it is simpler with many Wizards and more consistent. not offered as an option but can be hunted out from the CD (or via Microsoft Technical Support Articles) at your own risk and without guaranteed ongoing support.
The.
Configuring Windows XP to match an existing Network
1. Disable your firewall and virus checking: Before removing, installing or making significant modifications to anything to do with the Network, you should disable your firewall and virus checking. They may link into TCP/IP and give problems when their links disappear. Most Firewalls and Virus checkers have a flag to say if they should load automatically on startup which should be unticked and the system rebooted. After you have finished they should be re-enabled before you take too many risks.
2. Disable the Internet Connection Firewall: To disable ICF on the Local Area Network (LAN) Connection,
* Open Network Connections,
* Right click LAN Connection at the bottom and click Properties.
The Properties sheet shows the network components associated with the connection.
* Select the Advanced tab, then un-check the “Protect my computer and network by limiting or preventing access to this computer from the Internet” box.
* Windows XP asks you to confirm your decision to disable the firewall – Click OK to disable it.
This step should also be done for the Internet Connections if you intend to use a separate Firewall such as ZoneAlarm.
3. Set up Names: Firstly set up the Computer Name, Workgroup Name and Computer Description – on XP this is via the Network Connections I prefer to
* Go to the Control Panel and to change it to Classic View
* Open Network Connections
* Select LAN Connection at the bottom
* Click Network ID on the Advanced drop down Menu at the top
o Enter a Computer Description
o A unique Computer Name and
o the same Workgroup Name for all machines on the same network
If you are selecting and setting the Name and Workgroup for the first time on a new network it is best to use Upper letters and numbers only and to keep them less than 12 characters for
4. Add the IPX/SPX Protocol: IPX/SPX is fully supported in XP and is my prefered “safe” protocol which is used on networks set up as in Painless Networking. The name is slightly different with NW (for Netware) in the front.
* Click Start, click Control Panel, and then Open Network Connections.
* Right-click the LAN Connection and then click Properties.
* On the General tab, click Install.
* Click Protocol, and then click Add.
* Click NWLink IPX/SPX/NetBIOS Compatible Transport Protocol and click OK.
Two NWLink items are added to the connection’s Properties
* Restart your computer even if not requested and The IPX/SPX protocol should now be installed and working.
5. Set up Bindings: By default, Windows XP binds all installed protocols to each network connection and service. We need to remove various bindings to limit the services using each protocol. The mechanism is very different to Win9X and in XP one should:
* Open the Network Connections folder and on the Advanced drop down menu click Advanced Settings
* Click the connection name under Connections. The appropriate bindings appear under Bindings.
* To remove a binding, un-check the corresponding box. For example, we want to use IPX/SPX instead of TCP/IP for file sharing,so we un-bind TCP/IP from both File and Printer Sharing and Client for Microsoft Networks.
* It is also necessary to right click the LAN Network Connection and click properties then untick the TCP/IP box to completely prevent TCP/IP being used instead of IPX/SPX.
* Restart your computer even if not requested
6. Sharing: The existing network will already have shared folders but you will need to set them up on the XP machine before you will see it over the Network. If you can not see the Sharing Tabs on the Properties of a Folder check File and Printer Sharing is enabled in the LAN configuration
7. Testing: The Configuration should now be complete and you should be able to see the XP machine from the existing network and vice versa in Network Neighborhood/Network Places. One thing to note is that it can take a long time before Network Neighborhood/My Network Places fully updates for new machines and reconfiguration – this is because a Browse Master is automatically selected to retain Network configuration information and organise traffic and that process is not repeated until a change is recognised which can take a while. It took a long time before the XP machine was displaying up to date information although the Network was working fine from the other machines. Turning all the machines off and starting together may help.
8. Security Testing and Firewalls: The use of the IPX/SPX protocol and breaking of all bindings between TCP/IP should now have closed the security holes inherent in the use of TCP/IP over a LAN but it is still wise to check the security both with and without the firewall using the the Shields Up tests at the Gibson Research Corporation.
9. Windows XP Internet Connection Firewall: If you do not have a firewall it may now be possible to (re-)enable the simple built in Firewall on the Dial-up Connection without affecting the LAN – see above for the proceedure. I have not tried as I use ZoneAlarm, the excellent free firewall. If you do so repeat the Shields Up tests at the Gibson Research Corporation.
10. Re-enable Virus checkers: Remember to re-enable any virus checking you earlier disabled once you are sure you have finished making changes.
Register Hereor login if you are already a member
Discuss This Question: 1 Reply | http://itknowledgeexchange.techtarget.com/itanswers/networking-and-windows-workgroups/ | CC-MAIN-2017-04 | refinedweb | 1,846 | 60.45 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
how to select data from database?
i have to calculate the total amount of claims in my custome module.so i want to knwo that how to calculate the total amount of claims in my calim table. how it is posilble?is there anyfuction to done database retrivel of data?
Easiest way in old API would be self.pool.get('crm.claim').search(cr, uid, [], count=True), so you will receive number of all records in crm_claim table.
can u please give me one example with function definition
def count_claims(self, cr, uid, ids, context=None) return self.pool.get('crm.claim').search(cr, uid, [], count=True) Like so?
return self.pool.get('amount.claim').search(cr, uid, [], count=True) AttributeError: 'NoneType' object has no attribute 'search'--this is the error.pls help me how to select amount from claim?
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/how-to-select-data-from-database-77725 | CC-MAIN-2017-43 | refinedweb | 195 | 60.51 |
If you have a good understanding on Java, then it will be very easy for you to learn Scala. The biggest syntactic difference between Scala and Java is that the ';' line end character is optional.
When we consider a Scala program, it can be defined as a collection of objects that communicate via invoking each other’s methods. Let us now briefly look into what do class, object, methods and instance variables mean.
Object − Objects have states and behaviors. An object is an instance of a class. Example − A dog has states - color, name, breed as well as behaviors - wagging, barking, and eating.
Class − A class can be defined as a template/blueprint that describes the behaviors/states that are related to the class.
Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
Fields − Each object has its unique set of instance variables, which are called fields. An object's state is created by the values assigned to these fields.
Closure − A closure is a function, whose return value depends on the value of one or more variables declared outside this function.
Traits − A trait encapsulates method and field definitions, which can then be reused by mixing them into classes. Traits are used to define object types by specifying the signature of the supported methods.
We can execute a Scala program in two modes: one is interactive mode and another is script mode.
Open the command prompt and use the following command to open Scala.
\>scala
If Scala is installed in your system, the following output will be displayed −
Welcome to Scala version 2.9.0.1 Type in expressions to have them evaluated. Type :help for more information.
Type the following text to the right of the Scala prompt and press the Enter key −
scala> println("Hello, Scala!");
It will produce the following result −
Hello, Scala!
Use the following instructions to write a Scala program in script mode. Open notepad and add the following code into it.
object HelloWorld { /* This is my first java program. * This will print 'Hello World' as the output */ def main(args: Array[String]) { println("Hello, world!") // prints Hello World } }
Save the file as − HelloWorld.scala.
Open the command prompt window and go to the directory where the program file is saved. The ‘scalac’ command is used to compile the Scala program and it will generate a few class files in the current directory. One of them will be called HelloWorld.class. This is a bytecode which will run on Java Virtual Machine (JVM) using ‘scala’ command.
Use the following command to compile and execute your Scala program.
\> scalac HelloWorld.scala \> scala HelloWorld
Hello, World!
The following are the basic syntaxes and coding conventions in Scala programming.
Case Sensitivity − Scala is case-sensitive, which means identifier Hello and hello would have different meaning in Scala.
Class Names − For all class names, the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case.
Example − class MyFirstScalaClass.
Method Names − All method names should start with a Lower Case letter. If multiple words are used to form the name of the method, then each inner word's first letter should be in Upper Case.
Example − def myMethodName()
Program File Name − Name of the program file should exactly match the object name. When saving the file you should save it using the object name (Remember Scala is case-sensitive) and append ‘.scala’ to the end of the name. (If the file name and the object name do not match your program will not compile).
Example − Assume 'HelloWorld' is the object name. Then the file should be saved as 'HelloWorld.scala'.
def main(args: Array[String]) − Scala program processing starts from the main() method which is a mandatory part of every Scala Program.
All Scala components require names. Names used for objects, classes, variables and methods are called identifiers. A keyword cannot be used as an identifier and identifiers are case-sensitive. Scala supports four types of identifiers.
An alphanumeric identifier starts with a letter or an underscore, which can be followed by further letters, digits, or underscores. The '$' character is a reserved keyword in Scala and should not be used in identifiers.
Following are legal alphanumeric identifiers −
age, salary, _value, __1_value
Following are illegal identifiers −
$salary, 123abc, -salary
An operator identifier consists of one or more operator characters. Operator characters are printable ASCII characters such as +, :, ?, ~ or #.
Following are legal operator identifiers −
+ ++ ::: <?> :>
The Scala compiler will internally "mangle" operator identifiers to turn them into legal Java identifiers with embedded $ characters. For instance, the identifier :-> would be represented internally as $colon$minus$greater.
A mixed identifier consists of an alphanumeric identifier, which is followed by an underscore and an operator identifier.
Following are legal mixed identifiers −
unary_+, myvar_=
Here, unary_+ used as a method name defines a unary + operator and myvar_= used as method name defines an assignment operator (operator overloading).
A literal identifier is an arbitrary string enclosed in back ticks (` . . . `).
Following are legal literal identifiers −
`x` `<clinit>` `yield`!") } }
A line containing only whitespace, possibly with a comment, is known as a blank line, and Scala totally ignores it. Tokens may be separated by whitespace characters and/or comments.. Below syntax is the usage of multiple statements.
val s = "hello"; println(s)
A package is a named module of code. For example, the Lift utility package is net.liftweb.util. The package declaration is the first non-comment line in the source file as follows −
package com.liftcode.stuff
Scala packages can be imported so that they can be referenced in the current compilation scope. The following statement imports the contents of the scala.xml package −
import scala.xml._
You can import a single class and object, for example, HashMap from the scala.collection.mutable package −
import scala.collection.mutable.HashMap
You can import more than one class or object from a single package, for example, TreeMap and TreeSet from the scala.collection.immutable package −
import scala.collection.immutable.{TreeMap, TreeSet}
A marker trait that enables dynamic invocations. Instances x of this trait allow method invocations x.meth(args) for arbitrary method names meth and argument lists args as well as field accesses x.field for arbitrary field namesfield. This feature is introduced in Scala-2.10.
If a call is not natively supported by x (i.e. if type checking fails), it is rewritten according to the following rules −
foo.method("blah") ~~> foo.applyDynamic("method")("blah") foo.method(x = "blah") ~~> foo.applyDynamicNamed("method")(("x", "blah")) foo.method(x = 1, 2) ~~> foo.applyDynamicNamed("method")(("x", 1), ("", 2)) foo.field ~~> foo.selectDynamic("field") foo.varia = 10 ~~> foo.updateDynamic("varia")(10) foo.arr(10) = 13 ~~> foo.selectDynamic("arr").update(10, 13) foo.arr(10) ~~> foo.applyDynamic("arr")(10) | https://www.tutorialspoint.com/scala/scala_basic_syntax.htm | CC-MAIN-2019-39 | refinedweb | 1,160 | 59.3 |
while ago while in Norway. It allows me to write tests in a style that I have been writing them in for a few years now while removing the pain of doing so. You can grab grensesnitt on mygithub , to install just copy it into the addins folder of your particular nunit installation. If you want to just test it out, its installed in the nunit installation included in the /lib folder (you can run the tests in the sample project).
Many of our tests should not be written against classes but should instead be written against interfaces. They represent the invariants of the given interface. Consider as an example IList, I don’t care how you implement IList but if I call add and you return to me without an error, count needs to increment and I need to be able to get the item back. If you cannot do this in my eyes you are not really an IList as I cannot use you. Seriously, can you imagine someone passing you an IList that when you added stuff to it, you couldn’t get it back out? Right now we tend to have all of these assumptions implicitly, grensesnitt allows you to make them explicit.
nunit allows you to do some things like this using Generic Test Fixtures such as
[TestFixture(typeof(ArrayList))]
[TestFixture(typeof(List<int>))]
public class IList_Tests<TList> where TList : IList, new()
but there are some drawbacks to this. First I need to actually add the type to the test manually, what if I forget? manual steps suck. The second is that the test assembly needs references to all of the implementers which can be problematic.
With grensesnitt:
public interface ICanAdd {
int Add(int i, int j);
}
[InterfaceSpecification]
public class ICanAddTests : AppliesTo<ICanAdd>{
[Test]
public void can_add_two_numbers() {
Assert.AreEqual(5, sut.Add(2,3));
}
}
This would be the code that you would write. Grensesnitt will then automatically find any class that implements ICanAdd and these tests will be run against it. This automation of the process is very important. Said simply as soon as you implement ICanAdd you have N failing tests. Grensesnitt is capable of running either explicit interfaces or class interfaces (i.e. inheritance)
When you run grensesnitt, it will automatically find these implementers and you will see your tests show up as a test suite per implementer. As you can see in the image below. Adder1, Adder2, Adder3 etc are all implementers of the adder interface.
You can also control where grensenitt searches for implementers by using the [assembly: GrensesnittSearchLocation("../plugins")] attribute on your test assembly. By default it will search in all the assemblies in the directory.
Grensesnitt also plays nice with other nUnit plugins. As an example here is a test (shown above in runner) that also uses TestCase for parameterized tests.
[InterfaceSpecification]
public class WithOtherPlugins : AppliesToAll<ICanAdd>
{
[TestCase(1, 2, 3)]
[TestCase(-1, 2, 1)]
[TestCase(0, 0, 0)]
public void CanAddOrSomething(int x, int y, int r)
{
Assert.AreEqual(subject.Add(x, y), r);
}
[TestCase(1, 2, Result = 3)]
[TestCase(-1, 2, Result = 1)]
[TestCase(0, 0, Result = 0)]
public int CannAddOrSomethingWithReturn(int x, int y) {
return subject.Add(x, y);
}
}
Now ask yourself, how many times have you implemented an interface out of some library, then passed your implementer in and gotten some really weird bug happening 65 levels down the call stack in their code? Its because of something in your implementer but you don’t know what? Grensesnitt is a way to allow a framework developer to document their needs. They release the grensesnitt tests with their code. When you implement their interface, their context specifications get run automatically against you (it’s a form of documentation), and it works very very well with BDD style tests.
Grensesnitt is also fairly opinionated and its hard to do bad things. Grensesnitt does not as an example require default constructors on objects. Instead there is a hookable object creator. GrensesnittObjectLocator that you can hook all or specific calls to a factory method. Its like this by design, if your test depends on something being passed to a constructor eg: if I pass 5 to the constructor this property should return 5 that is *not* an interface test, it is a class test.
Anyways it makes this testing style easier for me so maybe it will benefit others.
Special thanks to Svein, Morten, and Einar who all helped with the creation of grensesnitt. Oh and nevermind all the dead bodies in the plugin itself (copy/pasted private code from nunit with internal calls replaced with reflections) those were just casualties from fighting the dragons that be in nUnit.
Pingback: mookid on code » Contract testing with NUnit
This is good stuff Greg, thanks for sharing. I came across a need for something similar last year when publishing an SPI for a Java library. When I get a chance, I’ll see if I can come up with a decent Java variation of grensesnitt.
Scooletz if you would need different constructed objects for different tests those tests should not be interface tests they should be class tests. The locator allows you to specify to always call a given factory for a given type or to hook all creations to your own method (eg: container).
It’s been a while since your last post Greg;-) I’ve got one question about GrensesnittObjectLocator. Does it uses some kind of conventions, or configuration to resolve how create objects injected in constructor? I can imagine tests, where in one case I pass one stub to the constructor, while when running other, another, both implementing the same interface.
Yes similar, I believe the big difference is it automatically finds anything that the specification can map to.
This [InterfaceSpecification] looks like the same as [Behavior] in mspec.
Excellent. Thanks! | http://codebetter.com/gregyoung/2010/10/29/hei-hei-grensesnitt/ | CC-MAIN-2014-10 | refinedweb | 973 | 62.07 |
M5ez, a complete interface builder system for the M5Stack as an Arduino library. Extremely easy to use.
@rop
Hi Rop,
I see you worked hard with the clock in ezTime library...
I wonder what will be the next step...
Will you merge M5ez with ezTime?
Will they be independent works?
Will M5ez call the functions of ezTime?
¯_('-')_/¯
@janseta If you have ezTime and turn on the clock (it'll be a
#define), M5ez will use ezTime to show an on-screen clock. And naturally if you include it in your own sketch you can use the features of it in your own code as well. Soon...
Hi everyone,
I just released version 1.3.1 of M5ez: it can now use images from program flash, SD-card and SPIFFS in image menus.The documentation says how, and there's an example that shows it in action.
Hi Rop,
I finaly found some time and as non programmer i did manage to use your code and make it talk mqtt just copy and pasted some code from you and the pubsub lib and it does work.
Below the code i used to control my domoticz setup thru mqtt :
I had to make some adjustment to PubSubClient.h and made some values higher like socket timeout, max packet size and degraded version.
So i guess it isnt that hard after all. To make sure you understand that i am a compete noob and dont even know what language i have been copy and pasting.
Next try will be to use the ezProgressBar and let that drive the dimmer based on pb.value. But that will be a real challenge for me as copy and paste coder.
adjustment to PubSubClient.h:
#define MQTT_SOCKET_TIMEOUT 60
#define MQTT_MAX_PACKET_SIZE 1024
#define MQTT_VERSION_3_1 3
Now the code below runs fine sofar ( 15 mins or so )
#include <M5Stack.h> #include <M5ez.h> #include <WiFi.h> #include <PubSubClient.h> const char* ssid = "xxxxxx"; const char* password = "xxxxxxxxxxx"; const char* mqttServer = "xxxxxxxxxxxxxx"; const int mqttPort = 1883; const char* mqttUser = "xxxxxxxxxxxxxxxxt"; const char* mqttPassword = "xxxxxxxxxxxxxx"; WiFiClient esp32Client; PubSubClient client(esp32Client); long lastMsg = 0; char msg[50]; int value = 0;); } } m5.begin(); } void loop() { ezMenu myMenu("Main menu"); myMenu.addItem("lamp bank aan", mainmenu_one); myMenu.addItem("lampbank uit", mainmenu_two); myMenu.addItem("dimmer keukenlamp", mainmenu_three); myMenu.run(); } void mainmenu_one() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 136, \"switchcmd\": \"On\", \"level\": 100}"); Serial.println("mqtt send"); } void mainmenu_two() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 136, \"switchcmd\": \"Off\", \"level\": 0}"); Serial.println("mqtt off send"); } void mainmenu_three() { ezMenu subMenu("Submenu"); subMenu.addItem("Keuken off", submenu_off); subMenu.addItem("Dim 10%", submenu_one); subMenu.addItem("Dim 20% ", submenu_two); subMenu.addItem("Dim 30%", submenu_three); subMenu.addItem("Dim 40%", submenu_four); subMenu.addItem("Dim 50%", submenu_five); subMenu.addItem("Dim 60%", submenu_six); subMenu.addItem("Dim 70%", submenu_seven); subMenu.addItem("Dim 80%", submenu_eight); subMenu.addItem("Dim 90%", submenu_nine); subMenu.addItem("Dim 100%", submenu_ten); subMenu.addItem("Back | Back to main menu"); subMenu.upOnFirst("last|up"); subMenu.downOnLast("first|down"); subMenu.run(); client.loop(); } void submenu_one() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 10}"); Serial.println("mqtt send"); } void submenu_two() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 20}"); Serial.println("mqtt send"); } void submenu_three() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 30}"); Serial.println("mqtt send"); } void submenu_four() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 40}"); Serial.println("mqtt send"); } void submenu_five() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 50}"); Serial.println("mqtt send"); } void submenu_six() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 60}"); Serial.println("mqtt send"); } void submenu_seven() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 70}"); Serial.println("mqtt send"); } void submenu_eight() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 80}"); Serial.println("mqtt send"); } void submenu_nine() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 90}"); Serial.println("mqtt send"); } void submenu_ten() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Set Level\", \"level\": 100}"); Serial.println("mqtt send"); } void submenu_off() { client.publish("domoticz/in", "{\"command\": \"switchlight\", \"idx\": 143, \"switchcmd\": \"Off\", \"level\": 0}"); Serial.println("mqtt send"); }```
. | http://forum.m5stack.com/topic/262/m5ez-a-complete-interface-builder-system-for-the-m5stack-as-an-arduino-library-extremely-easy-to-use/48 | CC-MAIN-2018-43 | refinedweb | 710 | 54.29 |
Elm has a very fine third-party line chart library which I've enjoyed using in my passion project, Chicago Test Out. It's well-documented as a library, but if I haven't used it in a while, I find myself struggling to get started with it. I end up starting at the middle or near the end and then clumsily working backwards from where I want to end up. For this reason,I'm working on writing a step-by-step guide for working with
terezka/line-charts based on my own preferences and assuming a high-degree of customization apart from the defaults, using Chicago Test Out as a model.
One of my preferences is that a line chart almost always be used with time on the x-axis, and you can't use a time without knowing the time zone, so we'll start there.
Step 1: Add a
Time.Zone field to your model.
Time zones have to be fetched asynchronously, which means
- Open the file that has your model record in it and, if you have not already,
import Time.
- Add a field of type
Time.Zoneto your
Modeltype record.
- In your model initialization, initialize your time zone field to Time.utc.
- Compile.
If you haven't already used
elm/time somewhere, the elm compiler may object and insist that you install the dependency, which it will walk you through Assuming you don't have a lot of different functions that initialize a new model, this should bring your code to a compiling state. I am including the full source for src/Models.elm from Chicago Test out below for reference.
module Models exposing (..) import Hospitalization exposing (Hospitalization) import TestDay exposing (TestDay) import Time type alias Model = { days : List TestDay , hospitalizations : List Hospitalization , mode : Mode , zone: Time.Zone } type Mode = Test | HospitalizationMode init : Model init = { days = [] , hospitalizations = [] , mode = Test , zone = Time.utc }
Step 2: Add a time zone update message
- Open the file containing your Elm messages. (Mine is in src/Msg.elm.)
- If you haven't already,
import Timeinto that module.
- Add an
UpdateZonetype that takes a
Time.Zoneparameter, like so:
module Msg exposing (..) import Hospitalization exposing (Hospitalization) import Httpimport Json.Encode import Models exposing (Mode(..)) import RawTestDay exposing (RawTestDay) import Timetype Msg = GotRawTestDays (Result Http.Error (List RawTestDay)) | SetMode Mode | UpdateHospitalizationDays Json.Encode.Value | UpdateZone Time.Zone
- Implement your new message in your
updatemethod of your elm application,likely located in src/Main.elm. (You may need to
import Timehere as well.)
- Compile.
Your code should be once again in a compiling state.
Get the Timezone from a Task
Now, just hook a Task to get
Time.here into your new message, and you should be up and running with time zones.
This example shows how to do it from
init, but in Chicago Test Out, I want to fetch the time zone after I've run a fetch, so I'm going to hook in from the end of my fetch event.This is what I mean:
update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of GotRawTestDays result -> case result of Ok response -> TestDay.fromRaws response |> \days -> ({model | days = days} , Task.perform UpdateZone Time.here ) Err e -> case e of . . .
That's a lot to look at, but as you can see I'm calling
Task.perform if the response from
GotRawTestDays is
Ok. If the Task is success full, the current time zone,
Time.here will be passed to the message handler of
UpdateZone.
A word on modelling times in Elm
As a reminder, Elm rejects ISO 8601 as a standard for dates. If you want dates along the x-axis of your chart, you need to have those dates passed as a posix number. For line charts, this should be a
Float type. The steps to get your data will vary, so I won't enumerate them here, but keep that in mind as you work on fetching your line chart dataset: You need a
Float for a date.
In Conclusion
This pretty well covers our prerequisites for working with line charts. In the next post, I'll start to scaffold a real chart.
Discussion | https://dev.to/webbureaucrat/elm-line-charts-part-i-times-and-timezones-42e4 | CC-MAIN-2020-45 | refinedweb | 699 | 74.39 |
This week, let’s discuss two features I’d really like to see in C and
C++; one trivial, one not so trivial.
The first feature I’d like to see is a rather trivial one, but one what may make things easier in low-level programs: binary notation for integers. In C/C++, we have “normal” integer notation, such as 120172, or whatever, that denotes base-10 integers as long as they do not begin by 0. A number that begins with 0 followed by digits 0 to 7, such as 06312 is in base-8, octal. While octal might have had some sense in the days where computers had odd-sized registers (12 bits?!), I don’t think it’s all that useful nowadays. Then comes hexadecimal, introduced by the prefix 0x and using “digits” 0 to 9, a to f.
I gather that binary notation would be introduced by the prefix 0b, followed by a list of bits. That’s it: 0xb01010101u. A minor itch, but one that may enhance code legibility in some cases.
*
* *
The second thing I’d really like, is a using clause that works pretty much like the old-time Pascal with. The with statement in Pascal introduces a scope that is relative to the variable to which with is applied. Simply:
this_toaster.slots=2; this_toaster.bread_loaded=false;
can be translated into
with this_toaster do begin slots=2; bread_loaded=false; end;
A first, it doesn’t look like much of an improvement, because the second version is much longer. But now, replace the simple this_toaster by toasters[3*i+4] and we see something different. A single evaluation of the expression toasters[3*i+4] may lead to better, faster code, in addition of avoiding the unsightly repetition of a complex expression, each being the chance of inserting an error.
In C++, we already have a using statement that could be extended to this behavior (it could also be introduced to C, but maybe with would be more c-like?). C++’s using statement brings a given namespace into the current namespace, in essence yielding the union of the current namespace and of the namespace in the using statement. In C++, we can write using just about everywhere:
int something(int x, ... ) { using namespace std; //...here std:: members are accessible //as if from the current namespace... }
What I propose is to extend using to behave “as expected” if we make follow a typename, struct, or class instance:
using some_struct { thingie=0; blorp++; }
should be equivalent to
some_struct.thingie=0; some_struct.blorp++;
I would expect it to work for static classes and other types, say, like this:
using std::numeric_limits<T> { low = min(); hi = max(); }
;
In this case, it’s not really all that much shorter than
low=std::numeric_limits<T>::min(); hi=std::numeric_limits<T>::max();
but it improves legibility.
Again, we have that the argument in the using is evaluated just once, at the moment of the clause; which may lead to better code as well.
We might even introduce a this that points to the object (if not static class?) being used in the using clause in order to disambiguate scope, just as we would do in a member function, and with the same rules.
*
* *
I really like the idea of extending using this way. Well, there’s an element of nostalgia to it, since Pascal was my first “real” programming language, more than 30 years ago. But there’s also the old me that is getting increasingly pragmatic and I see this extended using clause as a mean of writing more legible code, reducing the chance of error, and as a way of controlling explicitly the evaluation of repetitive statements. I think it would be a great addition to the next C++ standard, and, while we’re at it, why not add it to C too?
Did you mean 0b01 instead of 0xb01?
Reblogged this on Contingency Coder and commented:
I really like the ideas he has on the using statement! It would definitely improve code readability and conciseness in a lot of code bases.
I think the binary notation is slated for the next C++ standard, and you can already do add it via customized literals (as of C++11)
Haven’t tried, but I think you can define binary literals yourself:
JavaScript has this, and for a couple of reasons its use is discouraged. Aside from name performance issue which doesn’t affect C++, it hinders readability somewhat by introducing into local scope things that have been declared elsewhere, and there’s the added risk of name conflicts, especially by introducing new names into the struct/class used in your ‘with’ or ‘using’ statement.
Visual Basic (yes, I know…) has a relatively elegant compromise:
With some_object
.foo = 1234
.bar = 5678
End With | https://hbfs.wordpress.com/2013/10/01/two-features-id-like-to-see-in-c-and-c/ | CC-MAIN-2017-13 | refinedweb | 804 | 58.72 |
While browsing the Project Euler problems, I found problem 97, which is an incredibly straightforward problem that is buried within a sea of much more challenging problems. It’s called “Large non-Mersenne Prime” and it states the following.−1$, have been found which contain more digits.
However, in 2004 there was found a massive non-Mersenne prime which contains 2,357,207 digits: $28433\times 2^{7830457}+1$.
Find the last ten digits of this prime number.
Solution in Python
Since we’re only looking for the final ten digits of the number, we can form a solution modulo a sufficiently large number, effectively forgetting about any larger power digits. We’ll do all of the powers of two first, then multiply by the constant, then add one. We’ll take the first ten digits of the result and that should be the answer we’re looking for. I’d say that this one is pretty quick and painless.
#!/usr/bin/env python import time start = time.time() n = 2 for i in range(7830456): n = (2 * n) % 10000000000 n *= 28433 n += 1 n = n % 10000000000 elapsed = time.time() - start print "Result %s found in %s seconds" % (n, elapsed)
Then, executing, we have:
$ python problem-97.py Result 8739992577 found in 1.08037400246 seconds
Solution in C
This is a situation where the C solution is nearly as fast to write as the Python solution, and the code really follows the same structure.
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { unsigned long i; unsigned long long n = 2; for (i=0;i<7830456;i++) { n = (n << 1) % 10000000000; } n *= 28433; n += 1; n = n % 10000000000; printf("Result %lld\n", n); return 0; }
When we execute, the result is returned very quickly. (I’ve optimized the machine code using the -O3 flag as you can see below.)
$ gcc -O3 problem-97.c -o problem-97 $ time ./problem-97 Result 8739992577 real 0m0.030s user 0m0.028s sys 0m0.004s
That feels pretty fast, but I think a bottleneck is popping up when we bitshift (multiply by 2) AND reduce the result modolo 10000000000 at every single iteration of the for loop. The bitshifting is fast, but the modular arithmetic isn’t so much. Let’s rewrite the code so that we’re bitshifting at every iteration, but only using modular arithmetic every several iterations.
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { unsigned long i,j; unsigned long long n = 2; j = 0; for (i=0;i<7830456;i++) { //n = (n << 1) % 10000000000; n <<= 1; j++; if (j%10==0) { j = 0; n = n % 10000000000; } } n *= 28433; n += 1; n = n % 10000000000; printf("Result %lld\n", n); return 0; }
That runs in roughly 1/3 the time of the original C code.
$ gcc -O3 problem-97.c -o problem-97 $ time ./problem-97 Result 8739992577 real 0m0.009s user 0m0.008s sys 0m0.000s | http://code.jasonbhill.com/2013/04/ | CC-MAIN-2017-13 | refinedweb | 493 | 74.69 |
According to the documentation of the
==
For predefined value types, the
equality operator (==) returns true if
the values of its operands are equal,
false otherwise. For reference types
other than string, == returns true if
its two operands refer to the same
object. For the string type, ==
compares the values of the strings.
User-defined value types can overload
the == operator (see operator). So can
user-defined reference types, although
by default == behaves as described
above for both predefined and
user-defined reference types.
void Compare<T>(T x, T y) { return x == y; }
==
==
==
true
Test.test<B>(new B(), new B())
class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }
"...by default == behaves as described above for both predefined and user-defined reference types."
Type T is not necessarily a reference type, so the compiler can't make that assumption.
However, this will compile because it is more explicit:
bool Compare<T>(T x, T y) where T : class { return x == y; }
Follow up to additional question, "But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?"
I would have thought that == on the Generics would use the overloaded version, but the following test demonstrates otherwise. Interesting... I'd love to know why! If someone knows please share.
namespace TestProject { class Program { static void Main(string[] args) { Test a = new Test(); Test b = new Test(); Console.WriteLine("Inline:"); bool x = a == b; Console.WriteLine("Generic:"); Compare<Test>(a, b); } static bool Compare<T>(T x, T y) where T : class { return x == y; } } class Test { public static bool operator ==(Test a, Test b) { Console.WriteLine("Overloaded == called"); return a.Equals(b); } public static bool operator !=(Test a, Test b) { Console.WriteLine("Overloaded != called"); return a.Equals(b); } } }
Output
Inline: Overloaded == called
Generic:
Press any key to continue . . .
Follow Up 2
I do want to point out that changing my compare method to
static bool Compare<T>(T x, T y) where T : Test { return x == y; }
causes the overloaded == operator to be called. I guess without specifying the type (as a where), the compiler can't infer that it should use the overloaded operator... though I'd think that it would have enough information to make that decision even without specifying the type. | https://codedump.io/share/oeKXI4kZNpwb/1/can39t-operator--be-applied-to-generic-types-in-c | CC-MAIN-2017-04 | refinedweb | 428 | 55.13 |
The macro
NARG2 that we introduced in post still has a major disadvantage, it will not be able is cheating. It doesn’t count the number of arguments that it receives, but returns the number of commas plus one. In particular, even if it receives an empty argument list it will return
1. The following two macros better expresses this property:
#define _ARG16(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, ...) _15 #define HAS_COMMA(...) _ARG16(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0)
As before, these are constrained to a maximum number of arguments (here 16), but you will easily work out how to extend it to larger maximum values.
Now, when we want to write a macro that detects an empty argument we will be using the feature that a function macro that is not followed by an open parenthesis will be left alone. This we will do with the following macro that just transforms the following parenthesis and contents into a comma.
#define _TRIGGER_PARENTHESIS_(...) ,
The idea is to put the arguments that we want to test between the macro and its parenthesis, such that the macro only triggers if the arguments are empty:
_TRIGGER_PARENTHESIS_ __VA_ARGS__ (/*empty*/)
To do so we, must first check for some corner cases where special properties of the argument might mimic the behavior that we want to test.
*/)) \ )
Here we distinguish four different cases, of which the last is just the main idea as exposed above. The first helps to exclude the trivial case, that
__VA_ARGS__ already contains a comma by itself. The two others test if the two possible combinations of
_TRIGGER_PARENTHESIS_,
__VA_ARGS__ and
(/*empty*/) also already trigger a comma to their output.
Now the outcome of this will be calling the macro
_ISEMPTY with four different 0-1-values according to different cases that
__VA_ARGS__ presents. In particular, the case that
__VA_ARGS__ is empty corresponds exactly to the outcome
_ISEMPTY(0, 0, 0, 1). All other outcomes will indicate that it was non-empty. We will detect this case with the following helper macro.
#define _IS_EMPTY_CASE_0001 ,
and we leave all the other 15 cases undefined. Now with
#define PASTE5(_0, _1, _2, _3, _4) _0 ## _1 ## _2 ## _3 ## _4 #define _ISEMPTY(_0, _1, _2, _3) HAS_COMMA(PASTE5(_IS_EMPTY_CASE_, _0, _1, _2, _3))
we will exactly detect the case we are interested in.
As a test here comes all of that together in a block. This is not a reasonable C program but just something to run through the preprocessor to test the validity of the approach.
#define _ARG16(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, ...) _15 #define HAS_COMMA(...) _ARG16(__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0) #define _TRIGGER_PARENTHESIS_(...) , */)) \ ) #define PASTE5(_0, _1, _2, _3, _4) _0 ## _1 ## _2 ## _3 ## _4 #define _ISEMPTY(_0, _1, _2, _3) HAS_COMMA(PASTE5(_IS_EMPTY_CASE_, _0, _1, _2, _3)) #define _IS_EMPTY_CASE_0001 , #define EATER0(...) #define EATER1(...) , #define EATER2(...) (/*empty*/) #define EATER3(...) (/*empty*/), #define EATER4(...) EATER1 #define EATER5(...) EATER2 #define MAC0() () #define MAC1(x) () #define MACV(...) () #define MAC2(x,y) whatever ISEMPTY() ISEMPTY(/*comment*/) ISEMPTY(a) ISEMPTY(a, b) ISEMPTY(a, b, c) ISEMPTY(a, b, c, d) ISEMPTY(a, b, c, d, e) ISEMPTY((void)) ISEMPTY((void), b, c, d) ISEMPTY(_TRIGGER_PARENTHESIS_) ISEMPTY(EATER0) ISEMPTY(EATER1) ISEMPTY(EATER2) ISEMPTY(EATER3) ISEMPTY(EATER4) ISEMPTY(MAC0) ISEMPTY(MAC1) ISEMPTY(MACV) /* This one will fail because MAC2 is not called correctly */ ISEMPTY(MAC2)
Edit: What is presented here is a version with minor improvement to capture the case of
MAC0. Notice the restriction on the argument of
ISEMPTY that is apparent with
MAC2. In fact
ISEMPTY should work when it is called with macros as argument that expect
0,
1 or a variable list of arguments. If called with a macro
X as an argument that itself expects more than one argument (such as
MAC2) the expansion leads to an invalid use of that macro
X.
40 thoughts on “Detect empty macro arguments”
Clever but non-standard; see C99 §6.10.3 ¶4. Referring to a macro whose identifier-list ends with an ellipsis, the standard says:
I am not sure that I completely understand what you are referring to. C and the preprocessor are two different languages.
f()is a function call with an empty argument list.
f()is a macro call (if f is defined as such) with one argument, namely the empty token. You see that if you look at
f(,): this has two arguments, both empty tokens.
What the standard means here that a macro
must be called with at least one comma inside the ().
(If you found such an occurrence please point me to it, there are certainly still bugs and incompatibilities in there.)
As I understand it, given a macro defined
#define X(...) {__VA_ARGS__},
it is undefined behavior to invoke it in the form
X();
it may (and under GCC it does) resolve to
{ }, it may crash the compiler, it may resolve to
{nasal_demons(), etc., etc., etc.
I don’t see how you come to that conclusion. Maybe I didn’t explain myself well. The standard makes explicit reference to arguments that are empty in the context of the preprocessor. Before the text you cite, the standard explicitly allows for empty tokens in parameter lists:
So the usage is you are demonstrating is completely in line with the standard. This is a macro that has zero identifiers and that is called with one argument, consisting of no preprocessing token.
You also have other mention of empty arguments, e.g for stringyfication
So the empty token counts as a parameter? Cool—I had not realized that.
Cool, I don’t know. Actually this was just one of the difficulties from the start. The
PP_NARGmacro that you were citing was not able to distinguish
f()from
f(1)just because of that.
So at a first glance you would call that an inconsistency between the preprocessor and the rest of the language 😦
At a second, I have learned to live with it and even to take advantage 😉
You can make a work around for empty arguments case. The issue is that additional comma produces for empty parameters. You just can add a concatenation operator ## and it will resolve this issue. Here is an example.
#define COUNT(…) COUNT_ (0, ## __VA_ARGS__)
#define COUNT_(…) COUNT__ (__VA_ARGS__, 3, 2, 1, 0)
#define COUNT__(_0, _1, _2, _3, N, …) COUNT_ ## N (_1, _2, _3)
#define COUNT_0(…) 0
#define COUNT_1(…) 1
#define COUNT_2(…) 2
#define COUNT_3(…) 3
Would be nice such swallowing of the comma by the
##. Unfortunately this is only a GNU extension, which is even switched off when working in C99 mode. To cite the gcc documentation:
Well done. You’re real expert in PP.
This is an implementation of reflection mechanism in C. Definition of structures and other metadata in one one place.
Hi it mentions easily figuring out how to get around the 16 argument limitation. Could you please help me out on that one? Would love to pass 32 arguments to a c (…) function but __VA_ARGS_ seems to have that 16 argument limitation you note.
Hi, I don’t know exactly what you tried but the easiest would probably to download P99 and take it from there. The 16 arguments limit is really only for the one I give in the post, since the long one would be completely unreadable.
BTW, the C99 standard enforces that macros can take up to 127 arguments so that really shouldn’t be the limit.
So I’m trying to get this example working in Visual Studio 2008, but all ISEMPTY’s resolve to 0. Do you have any suggestions?
Hello Mark,
as far as I understand the Microsoft compilers don’t implement C99. In particular I remember having read that their preprocessor is not conforming to the C99 standard, and that there is a “wouldn’t fix” bug on the macro-argument counting trick.
So the only “simple” solution to that would be to use a different preprocessor, sorry.
Darn. Alright. Thank you! If I happen to figure anything out, I’ll be sure to post back here.
In the mean time I found a bug report and a workaround for this bug when occurring
VisualStudion C++. My guess would be that for their C implementation this is the same.
#define AMACRO(x) ()
IS_EMPTY(AMACRO) is true, where of course it should be false.
This is the flaw in your presentation and it is well-known. See Paul Mensonides post at.
I give a better and less complicated version of IS_EMPTY in my variadic data macro library in the Boost sandbox which is almost wholly based on Paul Mensonides brilliant version ( I have to do some tweaks for VC8 ).
Your assertion is incorrect.
ISEMPTY(AMACRO)gives the correct result, namely
1.
During the expansion of the fourth case of the
_ISEMPTYthe macro
_TRIGGER_PARENTHESIS_will only be expanded if and only if
__VA_ARGS__has been expanded to the empty token.
What your example and the discussion on the boost mailing list suggests, though, is that
ISEMPTYis not completely robust when it is called with macro names as parameters that receive multiple arguments. I improved the macro a bit to cover one more case and documented the cases for which it fails.
The preprocessor macro code to detect an empty argument list works fine on the flavors of Unix that I have tested (Linux, FreeBSD, OSX) with gcc, but fails on MS/Windows XP with MSVC. I have traced the problem down to how the MSVC preprocessor deals with the __VAR_ARGS__ token in a variadic macro that is defined in terms of another variadic macro. The following source code demonstrates the problem:
/* test_VA_ARGS
*/
#include
#include
#include
using namespace std;
int
main ()
{
#define THIRD_ARG(_1, _2, _3, ...) _3
#define TEST_THIRD_ARG(...) THIRD_ARG(__VA_ARGS__, 4, 5)
cout << "TEST_THIRD_ARG(1) = "
<< TEST_THIRD_ARG (1) << endl;
cout << "TEST_THIRD_ARG(1, 2) = "
<< TEST_THIRD_ARG (1, 2) << endl;
cout << "TEST_THIRD_ARG(1, 2, 10, 11) = "
<< TEST_THIRD_ARG (1, 2, 10, 11) << endl;
}
Here the TEST_THIRD_ARG variadic macro is defined in terms of the THIRD_ARG variadic macro where the argument list from TEST_THIRD_ARG, represented by __VA_ARGS__ in its definition, is expected to become the leading argument list parameters of the THIRD_ARG macro. This is the same as the _ARG16 and HAS_COMMA macros in the “Detect empty macro arguments” description. The result of using the TEST_THIRD_ARG macro should be the third argument of its argument list with arguments 4 and 5 being appended to its list.
On Unix systems with gcc the resulting executable produces the following output:
TEST_THIRD_ARG(1) = 5
TEST_THIRD_ARG(1, 2) = 4
TEST_THIRD_ARG(1, 2, 10, 11) = 10
This is what is expected. However, on MS/Windows XP with the MSVC compiler – Microsoft Visual Studio 9.0 (Compiler Version 15.00.30729.01 for 80×86) – the result is always the same:
TEST_THIRD_ARG(1) = 5
TEST_THIRD_ARG(1, 2) = 5
TEST_THIRD_ARG(1, 2, 10, 11) = 5
It seems that the __VA_ARGS__ token is not being expanded in the TEST_THIRD_ARG definition before the THIRD_ARG macro is being evaluated, or __VA_ARGS__ is being treated as a single argument regardless of whether it expands to a value that contains commas. To test this hypothesis the following can be added to the source code:
#define FIRST_ARG(_1, _2, _3, ...) _1
#define TEST_FIRST_ARG(...) FIRST_ARG(__VA_ARGS__, 4, 5)
cout << "TEST_FIRST_ARG(1) = "
<< TEST_FIRST_ARG(1) << endl;
cout << "TEST_FIRST_ARG(1, 2) = "
<< TEST_FIRST_ARG (1, 2) << endl;
This compiles and executes correctly on Unix with gcc, but will not compile on MS/Windows with MSVC:
.\test_VA_ARGS.cc(24) : error C2563: mismatch in formal parameter list
.\test_VA_ARGS.cc(24) : error C2568: '<<' : unable to resolve function overload
To confirm that __VA_ARGS__ is being treated by MSVC as a single argument in the TEST_FIRST_ARG definition, the last source code statement, above, can replaced with:
#define STRINGIFIED(...) #__VA_ARGS__
#define AS_STRING(...) STRINGIFIED(__VA_ARGS__)
cout << "AS_STRING (TEST_FIRST_ARG(1, 2)) = "
<< AS_STRING (TEST_FIRST_ARG (1, 2)) << endl;
On Unix with gcc this produces the expected result:
AS_STRING (TEST_FIRST_ARG(1, 2)) = 1
But on MS/Windows with MSVC this produces:
AS_STRING (TEST_FIRST_ARG(1, 2)) = 1, 2
So MSVC is evaluating the variadic macro definition in an unexpected manner. Is there a cl compiler option, or an in code pragma, to get it to expand __VA_ARGS__ and treat the result as additional parameters, if it contains commas, in the enclosing macro evaluation? If not, is there some clever way to work around this problem?
Hello,
yes MSVC is simply not complying to C99 and they don’t have the intention to be. So this has nothing to do with windows or unix as OS, but just with a compiler vendor being stubborn.
I will study your discoveries more precisely, but the first thing that strikes me is that you are using it clearly in C++ mode. I don’t have MSVC at hand, so I would very much appreciate if you could repeat the same tests with C. These two languages are sufficiently different such that this may matter, here.
Jens
Here is the C language version of the test source code:
/* test_VA_ARGS
*/
#include
int
main ()
{
#define THIRD_ARG(_1, _2, _3, ...) _3
#define TEST_THIRD_ARG(...) THIRD_ARG(__VA_ARGS__, 4, 5)
printf ("TEST_THIRD_ARG(1) = %d\n",
TEST_THIRD_ARG (1));
printf ("TEST_THIRD_ARG(1, 2) = %d\n",
TEST_THIRD_ARG (1, 2));
printf ("TEST_THIRD_ARG(1, 2, 10, 11) = %d\n",
TEST_THIRD_ARG (1, 2, 10, 11));
#define FIRST_ARG(_1, _2, _3, ...) _1
#define TEST_FIRST_ARG(...) FIRST_ARG(__VA_ARGS__, 4, 5)
printf ("TEST_FIRST_ARG(1) = %d\n",
TEST_FIRST_ARG(1));
#define STRINGIFIED(...) #__VA_ARGS__
#define AS_STRING(...) STRINGIFIED(__VA_ARGS__)
printf ("AS_STRING (TEST_FIRST_ARG(1, 2)) = %s\n",
AS_STRING (TEST_FIRST_ARG (1, 2)));
}
Output on Unix with gcc:
TEST_THIRD_ARG(1) = 5
TEST_THIRD_ARG(1, 2) = 4
TEST_THIRD_ARG(1, 2, 10, 11) = 10
TEST_FIRST_ARG(1) = 1
AS_STRING (TEST_FIRST_ARG(1, 2)) = 1
Output on MS/Windows with MSVC:
TEST_THIRD_ARG(1) = 5
TEST_THIRD_ARG(1, 2) = 5
TEST_THIRD_ARG(1, 2, 10, 11) = 5
TEST_FIRST_ARG(1) = 1
AS_STRING (TEST_FIRST_ARG(1, 2)) = 1, 2
The problem is the same as with the C++ version of the test source code. Note that the production code is C++. I would expect the same preprocessor to be used for both languages.
I’d be happy to run any further tests with MSVC on potential solutions.
Thnx.
Ok, now I see and this explains well how MSVC is not conforming to the standard. The standard prescribes very much in detail in which order parameter replacement has to take place, here:
TEST_THIRD_ARG(1, 2)leads to
THIRD_ARG(1, 2, 4, 5)
THIRD_ARGsees four arguments.
So effectively the correct answer is 4.
And it follows that MSVC is not standard compliant for C but probably there is also the same problem for C++. The two committees tend to try to have this sort of properties in sync.
This property of the evaluation order is deeply build into all that P99 does, so I don’t think there would be an easy way out of this. You’d somehow have to convince the compiler to expand all macro arguments once more. Adding such a thing would make the code of P99 even more terrible than it is already and in particular it would then be completely impossible to maintain.
The only solutions I see for you are 1. complain 2. use another preprocessor 3. use another compiler. There seem to be many alternatives, even on windows. Or you could look in BOOST and see how they work around that problem.
A bug report has been submitted to Microsoft.
Using another preprocessor or compiler are not viable options for the production project that has encountered the problem.
I’ll delve into Boost and see what I can find.
Thnx.
Hello,
Just writing a comment to thank you for the detailed post, explaining the use of this macro. In my project I am trying to heavily utilize the preprocessor and needed a way to detect if there are no arguments to a macro or not. The macros above is really clever and had my mind blown. Will attempt to integrate it into my project immediately. Thanks!
Thanks for the feedback.
Is there anything I could do to convince you to use P99 directly?
Jens
I will admit I have checked out most of P99 code and most of the functionality offered I don’t need so I just omitted it. On the other hand what I needed I took in and altered the calling code to conform with the calling convention of my project. It’s a GUI engine which at least for now does not seem to be going open-source. Might change in the future.
So in short, basically for clarity of code and just cause I am a bit picky as to how I want my code to look I just adopted it into my project and did not use it directly.
Of course I give due credit in all comments and whenever I release the project the P99 headers and this blog will be in the credits.
It’s not just this NARG macro but the way that you use the preprocessor. By studying it I realized that there are so many potential and safe uses of the preprocessor that I had totally disregarded. You opened up a lot of new ideas in my mind. Again thanks!
Hello!
Thanx for the idea, I have small improvement for your realization, see:
The main idea is the same as yours but instead of messing with macro-calls I’m using concatenation in order to detect if __VA_ARGS__ is *empty*.
This is not only simpler but also doesn’t generates C4003 (not enough actual parameters for macro ‘identifier’) for expressions like “__VA_ARGS__ (/*empty*/)” if
__VA_ARGS__ is equal to the name of some non variadic macro.
Hi, thanks for the comment.
Actually your solution only works with a very restricted context, namely that your argument starts and ends with a token that can be concatenated to identifier tokens.
My solution, and all of P99 builds on that, also works if the macro argument(s) contain arbitrary token sequences.
Jens
Hello!
Can you provide an example?
I don’t see any problems: my compiler expands IS_EMPTY(arg) to 1 if arg expands to (event if arg is a macro or macro call). Otherwise IS_EMPTY expands to 0.
An example would be
IS_EMPTY( "test" ). If I see it correctly such a call unconditionally forces the prepropressing phase to do the following operation:
maybe your compiler accepts this, but this is a constraint violation. Your compiler should issue a diagnostic in the vein of
You didn’t tell me which compiler you are using, the above message is from gcc. And from all that I can read in the standard(s) this interpretation of gcc is correct.
> I don’t see any problems: my compiler expands IS_EMPTY(arg) to 1 if arg expands to (event if arg is a macro or macro call). Otherwise IS_EMPTY expands to 0.
Read as “I don’t see any problems: my compiler expands IS_EMPTY(arg) to 1 if arg expands to nothing (event if arg is a macro or macro call). Otherwise IS_EMPTY expands to 0.”
I’ve read the documentation, you’re seemed to be right, but it works for me. Compiler is MSVС 2010. As you know, MSVC preprocessor does not standard-complaint and has a lot of problems…
Ah, this explains it.
But otherwise, do you have some success by using P99 with MSVC 2010? This would be the first positive report for that.
Jens
I’m actually using C++, so macros are used only if there is no other ways to generate code. Usually they are simple and BOOST::PREPROCESSOR is enough for me. As for BOOST::PREPROCESSOR, I’ve never saw any problems with it.
Actually, with C++ I need only “preprocessing loops”, e.g. generate some code for each func argument. All other metaprograming things are done using templates magic.
The two center cases of _ISEMPTY seem pointless:
First test:
From this it is known that __VA_ARGS__ is either empty or has a single argument. I’m assuming this will be the case in all following examples:
Second test:
Possibilities:
. __VA_ARGS__ is empty: HAS_COMMA is 0
. __VA_ARGS__ final (only) argument is (). HAS_COMMA is 1
. __VA_ARGS__ is anything else. HAS_COMMA is 0
Therefore, no useful information gleaned.
Third test:
Possibilities:
. __VA_ARGS__ is empty: HAS_COMMA is 0
. __VA_ARGS__ final (only) argument is a function macro name. This is expanded, and HAS_COMMA value depends on the output
. __VA_ARGS__ is anything else: HAS_COMMA is 0
Therefore, once again, no useful information gleaned.
The only important test is the fourth:
From which it can be discerned whether or not __VA_ARGS__ is truly empty or simply has a single argument.
Nice analysis, unfortunately it is incomplete. Look at the last case
and let us have a look under which circumstances the inner part will expand in something that contains a comma:
__VA_ARGS__is empty, this is obviously the case that we want to detect.
__VA_ARGS__expands to something with a comma. This is captured by the first test.
__VA_ARGS__expands to “
( something )“, this is discriminated by the second test, that, as you state gives us exactly that information.
__VA_ARGS__expands to a function like macro, which presented with parenthesis produces a comma. That case is captured by the third test.
So the test 2 and 3 that you question are well necessary for a complete case analysis.
I hadn’t thought of that. Very nice!
Edit: From looking at the resulting examples, it seems you actually intended for function macros to be called when __VA_ARGS__ contains either a function macro name or (). Why?
I am not sure that I completely understand your question. The difficulties of the implementation of that macro are actually the cases that you mention, when there are () or a function macro. I just want the macro to be able to handle these cases in addition to all the other more trivial cases that require less machinery.
#define ISEMPTY(…) (sizeof(#__VA_ARGS__) == 1)
Looks tempting. Two arguments against its general use:
#ifand in the other
P99_IFmacros that P99 has. | https://gustedt.wordpress.com/2010/06/08/detect-empty-macro-arguments/?shared=email&msg=fail | CC-MAIN-2019-04 | refinedweb | 3,688 | 71.14 |
OLED displays based upon the SSD1306 chip set are small, high contract display. These displays generate their own light and so no backlight is required.
Purchasing
There are a number of breakout board available using these displays. This driver has been tested with the following:
Board are also available from Adafruit.
Hardware
The OLED displays are available with a SPI or I2C interfaces. Wiring for the I2C interface is as follows:
Software
The application below uses the
GraphicsLibrary to draw three lines of text on a 128x64 pixel SSD1306 OLED display:
using System.Threading; using Netduino.Foundation.Displays; namespace SSD1306Test { public class Program { public static void Main() { var oled = new SSD1306(); var display = new GraphicsLibrary(oled); display.Clear(true); display.CurrentFont = new Font8x8(); display.DrawText(4, 10, 0, "NETDUINO 3 WiFi"); display.DrawText(48, 25, 0, "says"); display.DrawText(16, 40, 2, "Hello, world."); display.DrawLine(0, 60, 127, 60); display.Show(); Thread.Sleep(Timeout.Infinite); } } }
API
The
SSD1306 class is derived from the
DisplayBase class.
SSD1306 objects can control a number of SSD1306 based OED displays.
This class implements uses a buffer to contain the image as it is built up. This means that the image can be built up before it is displayed.
Enums
enum BitmapMode
Determine how bitmaps should be placed into the display buffer. Possible options are:
enum ScrollDirection
Defines the scroll direction for the
StartScroll method.
enum DisplayType
Display types supported by this class.
Properties
byte Contrast
Change the contrast of the display. A value of
0 will dim the display.
bool IgnoreOutOfBoundsPixels
Note: This property is derived from the
DisplayBase base class.
bool InvertDisplay
Setting this property to
true will invert the display immediately. A value of
false returns the display to normal.
bool Sleep
Put the display to sleep (
true) or wake up the display (
true). This reduces the amount of power that the display consumes.
Constructors
SSD1306(byte address = 0x3c, ushort speed = 400, DisplayType displayType = DisplayType.OLED128x64)
Create a
SSD1306 object with the default settings for a 128x64 pixel OLED display with an I2C interface.
Methods
void Show()
Copy the contents of the internal buffer to the display. This action makes the image in the internal buffer visible to the user.
void Clear(bool updateDisplay = false)
Clear the display buffer.
The display contents will only be updated immediately when
updateDisplay is set to true. If
updateDisplay is false then the internal buffer will be cleared without updating the image on view to the user. ine in the bitmap and the
height parameter gives the number lines in the bitmap.
bitmapMode determines how the bitmap is copied into the display buffer. Currently
BitmapMode.Copy is the only mode supported by this driver.
void StartScrolling(ScrollDirection direction)
Start scrolling in the specified direction using reasonable default settings.
void void StartScrolling(ScrollDirection direction, byte startPage, byte endPage)
Scroll in the specified direction. This method allows the application finer control over the scrolling compared with the default settings.
void StopScrolling()
Stop scrolling the display.
This method will be called automatically before any current change is made to the scroll direction. It can also be called when the application needs to stop the display scrolling. In this case it may be necessary for the application to re-display the current buffer using the
Show method. | http://netduino.foundation/Library/Displays/SSD1306/ | CC-MAIN-2018-05 | refinedweb | 548 | 59.4 |
Problem with CrunchBase API and jQuery $.getJSON
I am trying to simply send an alert with a "name", but It doesn't seem to work. Advice?
$(document).ready(function() { $.getJSON("", function(data) { alert("Hello: " + data.name); }); });
Here is what the JSON contains:
{"crunchbase_url": "", "permalink": "google", "name": "Google"}
Answers
Normally you'd use JSONP here by adding &callback=? to your URL, however a JSONP callback is not supported in this case, from the
List Entities
To retrieve a list of all of the entities in a certain namespace on CrunchBase, use a URL of the form:<plural-namespace>
The plural available namespaces are:
- companies
- people
- financial-organizations
- products
- service-providers
This action does not support JavaScript callbacks.
The bottom line is the most important, you'll see that this: still results in regular JSON, not JSONP.
If you're not Crunchbase, you can't send that request. For security reasons, only may send AJAX requests to. (Imagine we were talking about and I were logged in. It'd be a problem if just any site could send arbitrary requests to with my cookies attached.)
The
The URL is a similar resource to the one you mentioned, but this particular URL allows you to use JSON-P, whereas the one you posted does not. jQuery allows you to do this easily: pass the URL to $.getJSON as? (the bit about the callback is important!), and jQuery will fill in the blanks and handle the magic script loading behind the scenes. It's very fancy :)
Need Your Help
How do I require files in other directory branches?
php recursion require require-onceWhen I try to use require or require_once, it will work fine if the file to be required is in the same subdirectory, but the moment it sees a file outside of their subdirectory, it generates a fatal
calling external js twice
javascript internet-explorer externalIs it possible to use external js files and jquery twice on the one html doc? I have the first one running but the second time it calls it doesn't work. Also the external js doesn't work when opene... | http://unixresources.net/faq/4331308.shtml | CC-MAIN-2019-04 | refinedweb | 354 | 61.16 |
Announcing TypeScript 2.9 RC
Daniel
Today we’re excited to announce and get some early feedback with TypeScript 2.9’s Release Candidate. To get started with the RC, you can access it through NuGet, or use npm with the following command:
npm install -g typescript@rc
You can also get editor support by
- Downloading for Visual Studio 2015 (with Update 3)
- Downloading for Visual Studio 2017 (for version 15.2 or later)
- Following directions for Visual Studio Code and Sublime Text.
Let’s jump into some highlights of the Release Candidate!
Support for symbols and numeric literals in
keyof and mapped object types
TypeScript’s
keyof operator is a useful way to query the property names of an existing type.
interface Person { name: string; age: number; } // Equivalent to the type // "name" | "age" type PersonPropertiesNames = keyof Person;
Unfortunately, because
keyof predates TypeScript’s ability to reason about
unique symbol types,
keyof never recognized symbolic keys.
const baz = Symbol("baz"); interface Thing { foo: string; bar: number; [baz]: boolean; // this is a computed property type } // Error in TypeScript 2.8 and earlier! // `typeof baz` isn't assignable to `"foo" | "bar"` let x: keyof Thing = baz;
TypeScript 2.9 changes the behavior of
keyof to factor in both unique symbols as well as numeric literal types. As such, the above example now compiles as expected.
keyof Thing now boils down to the type
"foo" | "bar" | typeof baz.
With this functionality, mapped object types like
Partial,
Required, or
Readonly also recognize symbolic and numeric property keys, and no longer drop properties named by symbols:
type Partial<T> = { [K in keyof T]: T[K] } interface Thing { foo: string; bar: number; [baz]: boolean; } type PartialThing = Partial<Thing>; // This now works correctly and is equivalent to // // interface PartialThing { // foo?: string; // bar?: number; // [baz]?: boolean; // }
Unfortunately this is a breaking change for any usage where users believed that for any type
T,
keyof T would always be assignable to a
string. Because symbol- and numeric-named properties invalidate this assumption, we expect some minor breaks which we believe to be easy to catch. In such cases, there are several possible workarounds.
If you have code that’s really meant to only operate on string properties, you can use
Extract<keyof T, string> to restrict
symbol and
number inputs:
function useKey<T, K extends Extract<keyof T, string>>(obj: T, k: K) { let propName: string = k; // ... } If you have code that's more broadly applicable and can handle more than just strings, you should be able to substitute string with string | number | symbol, or use the built-in type alias PropertyKey. function useKey<T, K extends keyof T>(obj: T, k: K) { let propName: string | number | symbol = k; // ... }
Alternatively, users can revert to the old behavior under the
--keyofStringsOnly compiler flag, but this is meant to be used as a transitionary flag.
import() types
One long-running pain-point in TypeScript has been the inability to reference a type in another module, or the type of the module itself, without including an import at the top of the file.
In some cases, this is just a matter of convenience – you might not want to add an import at the top of your file just to describe a single type’s usage. For example, to reference the type of a module at an arbitrary location, here’s what you’d have to write before TypeScript 2.9:
import * as _foo from "foo"; export async function bar() { let foo: typeof _foo = await import("foo"); }
In other cases, there are simply things that users can’t achieve today – for example, referencing a type within a module in the global scope is impossible today. This is because a file with any imports or exports is considered a module, so adding an import for a type in a global script file will automatically turn that file into a module, which drastically changes things like scoping rules and strict module within that file.
That’s why TypeScript 2.9 is introducing the new
import(...) type syntax. Much like ECMAScript’s proposed
import(...) expressions, import types use the same syntax, and provide a convenient way to reference the type of a module, or the types which a module contains.
// foo.ts export interface Person { name: string; age: number; } // bar.ts export function greet(p: import("./foo").Person) { return ` Hello, I'm ${p.name}, and I'm ${p.age} years old. `; }
Notice we didn’t need to add a top-level import specify the type of
p. We could also rewrite our example from above where we awkwardly needed to reference the type of a module:
export async function bar() { let foo: typeof import("./foo") = await import("./foo"); }
Of course, in this specific example
foo could have been inferred, but this might be more useful with something like the TypeScript language server plugin API.
Breaking changes
keyof types include symbolic/numeric properties
As mentioned above, key queries/
keyof types now include names that are
symbols and
numbers, which can break some code that assumes
keyof T is assignable to
string. Users can avoid this by using the
--keyofStringsOnly compiler option:
// tsconfig.json { "compilerOptions": { "keyofStringsOnly": true } }
Trailing commas not allowed on rest parameters
#22262
This break was added for conformance with ECMAScript, as trailing commas are not allowed to follow rest parameters in the specification.
Unconstrained type parameters are no longer assignable to
object in
strictNullChecks
#24013
The following code now errors:
function f<T>(x: T) { const y: object | null | undefined = x; }
Since generic type parameters can be substituted with any primitive type, this is a precaution TypeScript has added under
strictNullChecks. To fix this, you can add a constraint on
object:
// We can add an upper-bound constraint here. // vvvvvvvvvvvvvvv function f<T extends object>(x: T) { const y: object | null | undefined = x; }
never can no longer be iterated over
Values of type
never can no longer be iterated over, which may catch a good class of bugs. Users can avoid this behavior by using a type assertion to cast to the type
any (i.e.
foo as any).
What’s next?
We try to keep our plans easily discoverable on the TypeScript roadmap for everything else that’s coming in 2.9 and beyond. TypeScript 2! | https://devblogs.microsoft.com/typescript/announcing-typescript-2-9-rc/ | CC-MAIN-2019-13 | refinedweb | 1,042 | 60.04 |
Hi,
I studied polymorphism and understand that it can do dynamic method binding like below.
Assuming that class Animal is abstract class.
public class AnimalReference { public static void main(String args[]) Animal ref // set up var for an Animal Cow aCow = new Cow("Bossy"); // makes specific objects Dog aDog = new Dog("Rover"); // now reference each as an Animal ref = aCow; ref.speak(); ref = aDog; ref.speak(); }
I used to create instance of ArrayList like:
ArrayList myList = new ArrayList();
But usually I figured that people write:
Collection myList = new ArrayList();
So my confusion is what is the benefit of declaring as Collection? Also I didn't know you can have "Collection" (which is an interface not abstract class) in front of "myList".
Why it is not good practice to just say:
ArrayList myList = new ArrayList();
I read Collection interface and ArrayList Java documents as well as online tutorials but still not really clear.. Could anyone give me some explanation? | http://ansaurus.com/question/3356113-what-is-the-benefit-of-polymorphism-using-collection-interface-to-create-arraylist-object | CC-MAIN-2017-34 | refinedweb | 158 | 52.19 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
On 03/20/2014 03:20 PM, Adhemerval Zanella wrote: > diff --git a/intl/loadmsgcat.c b/intl/loadmsgcat.c > index b96a997..d47b903 100644 > --- a/intl/loadmsgcat.c > +++ b/intl/loadmsgcat.c > @@ -62,6 +62,7 @@ char *alloca (); > #ifdef _LIBC > # include <langinfo.h> > # include <locale.h> > +# define PRI_MACROS_BROKEN 0 > #endif > > #if (defined HAVE_MMAP && defined HAVE_MUNMAP && !defined DISALLOW_MMAP) \ This hunk could go in immediately to fix the -Wundef issues while take our time to merge a new gettext update. I was looking at this today, but it's going to be more work than I have free time for this week. Even though Steve Ellcey has gotten upstream to change the code such that PRI_MACROS_BROKEN is always defined, there is no stable release with that change yet. Cheers, Carlos. | http://sourceware.org/ml/libc-alpha/2014-05/msg00057.html | CC-MAIN-2020-05 | refinedweb | 145 | 68.77 |
06 August 2010 14:47 [Source: ICIS news]
TORONTO (ICIS)--Methanex would be the “logical buyer” for BP’s 36.9% stake in the two firms’ 1.7m tonne/year Atlas methanol joint venture in Trinidad, a Canadian analyst said on Friday.
BP is under pressure to sell assets to pay for the massive ?xml:namespace>
Chemical assets sales, including the Atlas stake, would be an option for BP, John Cummings, an independent Toronto-based petrochemicals analyst, said in a research note to clients.
While BP had sold major chemical assets in past years, it remained a major producer of paraxylene, acetic acid and acetyls, Cummings said. Some BP chemical assets, including Atlas, were held in joint ventures, he said.
But Cummings noted that selling the Atlas stake – estimated to be worth at most $300m (€228m) - would add only little, when compared with the billions of dollars BP is seeking to raise through upstream oil and gas asset divestments..
Vancouver-based Methanex, for its part, has said it would want to buy the stake, should it come up for sale.
“To the extent that they [BP] want to monetise that [Atlas] stake, we want to be the 100% owner of that plant, there is no question,” chief executive Bruce Aitken told analysts during the company’s second-quarter results conference call.
However, Aitken said Methanex had an “outstanding relationship” with BP in
Longer-term, Methanex was interested in natural gas drilling in
“We are not going to do anything to accelerate [BP’s] decision, and I am sure they have much bigger things to worry about today than worrying about their share in the methanol plant,” Aitken added.
As for Trinidad’s other major methanol producer, Methanol Holdings (Trinidad) Limited (MHTL), Aitken said the
There had been speculation last year that Methanex could acquire control of MHTL after the firm's majority stakeholder came under pressure during the financial crisis and was bailed out by Trinidad's central bank.
Meanwhile, BP on Tuesday announced it would sell its oil and gas assets in
BP also said it was seeking buyers for upstream assets in
Last month, BP said it would raise $7bn through assets sales in the
($1 = €0.76)
For more on Methanex, B | http://www.icis.com/Articles/2010/08/06/9383042/methanex-logical-buyer-for-bps-atlas-methanol-stake.html | CC-MAIN-2014-41 | refinedweb | 375 | 62.41 |
NAME
boot - halt or reboot the system
SYNOPSIS
#include <sys/types.h> #include <sys/systm.h> #include <sys/reboot.h> void boot(int howto);
DESCRIPTION
The boot() function handles final system shutdown, and either halts or reboots the system. The exact action to be taken is determined by the flags passed in howto and by whether or not the system has finished autoconfiguration. If the system has finished autoconfiguration, boot() does the following: 1. If this is the first invocation of boot() and the RB_NOSYNC flag is not set in howto, syncs and unmounts the system disks by calling vfs_unmountall(9). 2. Disables interrupts. 3. If rebooting after a crash (i.e., if RB_DUMP is set in howto, but RB_HALT is not), saves a system crash dump. 4. Runs any shutdown hooks previously registered.) | http://manpages.ubuntu.com/manpages/karmic/man9/boot.9freebsd.html | CC-MAIN-2014-52 | refinedweb | 134 | 58.79 |
).
6.x Series¶
IPython 6.5.0¶
Miscellaneous bug fixes and compatibility with Python 3.7.
IPython 6.4.0¶
Everything new in IPython 5.7
IPython 6.3.1¶
This is a bugfix release to switch the default completions back to IPython’s own completion machinery. We discovered some problems with the completions from Jedi, including completing column names on pandas data frames.
You can switch the completions source with the config option
Completer.use_jedi.
IPython 6.3¶
IPython 6.3 contains all the bug fixes and features in IPython 5.6. In addition:
- A new display class
IPython.display.Codecan be used to display syntax highlighted code in a notebook (PR #10978).
- The
htmlmagic now takes a
--isolatedoption to put the content in an iframe (PR #10962).
- The code to find completions using the Jedi library has had various adjustments. This is still a work in progress, but we hope this version has fewer annoyances (PR #10956, PR #10969, PR #10999, PR #11035, PR #11063, PR #11065).
- The post event callbacks are now always called, even when the execution failed (for example because of a
SyntaxError).
- The execution info and result objects are now made available in the corresponding pre or post
*_run_cellevent callbacks in a backward compatible manner (#10774 and PR #10795).
- Performance with very long code cells (hundreds of lines) is greatly improved (PR #10898). Further improvements are planned for IPython 7.
You can see all pull requests for the 6.3 milestone.
IPython 6.2¶
IPython 6.2 contains all the bugs fixes and features available in IPython 5.5, like built in progress bar support, and system-wide configuration
The following features are specific to IPython 6.2:
Function signature in completions¶
Terminal IPython will now show the signature of the function while completing. Only the currently highlighted function will show its signature on the line below the completer by default. This functionality is recent, so it might be limited; we welcome bug reports and requests for enhancements. PR #10507
Assignments return values¶
IPython can now trigger the display hook on the last assignment of cells. Up until 6.2 the following code wouldn’t show the value of the assigned variable:
In[1]: xyz = "something" # nothing shown
You would have to actually make it the last statement:
In [2]: xyz = "something else" ... : xyz Out[2]: "something else"
With the option
InteractiveShell.ast_node_interactivity='last_expr_or_assign'
you can now do:
In [2]: xyz = "something else" Out[2]: "something else"
This option can be toggled at runtime with the
%config magic, and will
trigger on assignment
a = 1, augmented assignment
+=,
-=,
|= …
as well as type annotated assignments:
a:int = 2.
IPython 6.1¶
Quotes in a filename are always escaped during tab-completion on non-Windows. PR #10069
Variables now shadow magics in autocompletion. See #4877 and PR #10542.
Added the ability to add parameters to alias_magic. For example:
In [2]: %alias_magic hist history --params "-l 2" --line Created `%hist` as an alias for `%history -l 2`. In [3]: hist %alias_magic hist history --params "-l 30" --line %alias_magic hist history --params "-l 2" --line
Previously it was only possible to have an alias attached to a single function, and you would have to pass in the given parameters every time:
In [4]: %alias_magic hist history --line Created `%hist` as an alias for `%history`. In [5]: hist -l 2 hist %alias_magic hist history --line. PR #10532
IPython.displayhas gained a
%markdowncell magic. PR #10563
%configoptions can now be tab completed. PR #10555
%configwith no arguments are now unique and sorted. PR #10548
Completion on keyword arguments does not duplicate
=sign if already present. PR #10547
%run -m <module>now
<module>passes extra arguments to
<module>. PR #10546
completer now understand “snake case auto complete”: if
foo_bar_kittensis a valid completion, I can type
f_b<tab>will complete to it. PR #10537
tracebacks are better standardized and will compress
/path/to/hometo
~. PR #10515
The following changes were also added to IPython 5.4, see what’s new in IPython 5.4 for more detail description:
TerminalInteractiveShellis configurable and can be configured to (re)-use the readline interface.
- objects can now define a
_repr_mimebundle_
- Execution heuristics improve for single line statements
display()can now return a display id to update display areas.
IPython 6.0¶
Released April 19th, 2017
IPython 6 features a major improvement in the completion machinery which is now capable of completing non-executed code. It is also the first version of IPython to stop compatibility with Python 2, which is still supported on the bugfix only 5.x branch. Read below for a non-exhaustive list of new features.
Make sure you have pip > 9.0 before upgrading. You should be able to update by using:
pip install ipython --upgrade
Note
If your pip version is greater than or equal to pip 9.0.1 you will automatically get the most recent version of IPython compatible with your system: on Python 2 you will get the latest IPython 5.x bugfix, while in Python 3 you will get the latest 6.x stable version.
New completion API and Interface¶
The completer Completion API has seen an overhaul, and the new completer has plenty of improvements both from the end users of terminal IPython and for consumers of the API.
This new API is capable of pulling completions from
jedi, thus allowing
type inference on non-executed code. If
jedi is installed, completions like
the following are now possible without code evaluation:
>>> data = ['Number of users', 123_456] ... data[0].<tab>
That is to say, IPython is now capable of inferring that
data[0] is a string,
and will suggest completions like
.capitalize. The completion power of IPython
will increase with new Jedi releases, and a number of bug-fixes and more completions
are already available on the development version of
jedi if you are curious.
With the help of prompt toolkit, types of completions can be shown in the completer interface:
The appearance of the completer is controlled by the
c.TerminalInteractiveShell.display_completions option that will show the
type differently depending on the value among
'column',
'multicolumn'
and
'readlinelike'
The use of Jedi also fulfills a number of requests and fixes a number of bugs like case-insensitive completion and completion after division operator: See PR #10182.
Extra patches and updates will be needed to the
ipykernel package for
this feature to be available to other clients like Jupyter Notebook, Lab,
Nteract, Hydrogen…
The use of Jedi should be barely noticeable on recent machines, but
can be slower on older ones. To tweak the performance, the amount
of time given to Jedi to compute type inference can be adjusted with
c.IPCompleter.jedi_compute_type_timeout. The objects whose type were not
inferred will be shown as
<unknown>. Jedi can also be completely deactivated
by using the
c.Completer.use_jedi=False option.
The old
Completer.complete() API is waiting deprecation and should be
replaced replaced by
Completer.completions() in the near future. Feedback on
the current state of the API and suggestions are welcome.
Python 3 only codebase¶
One of the large challenges in IPython 6.0 has been the adoption of a pure Python 3 codebase, which has led to upstream patches in pip, pypi and warehouse to make sure Python 2 systems still upgrade to the latest compatible Python version.
We remind our Python 2 users that IPython 5 is still compatible with Python 2.7, still maintained and will get regular releases. Using pip 9+, upgrading IPython will automatically upgrade to the latest version compatible with your system.
Warning
If you are on a system using an older version of pip on Python 2, pip may
still install IPython 6.0 on your system, and IPython will refuse to start.
You can fix this by upgrading pip, and reinstalling ipython, or forcing pip to
install an earlier version:
pip install 'ipython<6'
The ability to use only Python 3 on the code base of IPython brings a number of advantages. Most of the newly written code make use of optional function type annotation leading to clearer code and better documentation.
The total size of the repository has also decreased by about 1500 lines (for the first time excluding the big split for 4.0). The decrease is potentially a bit more for the sour as some documents like this one are append only and are about 300 lines long.
The removal of the Python2/Python3 shim layer has made the code quite a lot clearer and more idiomatic in a number of locations, and much friendlier to work with and understand. We hope to further embrace Python 3 capabilities in the next release cycle and introduce more of the Python 3 only idioms (yield from, kwarg only, general unpacking) in the IPython code base, and see if we can take advantage of these to improve user experience with better error messages and hints.
Configurable TerminalInteractiveShell, readline interface¶
IPython gained a new
c.TerminalIPythonApp.interactive_shell_class option
that allows customizing the class used to start the terminal frontend. This
should allow a user to use custom interfaces, like reviving the former readline
interface which is now a separate package not actively maintained by the core
team. See the project to bring back the readline interface: rlipython.
This change will be backported to the IPython 5.x series.
Misc improvements¶
- The
capturemagic can now capture the result of a cell (from an expression on the last line), as well as printed and displayed output. PR #9851.
- Pressing Ctrl-Z in the terminal debugger now suspends IPython, as it already does in the main terminal prompt.
- Autoreload can now reload
Enum. See #10232 and PR #10316
- IPython.display has gained a
GeoJSONobject. PR #10288 and PR #10253
Functions Deprecated in 6.x Development cycle¶
ipython_extension_dirprints a warning that this location is pending deprecation. This should only affect users still having extensions installed with
%install_extwhich has been deprecated since IPython 4.0, and removed in 5.0. Extensions still present in
ipython_extension_dirmay shadow more recently installed versions using pip. It is thus recommended to clean
ipython_extension_dirof any extension now available as a package.
IPython.utils.warnwas deprecated in IPython 4.0, and has now been removed. instead of
IPython.utils.warninbuilt
warningsmodule is used.
- The function
IPython.core.oinspect.py:call_tipis unused, was marked as deprecated (raising a
DeprecationWarning) and marked for later removal. PR #10104
Backward incompatible changes¶
Functions Removed in 6.x Development cycle¶
The following functions have been removed in the development cycle marked for Milestone 6.0.
IPython/utils/process.py-
is_cmd_found
IPython/utils/process.py-
pycmd2argv
- The
--deep-reloadflag and the corresponding options to inject
dreloador
reloadinto the interactive namespace have been removed. You have to explicitly import
reloadfrom
IPython.lib.deepreloadto use it.
- The
profileused to print the current IPython profile, and which was deprecated in IPython 2.0 does now raise a
DeprecationWarningerror when used. It is often confused with the
prunand the deprecation removal should free up the
profilename in future versions. | http://ipython.readthedocs.io/en/stable/whatsnew/version6.html | CC-MAIN-2018-34 | refinedweb | 1,837 | 56.45 |
Hi,
I am trying to pull together a unit testing for routes but I am
getting confused. I have read AWDWR section 21.4 which explains how
to code the assertions.
also basically says the same. The problem I have is working out what
else I need in my test/unit/test_routing.rb.
require File.dirname(FILE) + ‘/…/test_helper’
def test_recognizes
ActionController::Routing.use_controllers! [“quote”]
load “config/routes.rb”
test “internal routing” do
assert_recognizes({“controller” => “quote” , “action” =>
“index” }, “/quote” )
assert_recognizes({“controller” => “quote” , “action” =>
“new” }, “/” )
end
end
def test_routing
true
end
The output is the following:
$ ruby -I development test/unit/routing_test.rb
Loaded suite test/unit/routing_test
Started
Finished in 0.000182 seconds.
0 tests, 0 assertions, 0 failures, 0 errors
Agreed it is super fast, but there appears to be no testing going on.
It’s early days on my testing on Rails so I am sure I am missing
something major here. Thanks for any pointers in the right direction.
O. | https://www.ruby-forum.com/t/unit-testing-of-routes/175547 | CC-MAIN-2021-49 | refinedweb | 162 | 59.4 |
Using UART on Raspberry Pi – PythonVivek Kartha
Contents.
Freeing up UART pins on Raspberry Pi GPIO
By default Raspberry Pi’s UART pins (GPIO 14 and 15) are configured as a serial console. It outputs all the kernel data during boot. We need to free up these pins for our use. For this launch terminal,
-’ and ‘kgdboc=ttyAMA0,115200’.
sudo nano /boot/cmdline.txt
- The remaining file looks like,
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p6 rootfstype=ext4 elevator=deadline rootwait
- Save the file, Ctrl + O
- Close the editor, Ctrl + X
- Now edit inittab, file containing serial console data
sudo nano /etc/inittab
- Comment out the line ‘2:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100’
#2:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
- Save the file, Ctrl + O
- Close the editor, Ctrl + X
- Reboot Raspberry Pi by using the command, sudo reboot.
Now you have freed the UART pins.
You can verify whether the Pi is sending and receiving UART data by installing the tool Minicom.
- Short the Rx and Tx pins on Pi (GPIO 14 and 15), such that it will receive the same data as it transmits.
- Install minicom,
sudo apt-get install minicom
- And launching it,
minicom -b 115200 -o -D /dev/ttyAMA0
Where,
- 115200 is the baud rate
- ttyAMA0 is the port
- Verify whether the pi is receiving the same data as it transmits.
Now the module serial can be imported to python by using ‘import serial‘.
Example Program
The following python program reads 10 characters from the serial port and sends back it.
import serial ser = serial.Serial ("/dev/ttyAMA0") #Open named port ser.baudrate = 9600 #Set baud rate to 9600 data = ser.read(10) #Read ten characters from serial port to data ser.write(data) #Send back the received data ser.close()
For More Information : pySerial API
Any doubts or suggestions? Comment below. | https://electrosome.com/uart-raspberry-pi-python/ | CC-MAIN-2016-44 | refinedweb | 312 | 57.16 |
Christmas Tracking - How to track Rubric's cube Object in python
Mohamed Khaled Yousef
Updated on
・5 min read
A month ago I am thinking about what to write in December and I decided that the best thing to close this year is the last thing I learned. So this is Computer Vision.
Object tracking is one of the most important components in numerous applications of computer vision and machine learning.
Object Tracking is like you are spying or following an object or person or car to know the the location of the object and how this object is moving, its speed, where is it going and etc.
But before we start to talk about the theory and the implementation. I want to tell that after you read this blog, We are going to make like this video.
First, there is steps or stages to track an object:
Background: is the image or the frame that have all the background without the object that we want to track.
for example if we want to track the car or wastebasket in street, We have to take a picture for the street without car or Wastebasket.
Current frame: is the image or the frame that have the background and our object
Mathematical subtraction: sub(Background, Frame)
For example if we have 2 images like the prev and we do mathematical subtraction on both, The result will be the object.
Notice we subtracted pixels:
- If the two pixels are same, the result is 0 which give us black pixel
- If the two pixels aren't same, we can't say the result is 1 which is white and it can be another value. But it is not necessary to be white.
Filter: The mathematical subtraction from previous step applies here threshold filter to get the difference between the two images.
For example we make a condition to make all pixels that less than 100 equals zero and all pixels greater than or equal to 100 equals to 255. Here's we can see our object
Masking &&: Between the result of our mathematical subtraction and the current frame which have the object.
Do you remember:
- 0 && any value => 0
- 255 && any value!=0 => any value!=0
Here's we get only the object from the frame with its color.
Blob detection: A Blob is a group of connected pixels in the frame that share some common property .like the dark connected regions that around the object. The goal of blob detection is to identify and mark these regions.
Blob detection is scanning the image from filtering stage until there is change in color (Called edge) which is the white around the object. Then draw around the object to compute containing box or containing rectangle (X1, X2, Y1, Y2) which means the height and width. Then we can get the center of container box
This is the concept around object detection and now lets detect the green color of our rubric's cube and track its moves in the frame
First we import our necessary packages. We’ll be using deque , a list-like data structure that allows us to draw the tail or contrail of the rubric.
import cv2 import imutils import numpy as np from collections import deque from imutils.video import VideoStream import argparse import time
To access webcam, we use --buffer which is the maximum size of our deque to maintain a list of the previous (x, y)-coordinates of the object that we are tracking. So the default is the value of our buffer.
This deque allows us to assembly points and track it so the deque draw the tail or contrail of the rubric.
ap = argparse.ArgumentParser() ap.add_argument("-b", "--buffer", type=int, default=50) args = vars(ap.parse_args())
We have to define the lower and upper boundaries of the color green in the HSV color to detect the green boundaries in our frame.
greenLower = (29, 86, 6) greenUpper = (64, 255, 255)
Then initialize the list of tracked points using the supplied maximum buffer size which defaults to 50
pts = deque(maxlen=args["buffer"])
To warm up and access the camera stream
vs = VideoStream(src=0).start() time.sleep(2.0)
Then we resize the frame to have a width of 700px. Then blur the frame to reduce high frequency noise and allow us to focus on the rubric inside the frame such. Finally, we convert the frame to the HSV color space.
frame = imutils.resize(frame, width=700) blurred = cv2.GaussianBlur(frame, (11, 11), 0) hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
Then we construct a mask for the color "green", then perform a series of dilations and erosions to remove any small blobs left in the mask so we can get and detect the actual localization of the green rubric in the frame
mask = cv2.inRange(hsv, greenLower, greenUpper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.dilate(mask, None, iterations=2)
Then we can find the center of the rubric by computing the contours of the object(s) in the mask.
Also we initialize the center of the rubric (x, y) coordinates to be None
cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) center = None
Then we have to make a check to ensure at least one contour was found in the mask. So we find the largest contour in the cnts list, Compute the minimum enclosing circle of the blob and then compute the center (x, y) coordinates (the centroids)"]))
Then we make a another check to ensure that the radius of the minimum enclosing circle is sufficiently large. So we then draw Contours surrounding the rubric. Then update our new points.
if radius > 10: cv2.drawContours(frame, [c], -1, (0, 255, 0), 2) pts.appendleft(center)
Finally, We have to to draw the tail or contrail of the rubric.
We start looping over the set of tracked points. If either the current point or the previous point is None that means the rubric was not successfully detected in that given frame, then we ignore the current index and continue looping over the set of tracked points.
for i in range(1, len(pts)): if pts[i - 1] is None or pts[i] is None: continue
Else if both points are valid, that means the rubric was successfully detected in that given frame so we compute the thickness of the contrail and then draw it on the frame.
thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 4.5) cv2.line(frame, pts[i - 1], pts[i], (0, 255, 250), thickness)
Finally, display and show the frame to our screen, detecting any key presses and break if you entered q
cv2.imshow("Rubik's cube tracking", frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break
Last thing to code is to release the camera
vs.release() cv2.destroyAllWindows()
Last thing to say, Happy new year and thank you for reading and I hope it would help and don’t hesitate to send your feedback and suggestions :)) | https://dev.to/mkhy19/christmas-tracking---how-to-track-rubrics-cube-object-in-python-4me4 | CC-MAIN-2019-35 | refinedweb | 1,178 | 68.91 |
One important part of writing programs is deciding what to do when things inevitably go wrong. One common way things go wrong is simple nonexistence: the value we want to have doesn’t exist. Let’s talk about three ways to handle this problem: null, exceptions, and optionals.
We’ll start with the billion-dollar mistake.
NULL,
null,
nil, or
None. It is admittedly convenient to have a way to “opt out” of having a real value with the correct type (or in more dynamic languages, the correct duck type). In C, there isn’t really a better representation for “we don’t have this thing” than a null pointer, unless you want to do a lot of extra work and explicitly represent the possibility of not having the thing as part of the thing.
Thing is…this leads to a “small” host of problems. If you’ve ever been bewildered by a
NullPointerException in Java, or had trouble with
NilClass in Ruby, you should feel this viscerally. Luckily, there are better ways to deal with stuff going missing than just hoping or (this is almost worse) explicitly checking at the beginning of every single function call for things that should not be null, but are.
The problems with unexpected null-related errors are pretty self-explanatory. It’s frustrating to have to handle values that were never really there. The other choice, though, isn’t much better. The convenience of creating a null is almost always outweighed by the inconvenience of having to check for it elsewhere. We usually want our programs saturated with values, not with nulls.
As a simple example, let’s say we have a function
f which takes some value
x. If that value can be null, then
f has to handle two paths:
x == someValue and
x == null. What happens when we add another argument
y? Now our logic is something like this:
if x is not None and y is not None: # happy path elif x is not None: # we have x, but not y elif y is not None: # we have y, but not x else: # we have neither
There’s a combinatorial explosion of possibilities here, only somewhat mitigated by the fact that we can sometimes treat “any value is null” in one way, and “all values are not null” in another. Also consider what happens if we add functions
g and
h to the mix, which both take those same arguments
x and
y. Adding explicit checks in all these places gets annoying fast, and adds unnecessary cognitive overhead.
We don’t need to clutter our code with null checks or ignore the problem altogether. Exceptions provide a convenient way out.
Let’s take a classic example: reading a config file which may or may not exist. We strongly expect the file to exist, but if it doesn’t there isn’t much we can do within our usual program flow. Sometimes it doesn’t make sense to prompt users for a file, if they’re not even aware that such an internal file exists.
This situation is, by all rights, exceptional, and so it merits being handled with exceptions. You can break out of the part of the program that needs the file, and do whatever handling needs to be done to avoid a Really Bad Situation (whether that’s a total program crash, writing some invalid state, etc.)
Exceptions are better than null insofar as being explicit is better than being implicit. We don’t just rely on a total program failure in unexpected conditions, but instead have at least some way to handle weird situations. Some language constructs (e.g.
throws in Java) give programmers at least a small heads-up that they need to be on the lookout for handling these cases.
There are certain aesthetic problems with using exceptions extensively. The adage “exceptions are for exceptional cases” is fairly wise, in my opinion. Its wisdom comes from a recognition of what exceptions are: a way to skirt around the natural control flow of your program when invalid conditions arise. Just as you shouldn’t be using exceptions for standard control flow, you shouldn’t be using them for standard value-gone-missing situations.
There is a better way when we know up front that we should sometimes expect to have a value, and sometimes expect not to. These kinds of values are “optional”. Optionals are a better representation of situations which aren’t actually exceptional, but where you still don’t just want to toss around a few nulls and call it a day.
Certain languages don’t even have
null at all. One example is Haskell. Yes, there are ways in Haskell to produce bad “bottom” values (e.g. infinite loops like
let x = x in x). But it doesn’t have a pervasive null value that infects everything and becomes an easy way out.
What can these languages do instead? Haskell provides a fantastic optional type called
Maybe. Here’s a definition for it:
data Maybe a = Just a | Nothing
What these means is that we have an optional polymorphic over any type
a, where our values are either wrapped in a
Just or have a special representation
Nothing that indicates the value is missing. For example, we can have optional integers that look like
Just 7 :: Maybe Int or they look like
Nothing :: Maybe Int. Note that
Nothing does not play the same role as
null does in most other languages, because a
Nothing :: Maybe Int is not the same as a
Nothing :: Maybe String, whereas in C, for example,
nullptr is always implicitly the same and can inhabit any pointer type, regardless of the type of thing being pointed to.
There is some pain associated with optionals that people are quick to bring up. Isn’t it a big hassle to have to wrap and unwrap your types in
Maybe all the time? The ease of use of
null sure seems appealing. And surely our program handles all the potential exceptions we missed appropriately…right?
There really is a better way. Often it’s accomplished by smart chaining of operations that might fail. In Haskell, Maybe is a monad, which among other things means we can hide away a lot of complexity behind a nice style called “do notation”. I’ve used this example before:
testMaybe :: Int -> Int -> [Int] -> Maybe Int testMaybe a b c = do found <- lookup a [1..b] divided <- maybeDiv found 2 head <- maybeHead c return (divided + head)
There isn’t any explicit optional handling here! Everything is handled behind the scenes, and if some part of our computation fails, we get back a Nothing, with no extra overhead when thinking about the happy path of this code. This is way better than having to manage which pieces of some computation might be null or throw an exception any old time.
Some other languages, like Swift, still have
nil but manage to solve a lot of the pain associated with optionals by using special operators. Swift lets you chain things together with
?: for example,
a?.my_func(b). You can also dangerously unpack things as an escape hatch (
a!.my_func(b)) but of course I don’t really recommend that unless you’re really certain
a exists and isn’t
nil.
Even in the world of nulls, we can do better by smarter chaining rather than throwing exceptions every time we touch something that’s unexpectedly null. Take the safe navigation operator (
&.) in Ruby. Let’s say we have some nested object where any part might be
nil, but we’re not sure if any part is. It’s a huge pain to write nil checks for every part of a complicated access, but using
&. is relatively painless. We can transform
a.b.c.d (which might blow up with something like
undefined method for NilClass) with an access like
a&.b&.c&.d, which instead has the same correct behavior on the happy path, but simply gives back
nil if any part of the access chain was
nil.
It’s hopefully pretty clear that I’ve organized this post in order of increasing preference. Optionals are a great way to handle values which may or may not be there. Exceptions are fine, if used sparingly for truly exceptional conditions which would otherwise leave your program in an invalid state. Null tends to lead to more trouble than it’s worth.
Unfortunately, the usual ease-of-use tends to point the other direction. Null is incredibly easy to use: you can throw it anywhere, in place of any value. Exceptions are a little trickier, since they have to be handled. Optionals are a bit painful if you have to do all the unpacking and repacking yourself.
Happily, certain languages have constructs that make optionals less painful to use (or even make nulls nonexistent). I’m looking forward to seeing how language designers can solve even more of these problems in the future, leading to a world where we can handle value nonexistence with as much of the desired explicitness and ease as we currently use to handle values that actually exist. | https://vitez.me/nullity-exceptionality-optionality | CC-MAIN-2019-26 | refinedweb | 1,532 | 61.97 |
When making the transition from a beginner to an intermediate or advanced Python programmer, it also gets important to understand the intricacies of variables used within functions and of passing parameters to functions in detail. First of all, we can distinguish between global and local variables within a Python script. Global variables are defined outside of any function. They can be accessed from anywhere in the script and they exist and keep their values as long as the script is loaded which typically means as long as the Python interpreter into which they are loaded is running.
In contrast, local variables are defined inside a function and can only be accessed in the body of that function. Furthermore, when the body of the function has been executed, its local variables will be discarded and cannot be used anymore to access their current values. A local variable is either a parameter of that function, in which case it is assigned a value immediately when the function is called, or it is introduced in the function body by making an assignment to the name for the first time.
Here are a few examples to illustrate the concepts of global and local variables and how to use them in Python.
def doSomething(x): # parameter x is a local variable of the function count = 1000 * x # local variable count is introduced return count y = 10 # global variable y is introduced print(doSomething(y)) print(count) # this will result in an error print(x) # this will also result in an error
This example introduces one global variable, y, and two local variables, x and count, both part of the function doSomething(…). x is a parameter of the function, while count is introduced in the body of the function in line 3. When this function is called in line 11, the local variable x is created and assigned the value that is currently stored in global variable y, so the integer number 10. Then the body of the function is executed. In line 3, an assignment is made to variable count. Since this variable hasn’t been introduced in the function body before, a new local variable will now be created and assigned the value 10000. After executing the return statement in line 5, both x and count will be discarded. Hence, the two print statements at the end of the code would lead to errors because they try to access variables that do not exist anymore.
Now let’s change the example to the following:
def doSomething(): count = 1000 * y # global variable y is accessed here return count y = 10 print(doSomething())
This example shows that global variable y can also be directly accessed from within the function doSomething(): When Python encounters a variable name that is neither the name of a parameter of that function nor has been introduced via an assignment previously in the body of that function, it will look for that variable among the global variables. However, the first version using a parameter instead is usually preferable because then the code in the function doesn’t depend on how you name and use variables outside of it. That makes it much easier to, for instance, re-use the same function in different projects.
So maybe you are wondering whether it is also possible to change the value of a global variable from within a function, not just read its value? One attempt to achieve this could be the following:
def doSomething(): count = 1000 y = 5 return count * y y = 10 print(doSomething()) print(y) # output will still be 10 here
However, if you run the code, you will see that last line still produces the output 10, so the global variable y hasn't been changed by the assignment in line 5. That is because the rule is that if a name is encountered on the left side of an assignment in a function, it will be considered a local variable. Since this is the first time an assignment to y is made in the body of the function, a new local variable with that name is created at that point that will overshadow the global variable with the same name until the end of the function has been reached. Instead, you explicitly have to tell Python that a variable name should be interpreted as the name of a global variable by using the keyword ‘global’, like this:
def doSomething(): count = 1000 global y # tells Python to treat y as the name of global variable y = 5 # as a result, global variable y is assigned a new value here return count * y y = 10 print(doSomething()) print(y) # output will now be 5 here
In line 5, we are telling Python that y in this function should refer to the global variable y. As a result, the assignment in line 7 changes the value of the global variable called y and the output of the last line will be 5. While it's good to know how these things work in Python, we again want to emphasize that accessing global variables from within functions should be avoided as much as possible. Passing values via parameters and returning values is usually preferable because it keeps different parts of the code as independent of each other as possible.
So after talking about global vs. local variables, what is the issue with mutable vs. immutable mentioned in the heading? There is an important difference in passing values to a function depending on whether the value is from a mutable or immutable data type. All values of primitive data types like numbers and boolean values in Python are immutable, meaning you cannot change any part of them. On the other hand, we have mutable data types like lists and dictionaries for which it is possible to change their parts: You can, for instance, change one of the elements in a list or what is stored under a particular key in a given dictionary without creating a completely new object.
What about strings and tuples? You may think these are mutable objects, but they are actually immutable. While you can access a single character from a string or element from a tuple, you will get an error message if you try to change it by using it on the left side of the equal sign in an assignment. Moreover, when you use a string method like replace(…) to replace all occurrences of a character by another one, the method cannot change the string object in memory for which it was called but has to construct a new string object and return that to the caller.
Why is that important to know in the context of writing functions? Because mutable and immutable data types are treated differently when provided as a parameter to functions as shown in the following two examples:
def changeIt(x): x = 5 # this does not change the value assigned to y y = 3 changeIt(y) print(y) # will print out 3
As we already discussed above, the parameter x is treated as a local variable in the function body. We can think of it as being assigned a copy of the value that variable y contains when the function is called. As a result, the value of the global variable y doesn’t change and the output produced by the last line is 3. But it only works like this for immutable objects, like numbers in this case! Let’s do the same thing for a list:
def changeIt(x): x[0] = 5 # this will change the list y refers to y = [3,5,7] changeIt(y) print(y) # output will be [5, 5, 7]
The output [5,5,7] produced by the print statement in the last line shows that the assignment in line 3 changed the list object that is stored in global variable y. How is that possible? Well, for values of mutable data types like lists, assigning the value to function parameter x cannot be conceived as creating a copy of that value and, as a result, having the value appear twice in memory. Instead, x is set up to refer to the same list object in memory as y. Therefore, any change made with the help of either variable x or y will change the same list object in memory. When variable x is discarded when the function body has been executed, variable y will still refer to that modified list object. Maybe you have already heard the terms “call-by-value” and “call-by-reference” in the context of assigning values to function parameters in other programming languages. What happens for immutable data types in Python works like “call-by-value,” while what happens to mutable data types works like “call-by-reference.” If you feel like learning more about the details of these concepts, check out this article on Parameter Passing.
While the reasons behind these different mechanisms are very technical and related to efficiency, this means it is actually possible to write functions that take parameters of mutable type as input and modify their content. This is common practice (in particular for class objects which are also mutable) and not generally considered bad style because it is based on function parameters and the code in the function body does not have to know anything about what happens outside of the function. Nevertheless, often returning a new object as the return value of the function rather than changing a mutable parameter is preferable. This brings us to the last part of this section. | https://www.e-education.psu.edu/geog489/node/2280 | CC-MAIN-2022-33 | refinedweb | 1,597 | 51.11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.