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 |
|---|---|---|---|---|---|
Symptoms:
New users, or users who recently changed their password are unable to log in at all, or able to log in on one or more machines but not on others. The user may see error messages with operative clauses such as:
First Possible Cause:
Password was changed on NIS machine.
If a user or system administrator uses the passwd command to change a password on a Solaris operating environment machine running NIS in a domain served by NIS+ namespace servers, the user's password is changed only in that machine's /etc/passwd file. If the user then goes to some other machine on the network, the user's new password will not be recognized by that machine. The user will have to use the old password stored in the NIS+ passwd table.
Diagnosis:
Check to see if the user's old password is still valid on another NIS+ machine.
Solution:
Use passwd on a machine running NIS+ to change the user's password.
Second Possible Cause:
Password changes take time to propagate through the domain.
Diagnosis:
Namespace changes take a measurable amount of time to propagate through a domain and an entire system. This time might be as short as a few seconds or as long as many minutes, depending on the size of your domain and the number of replica servers.
Solution:
You can simply wait the normal amount of time for a change to propagate through your domain(s). Or you can use the nisping org_dir command to resynchronize your system. | http://docs.oracle.com/cd/E19455-01/806-1387/abtrbl-11/index.html | CC-MAIN-2016-44 | refinedweb | 255 | 67.38 |
Checking in JSONTue 08 January 2019 by Moshe Zadka
JSON is a useful format. It might not be ideal for hand-editing, but it does have the benefit that it can be hand-edited, and it is easy enough to manipulate programmatically.
For this reason, it is likely that at some point or another, checking in a JSON file into your repository will seem like a good idea. Perhaps it is even beyond your control: some existing technology uses JSON as a configuration file, and the easiest thing is to go with it.
It is useful to still keep the benefit of programmatic manipulation.
For example,
if the JSON file encodes a list of numbers,
and we want to add
1 to every even number,
we can do:
with open("myfile.json") as fp: content = json.load(fp) content = [x + (2 % i) for i, x in enumerate(content)] with open("myfile.json", "w") as fp: json.dumps(fp, content)
However, this does cause a problem: presumably, before, the list was formatted in a visually-pleasing way. Having dumped it, now the diff is unreadable -- and hard to audit visually.
One solution is to enforce consistent formatting.
For example,
using
pytest,
we can write the following test:
def test_formatting(): with open("myfile.json") as fp: raw = fp.read() content = json.loads(raw) redumped = json.dumps(content, indent=4) + "\n" assert raw == redumped
Assuming we gate merges to the main branches on passing tests,
it is impossible to check in something that breaks the formatting.
Automated programs merely need to remember to give the right options
to
json.dumps.
However,
what happens when humans make mistakes?
It turns out that Python already has a command-line tool to reformat:
$ python -m json.tool myfile.json > myfile.json.formatted $ mv myfile.json.formatted myfile.json
A nice test failure will remind the programmer of this trick, so that it is easy to do and check in. | https://orbifold.xyz/check-in-json.html | CC-MAIN-2019-22 | refinedweb | 323 | 57.87 |
On Fri, 2005-10-21 at 04:00 -0400, Steven Rostedt wrote:> Thomas,> > I noticed you changed the names around for ktimer_start/restart. Is it OK> to just use the restart, if you don't know if it has already started,> every time, and never call the start. It seems to be OK now, but will> that ever change?No. Note also that there are no functional changes in the code. Its onlya cleanup vs. coding style and namespaces.> Basically, is just the ktimer_init good enough for ktimer_restart?Yes tglx-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 | https://lkml.org/lkml/2005/10/21/31 | CC-MAIN-2014-15 | refinedweb | 118 | 84.88 |
You use Cron Jobs to schedule various IT tasks. In addition, Cron Jobs allows you to automate specific commands or scripts on your server to complete repetitive tasks automatically.
This article will show you how to create a simple scheduled task using AWS Lambda and Amazon EventBridge to post messages to a Slack channel.
The AWS Services
There are two AWS services involved in building the scheduled task on AWS which are:
Amazon EventBridge Rule: Amazon EventBridge delivers a near real-time stream of system events that describe Amazon Web Services (AWS) resources changes. You can also use EventBridge Events to schedule automated actions that self-trigger at specific times using cron or rate expressions.
AWS Lambda Function: AWS Lambda. You can run code for virtually any application or back-end service with Lambda. All you need to do is supply your code in one of the languages that Lambda supports.
Situation
Slack Workflow Builder is a visual tool that allows Slack users to automate routine functions by creating custom workflows. For example, the Scheduled date and time workflow trigger start automatically at a set date and time. But the problem with this trigger is that we cannot trigger the workflow every hour or minute. Instead, we must create duplicates of a scheduled workflow for different time schedules, which may not be a good solution. However, you can set up an Amazon EventBridge rule to run an AWS Lambda function on a schedule to overcome this limitation.
Prerequisites
- AWS Lambda Layer for Python requests package
- Bot App registered with Slack Workspace with the necessary access token and permission scope to post message and read user details
- Bot App installed on the target Slack channel
Step 1: Create an AWS Lambda function
- Open the AWS Lambda console.
- Choose Create Function.
- Choose Author from scratch.
- Enter a Function name. For example, name the function slack-bot.
- Select Python 3.9 as Runtime
- Leave the rest of the options as the defaults and choose Create Function.
- On the Code tab of the function page, double click on lambda_function.py. Replace the existing code with the following code.
import requests import json from logging import exception SLACK_INSTANCE_NAME = "your-slack-instance-name" SLACK_TOKEN = "your-slack-token" SLACK_BOT_USERNAME = "your-bot-username" SLACK_CHANNEL_ID = "your-slack-channel-id" SLACK_MESSAGE = "Hello, This is a test message from the AWS Lambda function. " def post_message_in_slack(channel_id, message, posted_by): try: headers = { 'Authorization': 'Bearer ' + SLACK_TOKEN, 'Content-Type': 'application/json', 'accept': 'application/json' } payload = json.dumps({ "channel": channel_id, "text": message, "username": posted_by }) url = f' response = requests.post(url, headers=headers, data=payload) message = response.json().get('message', None) return message except requests.exceptions.RequestException as err: raise exception(err) def lambda_handler(event, context): try: message = post_message_in_slack( SLACK_CHANNEL_ID, SLACK_MESSAGE, SLACK_BOT_USERNAME) messageId = message.get('ts', None) return { 'statusCode': 200, 'body': json.dumps('Message posted! Message ID: ' + messageId) } except Exception as err: return { 'statusCode': 400, 'body': json.dumps(str(err)) }
NOTE: Update the environment-specific values in the sample code.
- Under Layers, choose Add a layer.
- For the Specify an ARN layer source:
- Enter the requests layer ARN in the text box and choose Verify.
- Choose Add.
- Choose Deploy.
Step 2: Create Amazon EventBridge Rule
- Open the Amazon EventBridge console.
- In the navigation pane, choose Rules. Choose Create rule.
- Enter a name and description for the rule.
- For Select event bus, choose AWS default event bus. Scheduled rules are supported only on the default event bus.
- For Define pattern, do the following:
- Choose Schedule.
- Choose A schedule that runs at a regular rate, such as every 10 minutes. and specify the schedule interval, for example, 5 minutes.
- For Target, choose Lambda function.
- For Function, select the Lambda function that you created in step 1.
- Choose Create.
This rule will be triggered every 5 minutes, and it will also trigger our Lambda function accordingly.
If you see the Lambda event in the CloudWatch logs, you can see the message posted in the Slack channel.
Thank you for reading this article. I hope it helped you in some way. | https://blog.josephvelliah.com/schedule-aws-lambda-function-using-amazon-eventbridge-rule | CC-MAIN-2022-21 | refinedweb | 670 | 58.18 |
Extended: Due by 7pm on Monday, 1/28.
Submission. See the online submission instructions.
Course Survey. Please complete our online course survey. The survey is for the instructors to get to know their students better, and your responses will be kept confidential to the staff. The survey is also due by 7pm on Friday, 1/25, and the confirmation message will give you the answer to Q3.
Q1. Read the Course Info page on the course website. Somewhere on that page, you will find out when Amir took CS 61A. Fill in the blank with the year:
def stone_age(): """Returns the year in which Amir took CS 61a.""" return _____
Q2. Login to Piazza and add CS 61A if it's not in your list of classes. Read the message titled "The answer to hw0 q2" and fill in the blank with Amir's favorite baseball player:
def favorite_player(): """Returns Amir's favorite baseball player.""" return '_____'
Q3. Complete the course survey linked above and note the confirmation message. Then fill in the blank with Amir's favorite number:
def favorite_number(): """Returns Amir's favorite number.""" return _____ | https://inst.eecs.berkeley.edu/~cs61a/sp13/hw/hw0.html | CC-MAIN-2018-05 | refinedweb | 188 | 75.3 |
#include <sasl/sasl.h>
int sasl_checkpass(sasl_conn_t *conn,
const char *user,
unsigned userlen,
const char *pass,
unsigned passlen);
sasl_checkpass() will check a plaintext password. This is needed for
protocols that had a login method before SASL (for example the LOGIN
command in IMAP). The password is checked with the pwcheck_method See
sasl_callbacks(3) for information on how this parameter is set.
sasl_checkpass returns an integer which corresponds to one of the fol-
lowing codes. SASL_OK indicates that the authentication is complete.
All other return codes indicate errors and should either be handled or
the authentication session should be quit. See sasl_errors(3) for
meanings of return codes.
RFC 2222
sasl(3), sasl_errors(3), sasl_callbacks(3), sasl_setpass(3)
SASL man pages SASL sasl_checkpass(10 July 2001) | http://www.syzdek.net/~syzdek/docs/man/.shtml/man3/sasl_checkpass.3.html | crawl-003 | refinedweb | 125 | 56.86 |
I have two classes which share some properties and behavior. One such cluster of common behavior is manipulation in 3D space. As such, each implements interface
Transformable:
public interface Transformable { public void position (double x, double y, double z); public void position (Tuple3d tuple); public void rotateDeg (double yaw, double pitch, double roll); public void rotateRad (double yaw, double pitch, double roll); // And so on... } public class Foo extends Apple implements Transformable { // Foo happens } public class Bar extends Orange implements Transformable { // Bar happens }
Now, the behavior for every method in
Transformable is identical for any implementing class, and the code required is substantial.
Foo and
Bar each extend different super classes which I have no control of, and Java doesn't have multiple inheritance, so that option is out.
Copy-pasting a slew of code into every class that implements
Transformable is antithetical to all things programming.
The best solution I've been able to conjure up is to create a class with all implementation details, and use pass-through methods:
public Foo extends Apple implements Transformable { // This class has all of the repeated implementation code private TransformationHelper helper; public final void rotate (double yaw, double pitch, double roll) { helper.rotate(yaw, pitch, roll); } }
However, this is only marginally better than repeating the code in every class. While the actual implementation code is in one spot, this is still pretty clumsy.
Does anybody have a better approach for this problem?
Edit: To clarify, I do have control over
Transformable. The entire idea is:
Foo and
Bar are completely different. It could just as easily be
Shoe and
SpaceShuttle, but both exist at distinct positions in 3D space, and need a
.position(x,y,z) method which will do the exact same thing. | http://www.howtobuildsoftware.com/index.php/how-do/fcA/java-oop-interface-how-to-implement-repeated-behavior-when-inheritance-isnt-an-option | CC-MAIN-2019-09 | refinedweb | 292 | 50.97 |
Draft Polygon/ru
Description
The Polygon tool creates a regular polygon inscribed in a circumference by picking two points, the center and the radius. It uses the Draft Linestyle set on the Draft Tray.
Regular polygon defined by the center point and the radius
Usage
- Press the
Draft Polygon button, or press P then G keys.
- Adjust the desired number of sides in the options dialog.
- Click a first point on the 3D view, or type a coordinate and press the
add point button.
- Click another point on the 3D view, or type a radius value to define the polygon radius.
The polygon can be edited by double clicking on the element in the tree view, or by pressing the
Draft Edit button. Then you can move the center and radius points to a new position.
The polygon is created inscribed in a circle of the specified radius; it can be switched to circumscribed after creation by changing its draw mode property.
The number of sides of the polygon can also be changed after creation by changing its faces number property.
Options
- Polygon tool will restart after you finish it, allowing you to draw another one without pressing the tool button again.
- Press L or click the checkbox to toggle filled mode. If filled mode is on, the polygon will create a filled face (DataMake Face True); if not, the polygon
Data
- DataRadius: specifies the radius of the circle that defines the polygon.
- DataDraw Mode: specifies if the polygon is inscribed in a circle, or circumscribed around a circle.
- DataFaces Number: specifies the number of sides of the polygon.
- DataChamfer Size: specifies the size of the chamfers (straight segments) created on the corners of the polygon.
- DataFillet Radius: specifies the radius of the fillets (arc segments) created on the corners of the polygon.
- DataMake Face: specifies if the shape makes a face or not. If it is True a face is created, otherwise only the perimeter is considered part of the object.
View
- ViewPattern: specifies a Draft Pattern with which to fill the face of the polygon. This property only works if DataMake Face is True, and if ViewDisplay Mode is "Flat Lines".
- ViewPattern Size: specifies the size of the Draft Pattern.
Scripting
See also: Draft API and FreeCAD Scripting Basics.
The Polygon tool can be used in macros and from the Python console by using the following function:
Polygon = makePolygon(nfaces, radius=1, inscribed=True, placement=None, face=None, support=None)
- Creates a
Polygonobject with the given number of faces (
nfaces), and based on a circle of
radiusin millimeters.
- If
inscribedis
True, the polygon is inscribed in the circle, otherwise it will be circumscribed.
- One of the vertices of the polygon will lie on the X axis if no other placement is given.
- If a
placementis given, it is used; otherwise the shape is created at the origin.
- If
faceis
True, the shape will make a face, that is, it will appear filled.
Example:
import FreeCAD, Draft Polygon1 = Draft.makePolygon(4, radius=500) Polygon2 = Draft.makePolygon(5, radius=750) ZAxis = FreeCAD.Vector(0, 0, 1) p3 = FreeCAD.Vector(1000, 1000, 0) place3 = FreeCAD.Placement(p3, FreeCAD.Rotation(ZAxis, 90)) Polygon3 = Draft.makePolygon(6, radius=1450, | https://wiki.freecadweb.org/index.php?title=Draft_Polygon/ru&oldid=623563 | CC-MAIN-2020-16 | refinedweb | 536 | 64.61 |
Neuen Kommentar schreiben
Drupal 8: Hello OOP, Hello world!
by Alex Bronstein
"Cross Posted from".
In this post, I'd like to dive a little deeper into the first thing you'll probably notice if you watch that video and write the module: that you're now writing namespaced PHP classes instead of global functions, even for very simple stuff. If you first learned PHP within the last couple years, or have worked with any modern object-oriented PHP project, this might all be second nature to you. However, if you're like me, and only learned PHP in order to develop for Drupal 7 or earlier, it might take a bit to learn and adjust to the best practices of OOP in PHP.. | http://www.acquia.com/de/comment/reply/3141056 | CC-MAIN-2015-14 | refinedweb | 124 | 64.24 |
How do I split a custom dataset into training and test datasets?
pytorch random split
torch.utils.data.random_split example
pytorch random_split
subsetrandomsampler
pytorch random split example
torch.utils.data.random_split(dataset lengths) example
pytorch random_split example
import pandas as pd import numpy as np import cv2 from torch.utils.data.dataset import Dataset): pixels = self.data['pixels'].tolist() faces = [] for pixel_sequence in pixels: face = [int(pixel) for pixel in pixel_sequence.split(' ')] # print(np.asarray(face).shape) face = np.asarray(face).reshape(self.width, self.height) face = cv2.resize(face.astype('uint8'), (self.width, self.height)) faces.append(face.astype('float32')) faces = np.asarray(faces) faces = np.expand_dims(faces, -1) return faces, self.labels def __len__(self): return len(self.data)
This is what I could manage to do by using references from other repositories. However, I want to split this dataset into train and test.
How can I do that inside this class? Or do I need to make a separate class to do that?
Using Pytorch's
SubsetRandomSampler:
import torch import numpy as np from torchvision import datasets from torchvision import transforms from torch.utils.data.sampler import SubsetRandomSampler): # This method should return only 1 sample and label # (according to "index"), not the whole dataset # So probably something like this for you: pixel_sequence = self.data['pixels'][index] face = [int(pixel) for pixel in pixel_sequence.split(' ')] face = np.asarray(face).reshape(self.width, self.height) face = cv2.resize(face.astype('uint8'), (self.width, self.height)) label = self.labels[index] return face, label def __len__(self): return len(self.labels) dataset = CustomDatasetFromCSV(my_path) batch_size = 16 validation_split = .2 shuffle_dataset = True random_seed= 42 # Creating data indices for training and validation splits: dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset : np.random.seed(random_seed) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] # Creating PT data samplers and loaders: train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) train_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=train_sampler) validation_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, sampler=valid_sampler) # Usage Example: num_epochs = 10 for epoch in range(num_epochs): # Train: for batch_index, (faces, labels) in enumerate(train_loader): # ...
How to split dataset into test and validation sets, I have a dataset in which the different images are classified into different folders. I want to split the data to test, train, valid sets. Please help..
Starting in PyTorch 0.4.1 you can use
random_split:
train_size = int(0.8 * len(full_dataset)) test_size = len(full_dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(full_dataset, [train_size, test_size])
Building Efficient Custom Datasets in PyTorch, Managing data for neural network training can be hard at “scale”. In this article, I will be exploring the PyTorch Dataset object from the ground up Let's have a look at what it would look like if we sliced the dataset into a batch: Create validation sets by splitting your custom PyTorch datasets easily with shuffle the whole matrix arr and then split the data to train and test. shuffle the indices and then assign it x and y to split the data. same as method 2, but in a more efficient way to do it. using pandas dataframe to split.
Current answers do random splits which has disadvantage that number of samples per class is not guaranteed to be balanced. This is especially problematic when you want to have small number of samples per class. For example, MNIST has 60,000 examples, i.e. 6000 per digit. Assume that you want only 30 examples per digit in your training set. In this case, random split may produce imbalance between classes (one digit with more training data then others). So you want to make sure each digit precisely has only 30 labels. This is called stratified sampling..
def sampleFromClass(ds, k): class_counts = {} train_data = [] train_label = [] test_data = [] test_label = [] for data, label in ds: c = label.item() class_counts[c] = class_counts.get(c, 0) + 1 if class_counts[c] <= k: train_data.append(data) train_label.append(torch.unsqueeze(label, 0)) else: test_data.append(data) test_label.append(torch.unsqueeze(label, 0)) train_data = torch.cat(train_data) for ll in train_label: print(ll) train_label = torch.cat(train_label) test_data = torch.cat(test_data) test_label = torch.cat(test_label) return (TensorDataset(train_data, train_label), TensorDataset(test_data, test_label))
You can use this function like this:
def main(): train_ds = datasets.MNIST('../data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor() ])) train_ds, test_ds = sampleFromClass(train_ds, 3)
Train, Validation and Test Split for torchvision Datasets · GitHub, Train, Validation and Test Split for torchvision Datasets - data_loader.py. num_workers: number of subprocesses to use when loading the dataset. - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to. True if using Test dataset now has first 1000 elements and the rest goes for training. You may use Dataset.take() and Dataset.skip(): For more generality, I gave an example using a 70/15/15 train/val/test split but if you don't need a test or a val set, just ignore the last 2 lines.
This is the PyTorch
Subset class attached holding the
random_split method. Note that this method is base for the
SubsetRandomSampler.
For MNIST if we use
random_split:
loader = DataLoader( torchvision.datasets.MNIST('/data/mnist', train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.5,), (0.5,)) ])), batch_size=16, shuffle=False) print(loader.dataset.data.shape) test_ds, valid_ds = torch.utils.data.random_split(loader.dataset, (50000, 10000)) print(test_ds, valid_ds) print(test_ds.indices, valid_ds.indices) print(test_ds.indices.shape, valid_ds.indices.shape)
We get:
torch.Size([60000, 28, 28]) <torch.utils.data.dataset.Subset object at 0x0000020FD1880B00> <torch.utils.data.dataset.Subset object at 0x0000020FD1880C50> tensor([ 1520, 4155, 45472, ..., 37969, 45782, 34080]) tensor([ 9133, 51600, 22067, ..., 3950, 37306, 31400]) torch.Size([50000]) torch.Size([10000])
Our
test_ds.indices and
valid_ds.indices will be random from range
(0, 600000). But if I would like to get sequence of indices from
(0, 49999) and from
(50000, 59999) I cannot do that at the moment unfortunately, except this way.
Handy in case you run the MNIST benchmark where it is predefined what should be the test and what should be the validation dataset.
Validation split with Dataloader/Dataset · Issue #1106 · pytorch , You can use a SubsetRandomSampler to achieve it, or a custom sampler which lets you create train, validation and test splits on torchvision datasets I check the example/mnist,it present the train and test ,not include valid. Try this snippet of mine if you need to split Dataset into training and validation. Splits and slicing. All DatasetBuilder s.
Custom dataset has a special meaning in PyTorch, but I think you meant any dataset. Let's check out the MNIST dataset (this is probable the most famous dataset for the beginners).
import torch, torchvision import torchvision.datasets as datasets from torch.utils.data import DataLoader, Dataset, TensorDataset train_loader = DataLoader( torchvision.datasets.MNIST('/data/mnist', train=True, download=True, transform=torchvision.transforms.Compose([ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize( (0.5,), (0.5,)) ])), batch_size=16, shuffle=False) print(train_loader.dataset.data.shape) test_ds = train_loader.dataset.data[:50000, :, :] valid_ds = train_loader.dataset.data[50000:, :, :] print(test_ds.shape) print(valid_ds.shape) test_dst = train_loader.dataset.targets.data[:50000] valid_dst = train_loader.dataset.targets.data[50000:] print(test_dst, test_dst.shape) print(valid_dst, valid_dst.shape)
What this will outupt, is size of the original
[60000, 28, 28], then the splits
[50000, 28, 28] for test and
[10000, 28, 28] for validation:
torch.Size([60000, 28, 28]) torch.Size([50000, 28, 28]) torch.Size([10000, 28, 28]) tensor([5, 0, 4, ..., 8, 4, 8]) torch.Size([50000]) tensor([3, 8, 6, ..., 5, 6, 8]) torch.Size([10000])
Additional info if you actually plan to pair images and labels (targets) together
bs = 16 test_dl = DataLoader(TensorDataset(test_ds, test_dst), batch_size=bs, shuffle=True) for xb, yb in test_dl: # Do your work
Splits and slicing, import pandas as pd import numpy as np import cv2 from torch.utils.data.dataset import Dataset class CustomDatasetFromCSV(Dataset): def As we work with datasets, a machine learning algorithm works in two stages. We usually split the data around 20%-80% between testing and training stages. Under supervised learning, we split a dataset into a training data and test data in Python ML. Train and Test Set in Python Machine Learning. a. Prerequisites for Train and Test Data.
How to split my image datasets into training, validation and testing , All DatasetBuilder s expose various data subsets defined as splits (eg: train , test ). The full `train` split and the full `test` split as two distinct datasets. train_ds.
PyTorch Tutorial: Dataset. Data preparetion stage., For train-test splits and cross validation, I strongly suggest using the SciKitLearn from sklearn import datasets; print('[INFO] loading MNIST full dataset. One common technique for validating models is to break the data to be analyzed into training and test subsamples, then fit the model using the training data and score it by predicting on the test data. Once you have split your original data set onto your cluster nodes, you can split the data on the individual nodes by calling rxSplit again within a call to rxExec.
A detailed example of data loaders with PyTorch, Simple Dataset; Splitting data into train and validation part; Using augmentation Dataset: An abstract class representing a Dataset. All other datasets should subclass it. 'test' if mode == 'train': self.mode = 'train' self.masks = pd.read_csv('. How do i split my dataset into 70% training , 30% testing ? Dear all , I have a dataset in csv format. I am looking for a way/tool to randomly done by dividing 70% of the database for training and 30% for testing , in order to guarantee that both subsets are random samples from the same d
- What is num_train?
- My bad, it has been renamed appropriately (
dataset_size).
- Also when I put this in model, the function
forwardtakes the input data. And the shape of that data is 5D tensor -
(32L, 35887L, 48L, 48L, 1L). 32 is the batch size, next is the length of dataset and then image height, width and channel.
Dataset.__getitem__()should return a single sample and label, not the whole dataset. I edited my post to give you an example how it should look.
- @AnaClaudia:
batch_sizedefines the number of samples stacked together into a mini-batch passed to the neural network each training iteration. See Dataloader documentation or this Cross-Validated thread for more info.
- I followed your answer and got this problem while iterating throught the split
train_loaderstackoverflow.com/questions/53916594/… | https://thetopsites.net/article/50544730.shtml | CC-MAIN-2021-25 | refinedweb | 1,743 | 52.15 |
XMLSerializer corrupts namespace prefixes when XHTML namespace is used
RESOLVED FIXED
Status
()
--
major
People
(Reporter: bedney, Assigned: peterv)
Tracking
({fixed-aviary1.0, fixed1.7.5, regression})
Points:
---
Firefox Tracking Flags
(Not tracked)
Details
Attachments
(2 attachments, 1 obsolete attachment)
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040616 Build Identifier: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7) Gecko/20040616 The XMLSerializer corrupts namespace prefixes when the XHTML namespace is used. Note that the DOM itself contains the correct namespace information (i.e. you can poke around and get 'namespaceURI's and 'prefix's) but the serializer corrupts the output. Note that this did not occur in Mozilla 1.6 and earlier. This is a new bug for Mozilla 1.7. Reproducible: Always Steps to Reproduce: 1.Run testcase 2.Note the errors in the testcase (its well documented) 3. Actual Results: Got incorrect serialization results. Expected Results: Correctly serialized the input. Check the testcase. There's 4 separate testcases. The first 2 work, the last 2 don't. Note again that this is a Mozilla 1.7 issue.
Jonas: shouldn't the GetNodeInfo call in nsGenericHTMLElement::SetAttrAndNotify () use aPrefix?
Status: UNCONFIRMED → NEW
Ever confirmed: true
Assignee: hjtoi-bugzilla → peterv
Status: NEW → ASSIGNED
Comment on attachment 151528 [details] [diff] [review] v1 This seems like the right thing and it fixes the bug. I can't think of anything that this could be breaking, you?
Attachment #151528 - Flags: review?(bugmail)
Comment on attachment 151528 [details] [diff] [review] v1 I think there is some other bug filed on this issue, or at least it was talked about in some other bug. The same problem exists in XUL. r=me if you fix it there too.
Attachment #151528 - Flags: review?(bugmail) → review+
Comment on attachment 151528 [details] [diff] [review] v1 sr=jst
Attachment #151528 - Flags: superreview+
Note that we probably get the wrong attribute for the mutation events (see).
Comment on attachment 151669 [details] [diff] [review] Patch that was checked in Carrying forward r/sr and asking for branch approval: trivial fix so that attributes in XHTML and XUL elements don't lose their prefix. Low-risk.
Attachment #151669 - Flags: superreview+
Attachment #151669 - Flags: review+
Attachment #151669 - Flags: approval1.7.1?
Comment on attachment 151669 [details] [diff] [review] Patch that was checked in a=mkaply for 1.7.1
Attachment #151669 - Flags: approval1.7.1? → approval1.7.1+
Checked in to trunk and 1.7 branch.
Status: ASSIGNED → RESOLVED
Last Resolved: 15 years ago
Keywords: fixed1.7.1
Resolution: --- → FIXED
Whiteboard: needed-aviary1.0?
AVIARY_1_0_20040515_BRANCH does not checkin yet.
Fixed on the aviary branch now too.
Keywords: fixed-aviary1.0
Whiteboard: needed-aviary1.0?
I have been remiss in thanking everyone involved, especially Peter, for fixing this bug so quickly. This was a showstopper for my product under 1.7. Thanks guys! Cheers, - Bill | https://bugzilla.mozilla.org/show_bug.cgi?id=248172 | CC-MAIN-2019-22 | refinedweb | 482 | 60.92 |
From TLS to authentication, “crypto” is used for a lot more than just currencies. Security should be part of every developer's toolkit and cryptography a fundamental building block for the libraries and tools we use to protect our data and applications. This post will dive into public key cryptography, also known as asymmetric cryptography, an overview of how it works, and its everyday use cases — including how Twilio uses public-key crypto in our Authy application and to secure our API.
Let's start with some context and history.
Meet Alice and Bob
Alice and Bob have a history of illicit dealings. We're not really sure what they're up to, but they don't want us, or the ever-curious Eve, to know. Before the internet, Alice and Bob could pass secret messages by encrypting text with an agreed upon cipher. Maybe that was through letter substitution or shifting or other sophisticated methods. They agreed on the method in advance and both knew how to encode and decode the end message.
This is known as symmetric cryptography — the same key is used in both directions. This worked well for World War II spies, but what happens when our secret messengers can't agree on the key in advance?
We invented public-key, or asymmetric, cryptography so that two people like Alice and Bob could communicate securely without meeting first to agree on a shared encryption key or risk an eavesdropper like Eve to intercept the key over unsecured communication channels. This is an incredibly necessary advancement because of the internet — we are no longer only transacting and communicating with people we know and trust.
What is Public Key Cryptography?
In public-key cryptography, also known as asymmetric cryptography, each entity has two keys:
- Public Key — to be shared
- Private Key — to be kept secret
These keys are generated at the same time using an algorithm and are mathematically linked. When using the RSA algorithm, the keys are used together in one of the following ways:
1. Encrypting with a public key
Use case: sending messages only the intended recipient can read.
Bob encrypts a plaintext message with Alice's public key, then Alice decrypts the ciphertext message with her private key. Since Alice is the only one with access to the private key, the encrypted message cannot be read by anyone besides Alice.
2. Signing with your private key
Use case: verifying that you're the one who sent a message.
Alice encrypts a plaintext message with her private key, then sends the ciphertext to Bob. Bob decrypts the ciphertext with Alice's public key. Since the public key can only be used to decrypt messages signed with Alice's private key, we can trust that Alice was the author of the original message.
These methods can also be combined to both encrypt and sign a message with two different key pairs.
Use Cases of Public-Key Cryptography
Public-key cryptography is used in a lot of scenarios:
- SSH
- TLS (HTTPS, formerly SSL)
- Bitcoin
- PGP and GPG
- Authentication
- Public Key Infrastructure (PKI) used for things like SHAKEN/STIR
How Twilio Uses Public-Key Cryptography
Authy Push Authentication
Authy
One of the ways Twilio uses public-key cryptography is in Authy applications for push authentication (seen above). For every site you enable on Authy, your device generates a new RSA key pair on your device and only sends the public key to our servers — your private key never leaves your device. When you "Approve" or "Deny" a request on your device, the Authy app validates:
- That the request comes from the sender who is in control of the private key
- That the authorization request has not been modified in transit
SHAKEN/STIR
SHAKEN (Signature-based Handling of Asserted information using toKENs) / STIR (Secure Telephone Identity Revisited) is a new industry standard to combat call spoofing and be able to track down spam callers more effectively. SHAKEN/STIR uses a public-key infrastructure with centralized Certificate Authorities (CAs) similar to how TLS is managed. With this technology, Twilio will sign your calls to add authentication. Learn more about enabling SHAKEN/STIR.
PKCV
Twilio also offers Public Key Client Validation as an added layer of security for making API requests. Like Authy, when you send a request with Public Key Client Validation, Twilio validates:
- That the request comes from a sender who is in control of the private key
- That the message has not been modified in transit
You can read more about PKCV and how to implement it here.
How Does Public Key Crypto Work? Trapdoor Functions for Security
Think about mixing together two paint colors: it's simple to combine them, but challenging to factor back out into the original colors. We see this idea all the time in physical security: things like zip ties, locks, tamper proof screws, sealed packages, and more. It's possible to undo these things without detection, but it's difficult enough that most people don't take the time or money to try. Cryptography relies on the same principle, using calculations that are easy to do in one direction and really hard to reverse unless you have a key. We call these trapdoor one-way functions.
One way we achieve this in digital security by using really large prime numbers and multiplying them together. It's easy for a computer to compute the product of two 600-digit prime numbers, but really hard to take the result and find its factors.
Your Challenge: find the two prime factors of 4,757
There are a few ways to do this, including brute force trial and error. For a 4-digit number you could write a script that loops through known prime numbers, but once that target number becomes 1000 digits long that's going to take a long time.
Your Next Challenge: multiply 67 and 71
Now that is much easier!
Your Final Challenge: let's build a key pair together! Don't worry, we'll walk you through this one. The numbers we use in our example are intentionally small.
Note: this example is for instructional purposes. Please don't roll your own cryptography for your application!
This example uses the RSA algorithm, one of many options for calculating key pairs for asymmetric encryption. You can follow along in python code below or find the whole script on my GitHub.
1. Pick two prime numbers:
p = 67 q = 71
2. Multiply your primes
n = p * q # n = 67 * 71 # n = 4757
3. Find the least common multiple (lcm) of p -1 and q -1
import math def lcm(a, b): return a * b // math.gcd(a, b) x = lcm(p - 1, q - 1) # x = lcm(67 - 1, 71 - 1) # x = lcm(66, 70) # x = 2310
4. Pick a number less than x that is not a divisor of x:
e = 23
5. Compute the modular multiplicative inverse of e:
def inverse_mod(e, x): t = 0 newt = 1 r = x newr = e while newr != 0: q = r // newr t, newt = newt, t - q * newt r, newr = newr, r - q * newr if r > 1: return None if t < 0: t += x return t d = inverse_mod(e, x) # d = 1607
Now we have all we need to create our keys!
public_key = (4757, 23) # (n, e) private_key = (4757, 1607) # (n, d)
We can use the public key to encrypt a message:
message = 123 encrypted = pow(message, e, n) # encrypted = pow(123, 23, 4757) # encrypted = 418
And we can use the private key to decrypt the message:
decrypted = pow(encrypted, d, n) # decrypted = pow(418, 1607, 4757) # decrypted = 123
...which gives us the original message! 🤯
Public Key Cryptography Algorithms and Key Size
RSA (Rivest–Shamir–Adleman)
The example showed how these trapdoor one-way functions are incorporated into common cryptography algorithms. Most of our explanation so far has focused on RSA, named for the researchers Rivest, Shamir, and Adleman, and one of the most common encryption algorithms used for public-key cryptography. You've probably used it if you've ever generated a GitHub SSH key, for example:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
This is how you generate an RSA key pair for real. Let's break down what's happening in this command.
ssh-keygen is a command included in MacOS and Linux (and in Git Bash for Windows) used for "authentication key generation, management and conversion."
-t rsa tells it to use the rsa algorithm. Other options include
dsa (Digital Signature Algorithm) and
ecdsa (Elliptic Curve DSA).
-b 4096 specifies the key size in bits to use. Key size impacts the security strength, measured in bits of security. Security strength is "a number associated with the amount of work (that is, the number of operations) that is required to break a cryptographic algorithm or system" according to the NIST Recommendation for Key Management. For example, an RSA key size of 2048 gives 112 bits of security while a key size of 3072 gives 128 bits of security.
The current NIST recommendations for RSA is to use at least 2048 bits for your key. These recommendations take into account advancements in hardware and computation power, so if you want your keys to be secure past 2030 NIST recommends 3072-bit encryption.
Once you run this command on your computer, you'll have two files: a public key and a private key. It's important that you do this on your own computer so that you only have to copy the public key to GitHub's servers. Now, every time you push code to GitHub, it signs the request with your private key, which GitHub authenticates by using your public key. Note: ssh authentication is different from signing git commits, which uses GPG, another form of public-key cryptography. It's everywhere!
Other common algorithms you might encounter include:
Diffie–Hellman
This is the foundation for public-key cryptography. The Diffie–Hellman approach involves two people building a shared secret key together. It's pretty neat. Here's a great video that explains how the Diffie–Hellman method works.
Elliptic-Curve Cryptography (ECC)
This has gained a lot of recent traction because the Elliptic Curve DSA algorithm can achieve the same level of security as RSA but with smaller key sizes. ECC is also what cryptocurrencies like Bitcoin use. I like this explainer for how ECC works if you want to learn more.
Elliptic Curve Addition (Image By SuperManu [GFDL or CC BY-SA 3.0], via Wikimedia Commons)
Cryptography in Your Applications
As a general rule, you should never roll your own crypto. Use libraries that implement well-accepted encryption schemes like RSA. If you're building common security workflows, like login, most major frameworks will already have encryption built-in.
Now that you have some security fundamentals under your belt, it might be time to audit your password requirements or implement two-factor authentication. If you have any questions about cryptography, leave me a comment or find me on Twitter @kelleyrobinson. | https://www.twilio.com/blog/what-is-public-key-cryptography | CC-MAIN-2021-17 | refinedweb | 1,841 | 60.04 |
Results 1 to 9 of 9
I'm really stuck on this one, and i've been for days on google now, only to run in circles I have a graphix tablet that i can't find drivers for ...
js_x, KB Gear jam studio / Pablo graphix tablet drivers...
I have a graphix tablet that i can't find drivers for linux for it. The company who made it went out of business before they even made win2000 drivers, and wine won't even install the 95/98 drivers. There are people who have made XP/2000/2003 drivers, but wine will not install them either.
From alllllllllllllll the info i've gathered so far, XORG makes a 'js_x' driver for it, but the article doesn't say how to USE it. I've also been to the Linux Wacom project on SF and that didn't work either. Some guy wrote an article that i came across on google, and he talked about how he checked the packets from the device, and wrote a driver to handle them. The problem is, i don't know what the hell to DO with the files! I'm just too new still
. I have also come across a looooottt of diff files posted on the net for it, but again, it might as well be Arabic to me.
Here are the contents of the two files that guy wrote:
tablet.cCode:
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include "tablet.h" #define BUFLEN 100 int tablet_fd = -1; int tablet_x = 0, tablet_y = 0; int tablet_button = 0, tablet_touch = 0, tablet_pressure = 0; static void (*callback_func)(void) = NULL; /* returns 1 for success */ int tablet_init(void) { int fd; struct termios t; fd=open(TABLET_FILE,O_RDWR); if (fd<0) return perror(TABLET_FILE),0; tcgetattr(fd,&t); t.c_cflag|=CLOCAL|CS8; t.c_cflag&=~CRTSCTS; t.c_iflag&=~IGNPAR; t.c_oflag&=~ONLCR; t.c_lflag&=~(ECHOE|ECHOK|ECHOKE|ECHOCTL); cfsetospeed(&t,B9600); t.c_cc[VTIME]=1; tcsetattr(fd,TCSANOW,&t); tablet_fd = fd; return 1; } static void got_packet(unsigned char *s, int len) { if ((len == 1) && ((s[0] & 0x0F) == 0x08)) { /* so far as I can tell this is just a pen-in-range * notification. big deal. */ } else if (len == 6) { /* the packets look like this (second line is bit significance): * 1??? 00bt 0xxx xxxx 0xx0 0xxx 0yyy yyyy 0y00 yyyy 00pp pppp * 876 5432 10 ba9 765 4321 0 ba98 54 3210 * so 12-bits of X, 12-bits of Y, button, touch, 6-bits of pressure, * and 3 mystery bits */ tablet_button = (s[0] & 0x02) ? 1 : 0; tablet_touch = (s[0] & 0x01) ? 1 : 0; tablet_x = (s[2] >> 5) | ((s[1] & 0x7F) << 2) | ((s[2] & 0x07) << 9); tablet_y = (s[4] >> 6) | ((s[3] & 0x7F) << 1) | ((s[4] & 0x0F) << 8); tablet_pressure = s[5] & 0x3F; if (callback_func) callback_func(); } else { /* craziness */ } } /* returns the number of complete packets read */ int tablet_read(void) { static unsigned char buf[BUFLEN]; static int buflen = 0; unsigned char s[BUFLEN]; int i,j; int ret = 0; i = read(tablet_fd, s, BUFLEN); if (i <= 0) return 0; for (j = 0; j < i; j++) { if (s[j] & 0x80) { if (buflen) { got_packet(buf, buflen); ret++; } buflen = 0; } buf[buflen++] = s[j]; if (buflen >= BUFLEN) { buflen = 0; printf("overflow in tablet packetizing\n"); } } return ret; } void tablet_register(void (*func)(void)) { callback_func = func; } void tablet_close(void) { close(tablet_fd); tablet_fd = -1; }Code:
#ifndef TABLET_H #define TABLET_H #define TABLET_FILE "/dev/ttyS0" extern int tablet_fd; extern int tablet_x, tablet_y; extern int tablet_button, tablet_touch, tablet_pressure; /* open the tablet, returns 1 for success */ int tablet_init(void); /* perform one read() on the tablet, returns num packets read */ int tablet_read(void); /* register a callback that is called when tablet_* vars update */ void tablet_register(void (*func)(void)); /* close the tablet */ void tablet_close(void); #endif /* TABLET_H */
Thanx
This person said they got it working, but i don't understand all their directions, as he doesn't explain how and where he did everything.
Also, while plugging and unplugging it in the different usb ports, dmesg gave this:
Code:
usb 2-1: USB disconnect, address 3 usb 2-1: new low speed USB device using uhci_hcd and address 4 usb 2-1: configuration #1 chosen from 1 choice hiddev96: USB HID v1.00 Device [KBGear USB Tablet] on usb-0000:00:1d.1-1 usb 2-1: USB disconnect, address 4 usb 2-1: new low speed USB device using uhci_hcd and address 5 usb 2-1: configuration #1 chosen from 1 choice hiddev96: USB HID v1.00 Device [KBGear USB Tablet] on usb-0000:00:1d.1-1 usb 2-1: USB disconnect, address 5 usb 1-1: new low speed USB device using uhci_hcd and address 2 usb 1-1: configuration #1 chosen from 1 choice hiddev96: USB HID v1.00 Device [KBGear USB Tablet] on usb-0000:00:1d.0-1 usb 1-1: USB disconnect, address 2 usb 1-2: new low speed USB device using uhci_hcd and address 3 usb 1-2: configuration #1 chosen from 1 choice hiddev96: USB HID v1.00 Device [KBGear USB Tablet] on usb-0000:00:1d.0-2
I seen where someone was posting a bunch of gibberish about files that made no sense. After digging around, i found the same files. I know i need to edit them or use them, but i don't know how?
/usr/src/kernels/2.6.18-1.2798.fc6-i686/drivers/usb/input
That's where 'Kconfig' is, but i don't know what to DO with it, but the option IS IN THERE to include a module for my graphix tablet. Can someone please tell me what to do with that file? Do i recompile the kernel with i
This also looks promising, but i don't know how to get to the page that it's showing from MAN.
Using Firefox, if you click the link, hit <ctrl><f> and type USB_WACOM and it will take you to the spot that i'm referring to:
Here is the product page for the device as well:
Here's another page with a possable solution, that i still don't understand what to do with:
Also, i found an srpm for Xorg's js_x driver, but i don't know what to do with a srpm...:
I was looking at this article:
and read this section here:Code:
[PATCH] USB: add KB Gear USB Tablet Driver drivers/usb/Config.in | 1 drivers/usb/Makefile | 1 drivers/usb/hid-core.c | 4 + drivers/usb/kbtab.c | 179 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+)
I was looking at this article:
and read this section here:Code:
[PATCH] USB: add KB Gear USB Tablet Driver drivers/usb/Config.in | 1 drivers/usb/Makefile | 1 drivers/usb/hid-core.c | 4 + drivers/usb/kbtab.c | 179 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 185 insertions(+)
Does ANYONe know what to do with the file:
/usr/src/kernels/2.6.18-1.2798.fc6-i686/drivers/usb/input/Kconfig
I see that it is supposed to be run by something OTHER than the terminal, because it's text is interpreted, and when it's supposed to run, it will ask me if i wan't support for my tablet. This is good... but how do i get it to RUN!?
Thanx
I have a KBgear USB tablet and is detected automatically with Ubuntu 6.10, it is also hot pluggable so is detected when I take it downstairs to use on the laptop. Working perfectly with GIMP, Inkscape and Xara so far. I have not had to do anything to make it work, perhaps try Ubuntu?
- Join Date
- Jul 2007
- 1
If you have the xf86-input-jamstudio-1.1.0.tar.bz2 file, extract it to any directory and then open a terminal console.
cd to your directory, then type this command:
./install.sh
Hopefully, that should do it. | http://www.linuxforums.org/forum/hardware-peripherals/75627-js_x-kb-gear-jam-studio-pablo-graphix-tablet-drivers.html | CC-MAIN-2014-15 | refinedweb | 1,304 | 68.7 |
User Commands nistest(1)
NAME
nistest - return the state of the NIS+ namespace using a
conditional expression
SYNOPSIS
nistest [ -ALMP ] [ -a rights | -t type ] object
nistest [ -ALMP ] [ -a rights ] indexedname
nistest -c dir1 op dir2
DESCRIPTION.
OPTIONS
The following options are supported:
-a rights
This option is used to verify that the current process
has the
desired or required access rights on the named object
or entries. The access rights are specified in the
same way as the nischmod(1) command.
-A All data. This option specifies that the data within
the table and all of the data in tables in the ini-
tial table's concatenation path be returned. This
option is only valid when using indexed names or fol-
lowing fol-
lowing links.
SunOS 5.8 Last change: 30 Jan 1998 1
User Commands nistest(1)
-t type
This option tests the type of object. The value of
type can be one of the following:
D Return true if the object is a directory object.
G Return true if the object is a group object.
L Return true if the object is a link object.
P Return true if the object is a private object.
T Return true if the object is a table object.
-c Test whether or not two directory names have a certain
relationship to each other, for example, higher than
(ht) or lower than (lt). The complete list of values
for op can be displayed by using the -c option with no
arguments.
EXAMPLES
Example 1: Examples of.
ENVIRONMENT VARIABLES
NIS_PATH
If this variable is set, and the NIS+ name is not
fully qualified, each directory specified will be
searched until the object is found. See
SunOS 5.8 Last change: 30 Jan 1998 2
User Commands nistest(1)
nisdefaults(1).
EXIT STATUS
The following exit values are returned:
0 Successful operation.
1 Failure due to object not present, not of specified
type, and/or no such access.
2 Failure due to illegal usage.
ATTRIBUTES
See attributes(5) for descriptions of the following attri-
butes:
____________________________________________________________
| ATTRIBUTE TYPE | ATTRIBUTE VALUE |
|_____________________________|_____________________________|
| Availability | SUNWnisu |
|_____________________________|_____________________________|
SEE ALSO
nis+(1), nischmod(1), nisdefaults(1), nismatch(1), attributes(5)
SunOS 5.8 Last change: 30 Jan 1998 3 | http://www.manpages.info/sunos/nistest.1.html | crawl-003 | refinedweb | 373 | 64.3 |
SCT-013-030 Energy Meter
Hi, great sketch! But i have a question: how to chanhe this sketch to send kwh often then once per hour? Maybe safer will be send kwh like sending wh - every minute?
@maciejka : you can change the value on column 98: minuten == 60
"Minuten" is german for minutes. if you want to report every minute change the value to 1.
@Surge86 : thank you for your improvements! I will compare our codes and hopefully learn a lot.
I startet arduino programming in november and keep on learning.
greets patrick
Thanks, i will test it
Regards
Maciej
Thanks for sharing this! I am hoping to create an all-in-one extension cord plus this meter. I hope this way I can detect when a pump fails or maybe just how much power is being used.
I have read that you when using a CT you must be careful to avoid a voltage build up on the CT output. Is that a concern with this current setup? With a battery powered arduino you are not grounded? In my extension cord project I was thinking I could use the ground from the extension cord.
I am not an electrical engineer so I may be way off here, just trying to be safe.
I think this setup could be very useful. In the high school greenhouse where I have my sensor network there are so many pumps, heaters, air stones, that need to be monitored and an alert sent if they stop working.
I may also try this with the sensebender micro.
- patrick schaerer last edited by patrick schaerer
As far as i understand there is a resistor built in the sct013 that prevents this voltage buildup. But i am not an electrician.
I optimized my code with the help of Surge.
I added a KWH reading on a restart of the node.
Now it's Version 1.3
Hello Patrick, thank you for sharing your project. I tested it and it works fine but I want to test how acurate it is with low current measurements. Can you please tell me how to change your code to get results below 60W? I'm just beginning to learn arduino-programming so i don't understand everything..
@m1rk0
In Line 95 is the following expression:
if (Irms < 0.3) Irms = 0;
Irms is RMS current. The expression sets all current smaller than 0.3 as 0.
You can delete this line for smaller values.
I suggest to use a SCT-013-005 instead of a SCT-013-030.
Thank you patrik, i already ordered an sct-013-005, but i need sometimes higher measurements than 5a. With this second sensor i will be able to compare the results.
Thank you patrik, i already ordered an sct-013-005, but i need sometimes higher measurements than 5a. With this second sensor i will be able to compare the results.
yeah 5A is within its range. I usually sit between 1A-20A
hello, where is the MySensor.h file??
This is made for an earlier version of the library, things has changed a lot since.
first off, the library header file is now called MySensors.h (note the added "s" to the name). But also how you use / initialize the mysensors project is very different in 2.x, than in 1.x,
have a look at this post to get an idea of what you have to change, to upgrade your arduino sketch to work with MySensors 2.x library
- patrick schaerer last edited by patrick schaerer
I alread updated to MySensors 2.0
This is the update code:
I also edited the first. * ******************************* * * EnergyMeterSCT by Patrick Schaerer * This Sketch is a WattMeter used with a SCT-013-030 non invasive PowerMeter * see documentation for schematic * * Special thanks to Surge, who optimized my code. * * updated to mySensors Library 2.0 */ #define MY_RADIO_NRF24 #define MY_REPEATER_FEATURE #define MY_DEBUG #include <SPI.h> #include <MySensors.h> #include <EmonLib.h> #define ANALOG_INPUT_SENSOR 1 // The digital input you attached your SCT sensor. (Only 2 and 3 generates interrupt!) //#define INTERRUPT DIGITAL_INPUT_SENSOR-2 // Usually the interrupt = pin -2 (on uno/nano anyway) #define CHILD_ID 1 // Id of the sensor child EnergyMonitor emon1; MyMessage wattMsg(CHILD_ID,V_WATT); MyMessage kwhMsg(CHILD_ID,V_KWH); MyMessage msgKWH(CHILD_ID,V_VAR1); unsigned long SLEEP_TIME = 60000 - 3735; // sleep for 60 seconds (-4 seconds to calculate values) float wattsumme = 0; float kwh = 0; float wh = 0; int minuten = 0; //vorher 61 boolean KWH_received=false; //Humidity Sensor Code #include <DHT.h> #define CHILD_ID_HUM 2 #define CHILD_ID_TEMP 3 #define HUMIDITY_SENSOR_DIGITAL_PIN 2 DHT dht; float lastTemp; float lastHum; boolean metric = true; MyMessage msgHum(CHILD_ID_HUM, V_HUM); MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); //End of Humidity Sensor Code void setup() { //energy clamp code //gw.begin(incomingMessage, AUTO, true,0); Serial.begin(115200); emon1.current(ANALOG_INPUT_SENSOR, 30); // Current: input pin, calibration. double Irms = emon1.calcIrms(1480); // initial boot to charge up capacitor (no reading is taken) - testing request(CHILD_ID,V_VAR1); //end of energy clamp code //Humidity Sensor Code dht.setup(HUMIDITY_SENSOR_DIGITAL_PIN); metric = getConfig().isMetric; //End of Humidity Sensor Code } void presentation() { // Send the sketch version information to the gateway and Controller // Register this device as power sensor sendSketchInfo("Energy Meter SCT013", "2.0"); present(CHILD_ID, S_POWER); present(CHILD_ID_HUM, S_HUM); present(CHILD_ID_TEMP, S_TEMP); } void loop() { //process(); //KWH reveived check if (!KWH_received) request(CHILD_ID,V_VAR1); // power used each minute if (minuten < 60) { double Irms = emon1.calcIrms(1480); // Calculate Irms only if (Irms < 0.3) Irms = 0; long watt = Irms*240.0; // default was 230 but our local voltage is about 240 wattsumme = wattsumme+watt; minuten++; send(wattMsg.set(watt)); // Send watt value to gw Serial.print(watt); // Apparent power Serial.print("W I= "); Serial.println(Irms); // Irms } // end power used each minute // hours KW reading if (minuten >= 60) { wh = wh + wattsumme/60; kwh = wh/1000; send(kwhMsg.set(kwh, 3)); // Send kwh value to gw send(msgKWH.set(kwh, 3)); // Send kwh value to gw wattsumme = 0; minuten = 0; } // end of hourly KW reading // Humidity Sensor Code if (minuten == 15 || minuten == 30 || minuten == 45|| minuten == 60) {); } } //End of Humidity Sensor Code wait(SLEEP_TIME); } void receive(const MyMessage &message) { if (message.type==V_VAR1) { kwh = message.getFloat(); wh = kwh*1000; Serial.print("Received last KWH from gw:"); Serial.println(kwh); //send(kwhMsg.set(kwh, 3)); // Send kwh value to gw KWH_received = true; } }
- Talat Keleş last edited by Talat Keleş
@patrick-schaerer said:
I alread updated to MySensors 2.0
I just got my sct-013-000 non-burden version and will try it as soon as atmega+nrf packs arrive. Thanks for code update.
Meanwhile what is "msgKWH" for? What is different than "kwhMsg"? Which controller do you use?
Hello, now with the new code I get this error:
Arduino: 1.6.9 (Windows 10), Board: "Arduino/Genuino Uno"
WARNING: Spurious .mystools folder in 'MySensors' library
C:\Users\LENOVO\Desktop\arduino_code\Voltage_sensor_5\Voltage_sensor_5.ino:58:19: fatal error: DHT.h: No such file or directory
#include <DHT.h>
^
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
- Talat Keleş last edited by
@john7845
Error is related to missing library of DHT. If you will use DHT temperature/humidity sensor in your circuit, you should add DHT library to your Sketchbook/libraries folder. If you don't use that sensor, clear or comment out dht related codes in sketch.
Hello,
I use this code just to see if the current sensor works, but I get 0.0 on the serial! What am I doing wrong?
/* * (1.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
Someone??
Again, I take zeros.
339) | https://forum.mysensors.org/topic/2700/sct-013-030-energy-meter/16 | CC-MAIN-2018-09 | refinedweb | 1,282 | 68.16 |
Developer Product Briefs
Check out the latest VS.NET add-ins, including a component that lets you bidirectionally transform data between XML formats and relational database structures.
Proposion Report Adapter 1.0
Proposion Report Adapter is a set of extensions for integrating Lotus Notes/Domino into Microsoft SQL Server 2000 Reporting Services. Proposion Report Adapter helps you use the Report Designer client to create professional reports that draw data, including images and attachments, directly from Notes and Domino databases. Users can visit the Report Server at run time using their Web browser and access cached or up-to-the minute versions of the report and view them interactively or download them in a variety of formats, including HTML, PDF, Excel, TIFF, CSV, and XML. Proposion Report Adapter also allows any Reporting Services report, whether or not it's based on Notes data, to be run automatically on the server and delivered to subscribers via native Notes Mail or deposited in a Notes database. Starts at $795.
Proposion
Web:
Phone: 978-388-7342
Updates:
Allora 4.1
Allora is a middleware tool that lets you bidirectionally transform data between XML formats and relational database structures. Version 4.1 includes a multiple SELECT feature. This option allows you to work with multiple sub-maps that are then joined in real time with XSL, a W3C language for transforming XML documents. Rather than use database-specific SQL dumps or flat files that cannot contain table relationships or constraints, you can persist the complete database structure and data into XML for easy access or transport, and you can re-create it on any other database platform at a minimum cost. Other enhancements include support for namespace definitions, complex database expressions, NetBeans 4.1, and stored procedures in Oracle packages. Contact vendor for pricing.
HiT Software
Web:
Phone: 408-345-4001
AspLib 3.01
AspLib is a component library that features an integrated, all-in-one pack of 18 different components to facilitate your ASP.NET development cycle. These components allow you to give your Web applications a Windows-style interface. The AspLib component library offers Binary Image, Button, Calendar, Checkbox, ColorPicker, ComboBox, DualSelectBox, and ToolBar, among many other components. It also features a Web-based WYSIWYG editor for editing HTML pages online. You can use it to create tables, links, and pictures; manage CSS styles; change text color, size, pattern, and font; and add snippets and insert images. Its design with Word-style toolbar buttons lets you start editing HTML pages without any training. $299.
Astron Digital
Web:
ComponentOne Doc-To-Help 2005
ComponentOne Doc-To-Help 2005 allows you to use any HTML editor for your source content, convert RoboHelp and other HTML Help projects, and generate NetHelp, a browser-independent, HTML-based help system. You can use styles from a customizable stylesheet to define help systems within your favorite HTML editor or Word. Version 2005 also features D2HML (Doc-To-Help Markup Language) and FrontPage integration. NetHelp lets you publish your documentation on the Web so that your audience can view it regardless of their platform. Doc-To-Help Enterprise 2005 $999.95; Doc-To-Help for Word 2005 $749.95.
ComponentOne
Web:
Phone: 800-858-2739; 412-681-4343
ComponentOne Studio Enterprise 2005 Vol. 2
ComponentOne Studio Enterprise 2005 Vol. 2 adds a new component, Barcode for .NET, as well as more than 60 updates to .NET WinForms and ASP.NET WebForms components already included in the Studio Enterprise subscription. Barcode for .NET allows you to create barcodes dynamically as image objects and display them in your .NET applications. You can add barcodes to reports, grid cells, Web pages, standard .NET PrintDocument objects, and more. You can print, save, and manipulate barcodes to fit any application, and you can add control symbols and checksums automatically. New features were also added to Chart for .NET, WebChart for ASP.NET, Menus and Toolbars for .NET, Reports for .NET, and more. $999.95; upgrade $749.95.
ComponentOne
Web:
Phone: 800-858-2739; 412-681-4343
Ektron CMS400.NET 5.0
Ektron CMS400.NET delivers an infrastructure to create, manage, publish, and reuse Web content, Microsoft Office documents, and other assets, while Webmasters and site administrators retain site control. It provides Web content management functionality, including WYSIWYG editing, workflow/approval, versioning/history/audit trails, metadata support, task management, and more. Advanced features include integrated document management, an online forms engine, a calendar module, XML indexing for advanced search, content translation/localization, RSS support, and a new Explorer-like interface. An open API lets you customize the Ektron system. Version 5.0 supports Macromedia ColdFusion, Microsoft ASP, JSP, and PHP, and ASP.NET sites. Contact vendor for pricing.
Ektron
Web:
Phone: 866-435-8766; 603-594-0249
Enterprise Blocks 2.5
Enterprise Blocks is a set of .NET Web controls that help you perform data analysis on SQL Server databases. Version 2.5 includes new and upgraded ASP.NET Web controls, as well as member properties filtering and drill-through to detail data. The Enterprise Blocks catalog and workbook Web controls are available as SharePoint Web parts. The Enterprise Blocks add-in for Microsoft Reporting Services provides drag-and-drop OLAP inside Reporting Services against Analysis Services databases. The add-in for DotNetNuke allows these end-user documents or objects to be saved into and retrieved from the Windows file system as XML documents. It exposes the Windows file system allowing end-user navigation to content from inside DotNetNuke. $495.
Enterprise Blocks
Web:
Franson GpsTools 2.20
Franson GpsTools allows you to develop GPS, mapping, and basic GIS applications in Visual Studio. Version 2.20 includes vector map support, which lets you draw polygons and polylines, as well as display, save, and manage ESRI Shapefiles. It also lets you access GPS position, speed, and satellite information, without any knowledge of low-level GPS protocols. It supports almost all geographic coordinate systems on earth with a new custom grid and custom datum feature. You can define raster maps and draw icons, lines, ellipses, rectangles, and other objects on them. You can connect these maps to the GPS data, where you can rotate and zoom them. You can also draw objects on multiple layers. Starts at $49.
Franson Technology
Web:
Phone: +46-8-612-50-70
InstallShield 11
InstallShield 11 keeps you up to date with support for the latest technologies and industry standards to avoid installation failures. It lets you author installations across all platforms, operating systems, and devices. You can create Windows Installer, InstallScript, and cross-platform installations and extend them to configure database servers, Web services, and mobile devices. Version 11 supports Microsoft's recent MSI 3.1 release, IIS 6.0, DIFx 1.1, and third-party objects, including DirectX, Crystal Reports, and WMI. It also includes more than 20 InstallScript enhancements, including the ability for installations to install and register 64-bit files. Starts at $1,399.
Macrovision
Web:
Phone: 800-374-4353; 847-466-4000
Proposion N2N 2.0
Proposion N2N is a native .NET data connector for integrating IBM Lotus Notes and Domino into Microsoft's .NET Framework and Visual Studio .NET development tools. It provides an implementation of Microsoft's ADO.NET managed data provider specification, the standard interface for accessing any data source from .NET applications. Proposion N2N lets you create, update, and delete documents in your Domino database. The connector can invoke Domino agents, allowing .NET applications to leverage investment in LotusScript and JavaScript libraries. Proposion N2N also includes the N2N Query Analyzer, programming examples and sample code, and integration into the Visual Studio .NET development environment. Starts at $795.
Proposion
Web:
Phone: 978-388-7342
SftTabs/ATL 5.0
SftTabs/ATL 5.0 offers 66 customizable tab-control styles designed specifically for use with Visual Basic 6 applications. Version 5.0 introduces six new tab styles; gradient-fill backgrounds; built-in MDI-style Close, Minimize, and Restore buttons including tooltips; new button styles; simplified deployment using registration-free activation on Windows XP; and online help, printable documentation, and design-time enhancements. The tab control supports many different styles and tab locations. Tabs can use different colors, display images, use special fonts, and display multiline text with various alignment options. Scrollable tabs offer several button styles, which can use custom images. The product supports development of wizard-style dialogs and similar multipage dialogs. $350.
Softel vdm
Web:
Phone: 941-505-8600
VBdocman .NET 2.0
VBdocman .NET 2.0 is a Visual Basic .NET add-in that allows you to generate technical documentation from VB.NET source files automatically. It parses source code and creates tables of contents, indexes, topics, cross-references, and context-sensitive help automatically. You can add additional descriptions manually, or let VBdocman .NET extract them from source code comments. You can add C#, XML, or JavaDoc comments in your source code. Version 2.0 features a WYSIWYG comment editor that helps you write your XML comments. It allows you to insert tables, lists, pictures, links, and other formatting directly into your source code. $229.
Helixoft
Web:
About the Author
Written/compiled by the editors of Visual Studio Magazine.
Printable Format
> More TechLibrary
I agree to this site's Privacy Policy.
> More Webcasts | https://visualstudiomagazine.com/articles/2005/09/01/transform-data-between-xml-and-databases.aspx | CC-MAIN-2018-13 | refinedweb | 1,538 | 50.43 |
The requirement coming from SO should have been reduced, it's probably a bug.
Please read OSS note 1457348, maybe it is applicable.
Edited by: Csaba Szommer on Jul 12, 2010 9:51 AM
Hi,
Your description is not clear...
1)
Now I want to do a KA (Consignment Pick-up) for remaining 5 pcs.
You sent 10 pcs to customer (consignment). Customer consumed 6 pcs. You want to pick up 5 pcs.
10 pcs - 6 pcs = 4 pcs --> why do you want to pick up 5 pcs?
2)
Based on the information given by you MMBE shows properly that you have 4 pcs...
MD04 shows ATP = 0 ???
It's not clear which field is "ATP" field in MD04... However if you have a look at OSS note 301681 you will see that system doesn't consider customer consignment for planning.
Regards,
Csaba
Edited by: Csaba Szommer on Jul 9, 2010 12:31 PM
You're right:
...
I want to do a KA (Consignment Pick-up) for remaining 4 pcs.
=> MMBE shows 4 pcs. on consignment stock.
In schedule lines it has just one entry
Delivery date Order Rounded Confirmed Sched.line cat. 11.06.2009 4 4 0 F1
I expected:
Delivery date Order Rounded Confirmed Sched.line cat. 11.06.2009 4 4 0 F1 09.07.2010 0 0 4 F1
When creating a delivery on KA it says:
"No schedule lines due for delivery up to the selected date"
Very very strange, isn't it.
What can you see in CO09? (you can set it for consignment)
Two remarks:
1) You said:
MMBE shows 4 pcs. on consignment stock.
Now, your reports show 5 pcs.
2) You didn't execute CO09 properly (in your message I can see SLoc stock --> consignment stock has nothing to do with SLoc). Please set consignment stock and proper customer on selections screen.
---
I guess, the problem is, that I just did a KE followed by a partially delivery/invoice.
Yes, it might be problem. That's why it would be necessary to run CO09 properly --> we would see whether there's any open order (e.g.).
Edited by: Csaba Szommer on Jul 9, 2010 2:46 PM
Edited by: Csaba Szommer on Jul 9, 2010 2:48 PM
Additonally to CO09 (with proper selection scriteria, please read in my previous message), you can also check:
1)
Who is the special stock partner ("SB") in your SO (the same customer from which special stock segment you want to pick up the stock)
2)
In VA05N you can also check whether there's any open order (consignment issue / pick up - I would use material and document type, but sold-to not) which can cause problem...
Edited by: Csaba Szommer on Jul 9, 2010 2:57 PM
When you have already issued the material to end customer and raised an invoice, then why do you create consignment pick up which should have been consignment return with order type KR. Consignment pick up can be generated only if the stock is in warehouse but in your case, from warehouse, it has been despatched to end customer.
thanks
G. Lakshmipathi
OK, I did a complete new test !
Material 2-006-51-6440 had 14 pc. in unrestricted stock!
MB51 after I did a KB, then moved it with a delivery to consignm. stock.
Then created a KE and delivered/invoiced just 10 pcs.
Material Material Description Plnt Name 1 SLoc MvT Movement Type Text S Mat. Doc. Item Entry Date Time Pstng Date Quantity in UnE EUn D 2-006-51-6440 LEVER KURZ 1901 Homag Italia S.p.A. Giussano 631 GD consgmt: lending W 4900096980 2 09.07.2010 15:22:52 09.07.2010 14 PC 0001 631 GD consgmt: lending 4900096980 1 09.07.2010 15:22:52 09.07.2010 14- PC 633 GI iss: cust.consgmt W 4900096981 1 09.07.2010 15:25:06 09.07.2010 10- PC
Now CO09 looks this way:
Date MRP element data rec./req. qty. conf. cum ATP qty. 09.07.2010 CCsgmt 78370 4 0 0 09.07.2010 CusOrd Totals record 10- 10 6- 09.07.2010 CusOrd 6200055439/000010/0001 10- 10 6-
MB58 shows:
Customer Name 1 Material Batch Unrestricted In Quality Insp. Restricted-Use BUn Material Description Plnt S 78370 FRIUL INTAGLI INDUSTRIES S.P.A. 2-006-51-6440 4 0 0 PC LEVER KURZ 1901 W
Now when I do a KA for the remaining 4 pcs. it says no qty available ?!?!?!
Hope now it's clear.
According to the data in your message you have an open order (6200055439) of 10 pcs for the material in the consignment stock segment of your customer. I guess this is not the pick-up order because previously you mentioned you wanted to create the KA (pick-up) order for the remaining quantity (4 pcs):
I want to do a KA (Consignment Pick-up) for remaining 4 pcs.
If it is so, this might be the reason why the system doesn't confirm the quantity in the SO for the 4 pcs (ATP quantity in CO09 is -6). You should find out why you have an order of 10 pcs for the material and take action accordingly (e.g. reject / delete it).
Edited by: Csaba Szommer on Jul 9, 2010 4:27 PM
Dear G.L.
consignm. return (KR) is normally used if customer wants to undo a consignm. issue. For instance customer didn't need the part and put it back into consignm. stock.
Consign. pickup (KA) is used to receive unused parts from consignm. stock into own warehouse!
Cheers
wolfi.
Add comment | https://answers.sap.com/questions/7503722/consignment-pickup-problem.html | CC-MAIN-2019-22 | refinedweb | 946 | 74.9 |
clearenv()
Clear the environment
Synopsis:
#include <stdlib.h> int clearenv( void );
Since:
BlackBerry 10.0.0
Library:
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
Description:
The clearenv() function clears the environment area; no environment variables are defined immediately after the clearenv() call.
Note that clearenv() clears the following environment variables, which may then affect the operation of other library functions such as spawnp():
- PATH
- SHELL
- TERM
- TERMINFO
- LINES
- COLUMNS
- TZ
Errors:
- ENOMEM
- Not enough memory to allocate a control structure.
Examples:; }
Last modified: 2014-06-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus | https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/c/clearenv.html | CC-MAIN-2020-10 | refinedweb | 114 | 50.84 |
#include <apr_buckets.h>
apr_bucket structures are allocated on the malloc() heap and their lifetime is controlled by the parent apr_bucket_brigade structure. Buckets can move from one brigade to another e.g. by calling APR_BRIGADE_CONCAT(). In general the data in a bucket has the same lifetime as the bucket and is freed when the bucket is destroyed; if the data is shared by more than one bucket (e.g. after a split) the data is freed when the last bucket goes away.
Links to the rest of the brigade
type-dependent data hangs off this pointer freelist from which this bucket was allocated.
The type of bucket. | http://apr.apache.org/docs/apr-util/1.4/structapr__bucket.html | CC-MAIN-2014-52 | refinedweb | 106 | 73.58 |
Every Colibri and Apalis Txx module has unique ID which can not be changed. Customer who wants to protect their application binary from getting copied and used by competitors can use this function to safeguard their interest.
unsigned long long getcolibritxxuniqueid();
#include "getuniqueid.h" int _tmain(int argc, _TCHAR* argv[]) { unsigned long long colibriTxxUniqueId =0; colibriTxxUniqueId = getcolibritxxuniqueid(); return 0; }
The supporting code is available as a zip file. The file contains a dll as well as a static library.
We recommend to link the static library to your code - this adds an extra layer of security, as the dll can be easily replaced. | https://developer.toradex.cn/knowledge-base/get-unique-id-of-colibri-txx-and-apalis-t30 | CC-MAIN-2019-09 | refinedweb | 103 | 54.42 |
In this article, I will explain how you can implement advanced filtering in fully AJAXified tables using the jQuery DataTables plug-in and ASP.NET MVC.
An example of a table with column filters is shown in the following figure:
As you can see, among the other table features (pagination, sorting), this table has separate filters placed in each column.
The goal of this article is to show how you can implement tables where the content of the table will be refreshed with AJAX calls each time the user changes the filter.
The jQuery DataTables^ plug-in can work in two major modes:
If you want to add pagination, sorting, and filtering in the client-side mode, you will need just one line of JavaScript code:
$("table#myTable").dataTable().columnFilter();
This line finds a table with id myTable, applies the dataTable plugin that adds
pagination and sorting features, and then applies the columnFilter plugin that puts filters in the individual columns.
This is everything you need to do in the client side mode. Optionally, you can customize plugins by passing different parameters - see more examples
on the DataTables Column Filter^ site.
myTable
However, if you work with larger data sets, you might want to implement some AJAXified table where filtering conditions will be sent to the server.
You will need to add more code for this, therefore I will explain that scenario in this article.
This article is part of a series about the integration of the jQuery DataTables^ plug-in with ASP.NET MVC web applications.
You might also want to take a look at other articles in this group:
In these articles, you might find lots of useful information about the usage of
the jQuery DataTables^ plug-in in ASP.NET MVC.
If you have not read the first article, I would recommend that you read it too because it contains some important details about the integration of
jQuery DataTables
with ASP.NET MVC applications.
jQuery DataTables is an excellent jQuery plug-in that enables you to display and manage information in the table.
To use the jQuery Datatables plug-in in your MVC applications, you will need to setup
the following steps.
First, you will need to place in your page an empty table that represents the table structure. An example of a table is shown in the following code:
<table class="display" id="example">
<thead>
<tr>
<th>ID</th><th>Company</th><th>Town</th><th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>ID</th><th>Company</th><th>Town</th><th>Date</th>
</tr>
</tfoot>
</table>
In this table are defined fixed parts of the table such as table header, table footer, but the body is empty. With the DataTables plug-in,
data that will be displayed in the body of the table will be loaded dynamically via AJAX calls.
Then, you will need a controller that has an action for providing data to the DataTables plug-in. This controller is shown in the following listing:
public class HomeController
{
public JsonResult DataProviderAction(string sEcho, int iDisplayStart, int iDisplayLength)
{
//Implementation of action body
}
}
The actual implementation of the controller method is not shown here. If you are not familiar with the integration of the DataTables plug-in into the MVC
application you can find more in the first article in this series - jQuery DataTables and ASP.NET MVC Integration. There you can find everything that is needed for integration with
the plug-in and the implementation of this controller action. Also, you have this method in the attached code sample.
Finally, you will need to bind the empty HTML table with the controller in order to start displaying data. This is done using the following jQuery call:
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
$('#example').dataTable({
"bServerSide": true,
"sAjaxSource": "/Home/DataProviderAction"
});
});
</script>
This initialization call defines that data will be fetched from the server side via an AJAX call, and that for Ajax source, action on the
URL "/Home/DataProviderAction" will be used. As a result, you will get a fully functional table with pagination,
sorting, and filtering as the one shown on the following figure:
This table is completely AJAXified - each time the user changes something on the client-side (e.g., change page or sort order, type anything in the search text box),
an AJAX request will be sent to the controller and new set of data will be shown in the table.
The goal of this article is to show you how you can replace the default, global single keyword search with advanced multi-column filters.
I will show you how you can use various types of filters such as drop down lists, date ranges, and a range of numbers.
Code is organized in a standard Model-View-Controller architecture.
The Model comes to a simple class containing company data. The fields that we need are company ID, name, date, and town. The source code of the company model class is shown below:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DateCreated { Filtering</title>
<link href="~/Content/dataTables/demo_table.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/jQuery-1.4.4.min.js" type="text/javascript"></script>
<script src="~/Scripts/jQuery.dataTables.min.js" type="text/javascript"></script>
<script src="~/Scripts/init.js" type="text/javascript"></script>
</head>
<body>
<table id="myDataTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Company name</th>
<th>Town</th>
<th>Date</th>
</tr>
</thead>
<tbody>
</tbody>
<thead>
<tr>
<th>ID</th>
<th>Company name</th>
<th>Town</th>
<th>Date</th>
</tr>
</thead>
</table>
</body>
</html>
Also, as a part of the view we would need to initialize the table with the jQuery DataTables plug-in and setup individual column filtering.
This part will be implemented in the init.js file shown in the following listing:
$(document).ready(function () {
// Setup JQuery UI date picker format to dd/mm/yy
$.datepicker.regional[""].dateFormat = 'dd/mm/yy';
$.datepicker.setDefaults($.datepicker.regional['']);
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "/Home/DataProviderAction"
}).columnFilter({
"aoColumns": [
{ "type": "number-range" },
{ "type": "text" },
{ "type": "select" },
{ "type": "date-range" }
]
});
});
The standard jQuery DataTables plugin is applied to the table, and configured in server-side processing mode. This initialization script will add standard DataTables features (pagination, filtering by keyword, and sorting).
In order to setup advanced column filtering, in this example, we use the DataTables Column Filtering add-on. This is
an additional plug-in for DataTables
that adds filters in each column and enables the user to filter data by individual columns.
Additionally, you can define in the plugin configuration what kind of filters you want to use in each column. In the example above, the first column will be filtered by number range, second filter will be plain text, in the third column will be placed
a select list,
and the last column will be filtered by date range using two date pickers. The first two lines in the script are used to set
the date format in the date pickers.
As a result of this script, individual column filters will be injected in the footer of the table as shown on the following figure.
This is just an optional configuration for filtering - as an alternative, you can place filters in the header or even in the external form.
Column filters are also AJAXified. Each time the user types something in the column filters, values will be sent to the controller action.
In the figure, you can see part of the AJAX request that is sent to the
controller action. In sSearch_0, sSearch_1,
sSearch_2, and sSearch_3 are sent values from the filters. Note that single filters (text box and select) are sent as single values,
and in the number range and date filters are lower and higher range combined in the same value and separated with
a tilde (~) character. If there is no value in the filter,
an empty string will be sent as a boundary.
sSearch_0
sSearch_1
sSearch_2
sSearch_3
Controller is the most important part in the integration. It should handle AJAX requests sent from the plug-in, take parameters that contain the filter condition,
and return companies that match the criterion. The full controller code is shown in the following listing:
public JsonResult DataProviderAction(string sEcho, int iDisplayStart, int iDisplayLength)
{
var idFilter = Convert.ToString(Request["sSearch_0"]);
var nameFilter = Convert.ToString(Request["sSearch_1"]);
var townFilter = Convert.ToString(Request["sSearch_2"]);
var dateFilter = Convert.ToString(Request["sSearch_3"]);
var fromID = 0;
var toID = 0;
if (idFilter.Contains('~'))
{
//Split number range filters with ~
fromID = idFilter.Split('~')[0] == "" ? 0 : Convert.ToInt32(idFilter.Split('~')[0]);
toID = idFilter.Split('~')[1] == "" ? 0 : Convert.ToInt32(idFilter.Split('~')[1]);
}
DateTime fromDate = DateTime.MinValue;
DateTime toDate = DateTime.MaxValue;
if(dateFilter.Contains('~')){
//Split date range filters with ~
fromDate = dateFilter.Split('~')[0] == "" ?
DateTime.MinValue : Convert.ToDateTime(dateFilter.Split('~')[0]);
toDate = dateFilter.Split('~')[1] == "" ?
DateTime.MaxValue : Convert.ToDateTime(dateFilter.Split('~')[1]);
}
var filteredCompanies = DataRepository.GetCompanies()
.Where(c => (fromID == 0 || fromID < c.ID)
&&
(toID == 0 || c.ID < toID)
&&
(nameFilter == "" || c.Name.ToLower().Contains(nameFilter.ToLower()))
&&
(townFilter == "" || c.Town == townFilter)
&&
(fromDate == DateTime.MinValue || fromDate < c.DateCreated)
&&
(toDate == DateTime.MaxValue || c.DateCreated < toDate)
);
//Extract only current page
var displayedCompanies = filteredCompanies.Skip(iDisplayStart).Take(iDisplayLength);
var result = from c in displayedCompanies
select new[] {
Convert.ToString(c.ID),
c.Name,
c.Town,
c.DateCreated.ToShortDateString()
};
return Json(new
{
sEcho = sEcho,
iTotalRecords = DataRepository.GetCompanies().Count(),
iTotalDisplayRecords = filteredCompanies.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
The first action here is taking values of the filter boxes from the Request object.
The jQuery DataTables plug-in sends these parameters in the sSearch_0,
sSearch_1, ..., sSearch_N parameters, where N is the number of columns. Range filters (number range and date range filters) that
use two values in the filters send ranges separated by ~ therefore they are split by this character, so the first part is set as
the lower boundary and the second
part as the higher boundary. Additionally, if only lower or higher boundary is entered on the page, default values are set (0 for number range boundary
and MinDate/MaxDate for date range boundary). If values in the range filter contain default values,
a filter will not be applied.
Request
sSearch_N
When the filter criteria is loaded, companies are filtered. There are many ways to implement this, e.g., via
a SQL query or a Stored Procedure in the database,
with LINQ query, etc. In this case, I have used the Where LINQ function where I have built
a lambda expression that filters companies by filter parameters.
Note that you can change the logic of this query depending on your requirements. In this query, I have used AND conditions but you can use OR instead.
Also I have used the less operator in range filters, but you can use less or equal if you need it. From the DataTables point of view, this server-side logic
is irrelevant - as long as you provide some results for the filter criterion, it will work fine.
Where
Once companies are filtered, they are formatted as a JSON array and returned back to the plug-in as a response of
the view. You can see more details about
returning a JSON response to a plug-in in the article jQuery DataTables
and ASP.NET MVC Integration. Also, you might notice that in this code,
we have used information about the first record that should be displayed in the
table (iDisplayStart) and the number of records that should be displayed on the current page in the table (iDisplayLength).
This LINQ query has a simple pagination command (the Skip(iDisplayStart).Take(iDisplayLength) part) that displays only a page that
the user currently
is looking at. In real code, you should handle sorting by columns too, but this is not shown in this example. However, you can find detailed description about
the integration in the jQuery DataTables and ASP.NET MVC Integration article.
iDisplayStart
iDisplayLength
Skip(iDisplayStart).Take(iDisplayLength)
In this article, I have explained how to implement a fully functional AJAXified table with advanced filters. As you can see, you need minimal effort on the
view side - just an empty table and simple JavaScript that can be easily changed.
All you need to do is create a controller action method that will handle AJAX calls sent by
the plug-in and filter them by criteria that the plug-in has sent.
In this article, I have shown some basic features of the DataTables and Column filter plug-in, however theree are
a lot of other settings that can be customized. Some of them are:
An example of the filtering configuration where filters are placed in a separate form is shown on the following figure:
Each time you change the filter condition in the form, the table will be refreshed. You can see other features of
the column filter plug-in
on the plug-in site.
Also, DataTables and Column Filter plug-ins do not need to work in AJAXified server-side processing mode. If you do not want to create
an action that handles requests, you
can just output all rows in the TBODY of the table and let them work in pure client-side mode. If you want to use them in this mode, you might need to take a look
at the Enhancing HTML tables using
the jQuery DataTables plug-in article where I have explained what you can do with these plug-ins in pure client-side mode.
Beware that
client-side mode should not be used with huge amounts of data. If you have a lot of records that should be processed, you should consider using server-side processing mode.
T. | http://www.codeproject.com/Articles/331855/jQuery-DataTables-Advanced-Filtering-in-ASP-NET-MV?msg=4217483 | CC-MAIN-2015-40 | refinedweb | 2,273 | 54.32 |
I am trying to use the HETCOR package to find the polychoric correlation matrix for my ordinal data. I have installed the package, as well as the Essentials for R & Python, and the polycor package for R. After working through a series of error messages, guided by previous threads, I now just get the following message: <br>
SPSSINC HETCOR command failed
In the Warnings section it simply says <type 'exceptions.Exeptions'>
I have no clue how to proceed or what the error is. Please help.
Answer by SystemAdmin (532) | Feb 21, 2013 at 08:53 PM
the R package can fail if the the data are too far from normality to find good starting values, but usually in that case a more informative message appears. If you can send me the data and syntax you are using, I can see whether there might be still a configuration issue. Let me know as well what version of everything you are running.<br>
Regards,
Jon Peck
Answer by SystemAdmin (532) | Feb 21, 2013 at 09:02 PM
I would not be surprised if my data was too far from normal and that is making it fail. Here is my data. I am using SPSS V.21 on a PC with Windows 7. I have the latest version (2.7) of R and Python. <a href="">I downloaded everything yesterday</a>.
Answer by SystemAdmin (532) | Feb 21, 2013 at 09:35 PM
Oh, and thank you for your help Jon, <br>
Cheers,
Nathan
Answer by SystemAdmin (532) | Feb 21, 2013 at 09:40 PM
If I use all the variables in the dataset, I get the exception error, but I also get this message:<br> There were 50 or more warnings (use warnings() to see the first 50) <br> SPSS HETCOR command was unable to compute the correlations due to data conditions. <br> This is usually due to some variables being too far from a bivariate normal distribution.<br>
Did you not get this? The job ran for 5 minutes or so before giving up.
However, if I take subsets of the data, I am able to compute the correlations among all the variables in each subset. I tried all the subsets of names that seem to go together. I used all the default settings in the dialog box.
I have attached the spv file.
Answer by SystemAdmin (532) | Feb 21, 2013 at 09:54 PM
Hi Jon, <br>
No, I didn't get that message. I tried to replicate your results by just pulling specific variables, but I got the same error message as I did originally "SPSSINC HETCOR command failed" This makes me think that it's a configuration problem and that it's not able to get far enough to see the data problems.
Answer by SystemAdmin (532) | Feb 21, 2013 at 10:22 PM
Try these programs to see whether programmability is basically working.<br>
begin program.
import spss
print 'ok'
end program.
begin program r.
print('ok')
end program.
Answer by SystemAdmin (532) | Feb 21, 2013 at 10:51 PM
Hello Jon, <br>
I am not sure where/how to input such a command. I work through the SPSS interface, not in R or Python or something similar. I'm not familiar where I can input a command like that into SPSS. I access (or attempt to) the Polychoric analysis through Analyze->Correlate-> Heterogeneous Correlations...
Please advise.
Thanks,
Nathan
Answer by SystemAdmin (532) | Feb 21, 2013 at 10:56 PM
Open a syntax window - Fil > New > Syntax.<br>
Paste in the code I posted.
Select the first program from begin program through end program.
Use Run > Selection
After it is done, repeat the process for the second program.
Answer by SystemAdmin (532) | Feb 21, 2013 at 11:02 PM
I get the following error message in the Output window:<br>
import spss
print 'ok'
end program.
>Error # 5712 in column 8. Text: spss
>A valid IMPORT subcommand name is expected but not found. Recognized
>subcommands are FILE, TYPE, KEEP, DROP, RENAME, and MAP.
>Execution of this command stops.
Answer by SystemAdmin (532) | Feb 21, 2013 at 11:19 PM
You didn't select the whole program. Your selection needs to incude the begin program line through the end program line.
44 people are following this question. | https://developer.ibm.com/answers/questions/217680/error-message-when-trying-to-use-spssinc-hetcor.html | CC-MAIN-2019-22 | refinedweb | 718 | 72.87 |
What Would We Lose From a Regionalized Internet? 433
Vegan Pagan asks: "If the internet was separated into regions, how much would you lose? How often do you visit other countries' web sites? How often do you e-mail people in other countries? Do you ever search in a language other than English, and if you do, how often does it turn up foreign vs domestic sites? What would foreigners lose by not being able to visit US-hosted sites, and how quickly would they be able to recreate what they lost? What other process that we are not normally aware of depend on a borderless internet? I find that although I often read in-depth news about other countries, the sites I get that news from are usually hosted in USA, and I only bother to read in English. Would the Americans who report world news be hindered by a segregated internet, or do they already have the means to overcome such barriers? How much more expensive and complicated would it be to access sites outside of 'your' internet, and how much slower would it be?"
Spam (Score:5, Funny)
Re:Spam, would it diminish? (Score:2, Funny)
Re:Spam (Score:2, Insightful)
About 80% of the worlds spam comes from USA.
My first thought exactally (Score:2)
Re:My first thought exactally (Score:2)
Re:My first thought exactally (Score:2)
It woud be a good start in the right direction for the US.
Re:My first thought exactally (Score:3, Insightful)
i dont have a problem with us being cut off from the rest of the world. It woud be a good start in the right direction for the US.
You think the USA would benefit from being more isolationist?! I'm not even going to ask - you're probably a fundamental religionist or something. By the way I was *joking* before
RESPONSIBLE and SENDING are different (Score:3, Interesting)
Yes- The US and US Companies (both large and small businesses) are, by many factual studies responsible for more of the Spam received by US users.
Now- That doesn't mean that the Spam messages originate within the US, and this is where WHAT you measure becomes important.
US firm wants to sell product
hires foreign Spammer to do his/her dirty work
profit?!
-M
Re:Spam (Score:2, Funny)
Its completely safe too! I don't get paid until you're satisfied it worked!
Just send $500 by Western Union to me here in Ukraine. In one month, once you are satisfied that the spam has stopped, tell me your confirmation number to release the money so I can pick it up!
i for one (Score:4, Insightful)
Re:i for one (Score:2)
Re:i for one (Score:3, Funny)
I pity you, and I pity me for knowing what you're talking about.
Re:i for one (Score:2)
Re:i for one (Score:2)
Sounds awesome! (Score:5, Funny)
As a programmer... (Score:5, Insightful)
Re:As a programmer... (Score:4, Interesting)
Re:As a programmer... (Score:5, Funny)
I recant my opposition, then.
Re:As a programmer... (Score:2)
Ubuntu
QEMU
Most codecs...
ebay (for the JDM car parts, Yo!)
The Reg
5fm (uncensored music and cool accents...)
I can't say NO loud enough.
Obviously.. (Score:5, Insightful)
Re:Obviously.. (Score:5, Interesting)
I'm in the US and 1/2 of the stuff I use is non-US (Score:2)
15% British/Australian
35% all other countries
And I get a lot of email from overseas.
I'm wondering how, exactly, the "separated into regions" would work. Is it the old
A lot (Score:5, Insightful)
A lot of software for Free OS'es violates software patents and other inane IP law here in the states, so it needs to be hosted outside our borders.
Regionalize the Internet, and I can't play DVDs in Linux anymore.
Re:A lot (Score:2, Interesting)
I think regionalization is a really poor idea and unworkable in most cases. By way of example, despite not being a citizen of the UK, I've seen all six episodes of The IT Crowd. At one point, I owned
RE (Score:2)
I visit foreign sites all the time- a lot of British music sites, and I love the BBC. When young, i watched BBC shows, and listened to the BBC World Service on shortwave.
I visit Carnival sites of course.
What the internet has allowed me to do, is see what people in other countries think, not just hear (occasionally, because even the few foreign counti
Google Seppuku (Score:2)
Holy (Score:2)
Arrr (Score:5, Funny)
I would lose access to a wonderful sweedish website. [thepiratebay.org]
Re:Arrr (Score:2)
Um, it's called the INTER-net for a reason... (Score:2)
Oh nothing much, except
/., google, del.icio.us, megatokyo, gmail... basically every website I check.
Don't assume that "foreign to the US"="non english speaker". Even if it did, I can see no compelling reason to segregate the net
TBH, I don't really understand why you're asking this; what would anyone have to gain by this?
A lot of sites are hosted in a country other than where their target audience is, for reasons of cost mainly, but also
Freedom Goes Down, Gov't Control Goes Up... (Score:5, Insightful)
Think about programs like Skype.
The US is getting close to making sure all encrypted communication has back doors for the government. This rule only seems enforceable on US based companies. Most of us probably didn't think too much about that, since we could always just use Skype or some other foreign based VOIP. Kiss that back up plan goodbye. Access to the executable gets diminished, as well as communication with Skype's servers.
The Government can then start to come down on all questionable content, since all hosting servers will on US soil.
I think internet fragmentation would be one the greatest disasters seen by the modern world. Is that a little over the top? Maybe... But I definitely don't want to see it happen.
Re:Freedom Goes Down, Gov't Control Goes Up... (Score:2)
Re:Freedom Goes Down, Gov't Control Goes Up... (Score:2)
Re:Freedom Goes Down, Gov't Control Goes Up... (Score:4, Informative)
Re:Freedom Goes Down, Gov't Control Goes Up... (Score:2)
No they're not, they won't, and they can't.
The age of purposefully building backdoors into software is long gone. If you built something that the FBI could get into, then so could anybody with enough programming knowledge to examine the binaries and deduce the functionality. All such attempts (such as, for instance, DVD encryption) has taken less than a week to reverse. It may suprise you to learn this, b
Re:Freedom Goes Down, Gov't Control Goes Up... (Score:2)
Re:Freedom Goes Down, Gov't Control Goes Up... (Score:3, Informative)
Wow, you need to lay off on the 1990 paranoid theories. Back doors into software are so easily cracked (50~100 corporate programmers versus 500~1000 skilled/curious/hobbist "lets take it apart and see how it works just for fun" programmers online) no programmer uses them anymore.
Gain nothing, lose everything (Score:5, Insightful)
You get to see a different point of view, you gain insight, you get to see things from a different angle. You get more information to base your judgement on. Thus your decisions will improve in quality, being based on more information. Not necessarily "better" information, but you can gain insight into the various views different people from all over the world have on a certain matter.
This will enable you to make well founded decisions and it allows you to understand some of the things going on around our planet better. Why some people react "irrational" from your point of view can be explained when you're able to listen to them and see their point of view.
I'd like at least regonailized searches (Score:2)
Overall, I like the ability to see sites that aren't here in the US. The different perspectives you get when reading about issues on a UK or Australian news site are both interesting and useful in getting a clearer picture of what is newsworthy in (
Sheesh QWZX (Score:3, Insightful)
Community. (Score:3, Insightful)
The internet is, as I see it, the biggest social step from being a couple hundred countries to becoming a world. The internet allows the social interaction to reach the level of economic interaction, and then proceed to push both further. Fracturing the internet would undo what I see as progress towards a world with less important boarders. Some day, country lines may be what state lines currently are.
What would I lose? (Score:4, Insightful)
Only access to the web sites of about half the people I know. And access to half my hardware vendors (including such minor things as case-maker Lian-Li and thermal product vendor Zalman). And access to the support site for my motherboard (made by Soyo). And a huge number of anime-related sites.
Is the picture clearer now?
Holy Shit (Score:5, Insightful)
But not any more. Today, I'm convinced Slashdot is as stupid as it will ever possibly get.
Fuck you guys. Seriously. If you're not even going to try to post interesting articles, I'm not going to bother reading anymore. Frankly, you shit on your readers when you post bullshit articles like this, and lately every time I've read slashdot I've felt like I was sharing a shower with tubgirl.
Come on... (Score:2)
If you are disliking
I read foreign sites (Score:3, Interesting)
I also read The Register occasionally for snarky IT, and it's sometimes good to get a feel for what people in foreign countries think about the US without going through the "We're awesome; they're all biased against us" filter. (It's also good to find out who is genuinely biased against us.)
I actually get a lot out of an international internet.
Also, global trade hinges on our current, growing levels of connectivity, and that will never allow some aspects of the internet to ever become fully severed without a huge breakdown in global trade into segemented markets -- which is pretty much prelude to global war.
Bad idea (Score:2, Insightful)
Segmenting the internet geographically would be a "Very Bad Idea".
Pretty much... everything (Score:3, Insightful)
A regionalized internet would seriously hurt the net's diversity. I can't imagine waiting for someone from Poland to re-invent every application that I use right now. What would happen is companies that could afford it, would find markets that can support licensed copies of the app and invest in those markets. So all the little, quarky, cool applications/rss feeds/sites we use every day would disappear outside of their home markets. And that'd suck for everybody, except the corporation that could afford to franchise.
University research (Score:2, Insightful)
Also, a lot of works are not translated and are relatively minor outside of a very narrow discipline, and so American bookstores (online or in the real world) do not carry them. Having access to international bookstores via the in
Language (Score:2)
As for communicating with people in other countries -- every day on IRC.
Re:Language (Score:2)
Would loose the community feeling (Score:2, Insightful)
There's a difference within this case of course for large countries like the US where there are lots of content is generated already but this will defenitely harm the many smaller countries. The
Sheesh (Score:5, Insightful)
More fool you, then. It's dubious enough relying on the US media to report US news, let alone world news.
Re:Sheesh (Score:3, Funny)
If you want someone on the radical left, there's always good ol' blood and guts Robert Fisk of the Independent [independent.co.uk], also out of the UK, although you have to pay to
Re:Sheesh (Score:2)
War ain't over yet.
Re:Sheesh (Score:3, Insightful)
From the way you talk, you sound pretty sour on life. It disturbs me because nowadays America is the country of sour, unhappy people. I see them all over the place.
Then I visit the Philippines, and everyone there has a smile and a laugh for me, even though most of them only make about 200 pesos a day [$4].
And I wonder
I hate to say it, but
but...but... (Score:2)
-Rick
I'm in Poland (Score:5, Insightful)
I know many people in Poland who are limited only to
BTW, what if Linus never left Finland and his ftp wouldn't be available across the ocean?
Ethnocentrism (Score:5, Insightful)
Let me sum up all those words in the article in two questions:
In other words: "We are not part of a global culture, we are Fortress America and have everything we could ever want right here."
The views expressed in the article are part of the reason why the rest of the world regards the average American as at best ignorant and naive, and at worst simply lame. I sincerely hope the writer was below the legal age to vote.
Why?? (Score:5, Insightful)
Maybe the next question can be: "What would we lose from getting rid of passports?"
Re:Why?? (Score:3, Insightful)
Now that is a good question!
A regionalized Internet is completely absurd and could only appeal to people who would like to destroy it.
But a world without passports is just like it has always been (except for the last ~ 100 years) and should be.
Re:Why?? (Score:2)
Don't ever want to travel overseas then? I think the OP was suggesting the US government stop issuing passports, thus preventing you from travelling outside the country.
Re:Why?? (Score:2)
Exactly (Score:3, Insightful)
I mean dear god we finally finally have everyone talking, the whole world, discussing issues, getting together and trying to understand the other's point of view, cross cultural debate and ideas being swapped, and now someone wants to take that away? The only reason I could possibly see for a balkanisation would be to control content or limit access to other cultures or ideas, probably for a higher profit. Now isn't that nicely fascist. Not to mention that ultimately someone would come up with a protocol t
Re:Why?? (Score:2)
We would lose the internet. (Score:2)
What would foreigners lose? (Score:5, Insightful)
I guess there's one thing I'd lose - the unconscious jingoism that makes people such as you forget that you address an international audience, even as you speculate on the effects that such a change would have on that very audience. I don't think I'd miss it much though.
Re:What would foreigners lose? (Score:3, Insightful)
I think of tiny niche interests (many software packages would be similar), and I am amazed at the effort many non-native English speakers provide content in English (as painful as it may be) to attract a wider audience than they might in say, Danish.
The benefit is clear: control. Everything else is clearly a looser.
You're missing the whole point! (Score:5, Insightful)
Peeling the onion another layer would help (Score:2)
I bet the computers on which the articles are created and the computers that serve the articles are all connected to different LANs, which are internetworked.
Hm. "Internetworked"...There's something familiar sounding about that.
I'd rather split the internet ... (Score:2)
I'd rather split the internet on the basis of ISPs that allow, or do not allow, spammers to be hosted. There would then be 2 internets, of which one (the clean one) would have rules against spam and any other forms of abuse (but not any rules against any particular content, per se, though local jurisdiction rules would still apply). Any ISPs that allows spammers and other abuses would then be forced to move their connection to the other one (the dirty one), which would, of course, affect all their custome
What the %^&* does that even mean? (Score:2)
But to answer some of your other questions, 99% of the sites
I care about use English, but many of those are in outher
countries, and loss of access or difficult access, or pay
per access would be a huge loss. SInce I also provide
information to people in other countries, as well as interact
with them on a couple of forums hoste din the USA, they would
lose as well.
The 1% that aren't in English are either in Spanish or they are
site
Absurd question, but let's answer anyway... (Score:5, Interesting)
Well, the Internet is what I would lose....
How often do you visit other countries' web sites?
How often do you e-mail people in other countries?
All the time.
Do you ever search in a language other than English,
My Google preferences are set to "Any language".
and if you do, how often does it turn up foreign vs domestic sites?
I usually search first in English, then in German, then in French. That is the order of quantity of existing pages in a language which I can read easily. But I may change the order depending on the subject. My main language is really French, but on most subjects for which I search the net, the results in French tend to be much poorer than in English or German.
I occasionally found relevant results in Spanish, Italian or Polish. While I don't speak these languages, for computer related stuff, I could sometimes decipher enough of what I found to make it useful.
What would foreigners lose by not being able to visit US-hosted sites, and how quickly would they be able to recreate what they lost?
It depends. If I had only acces to sites in my own country, the Internet would become pretty much useless. But if the world lost the US and vice-versa, I guess it would be the US which would lose the most. The rest of the world is much bigger after all.
News is where the biggest difference would be, and where the US would lose the most. Since US TV tends to be completely clueless about the rest of the world, all the news sources you have are papers and the Internet. How much of the news in the papers is actually gathered or researched in more depth through the Internet, I don't know.
But what a stupid idea to begin with anyway!...
Re:Absurd question, but let's answer anyway... (Score:2, Insightful)
I don't think you need to add that rest of the world part.
Re:Absurd question, but let's answer anyway... (Score:4, Insightful)
Still the most important thing is for work: I'm accessing web-site all over the world to get papers, either from University web-site or the web-sites of organizations like IEEE or ACM. Was the whole thing not put into place to help academic research? If the web would be really be split along political lines, research would be the first causality. Some of the largest online databases on genes or proteins are not in the US. Same goes for physics: the largest particle accelerator will not be in the US. Many academic projects are international, same goes for open-source projects.
Re:Absurd question, but let's answer anyway... (Score:2, Interesting)
If you took this away from me I'd have to find something else to do with my computer skills, such as writing worms, taking down networks, and breaking auth systems every way I can. I didn't go through 10 years of study to become this expert for nothing. And I
Oh internets, how do I love thee (Score:2, Insightful)
This is not even taking into account things such as online MMO's, entertainme
Bad news for international companies (Score:2)
Re:Bad news for international companies (Score:2)
It's already segmented (Score:4, Insightful)
The internet is nothing more than an interconnected series of independently operated networks--some privately run, some government run, but all separated physically, administratively, and financially.
They are interconnected via circuits that generally fall into one of two catagories, transit and peering. Transit circuits are your basic ISP/customer type, where one customer--who could be a smaller ISP--pays for connectivity to a service provider--who may, in turn, pay an even larger provider for their service. Peering circuits are commonly arranged between networks that exchange roughly equivalent amounts of traffic, where neither party bills the other for service. If billing is done on a peering arrangement, one network bills the other based specifically on the amount of imbalance in traffic between them, eg. the network sending more data gets paid.
The only technical aspects of the internet that are centralized administratively are domain naming and ip address allocation authority. This is a pain point for some non-US networks and governments, who want more influence over policy decisions. That's understandable. And if the world manages to wrest total control away from the US-based entities that have complete authority now, things will probably be okay, as long as there remains a single centralized and authoritative system for DNS and address allocations.
If alternate authorities start flourishing, the namespace will get unstable and corrupt, and Bad Things (c) will happen. For example, if your naming authority and my naming authority separately assign "slashdot.org" to different sites, you may get a useful tech news site...and I may get this one.
My comments (Score:2)
The web never was American.... (Score:4, Insightful)
I search in German as well as English
I buy books, CDs and videos over the web from Australia, the US, Britain and Germany.
I download software from all over the world (ALSA is Czech, isn't it - and aalib?).
I read English-language pages in lots of countries: e.g. Russia, China, Japan, India, Spain, Indonesia, Middle-east
I used the internet to book accommodation in New Zealand - and buy my airline tickets there. Picked them up in Australia. I would do the same if travelling to Europe or America.
When I go onto the web, I don't think of myself as being "in Australia", but as being in an international forum. Wish more people would think that way.
My livelihood, family and friends (Score:2)
If we lose the w
Not everyone lives in the US (Score:2)
As someone who does not reside in the USA and works for a global company I communicate online with people from other countries on a daily basis.
I also have numerous friends who travel and communicate via email or blogs or other web based technologies.
Foreigner... (Score:2, Interesting)
This
it's an oxymoron (Score:2)
Why don't we just take another step backwards and just communicate with smoke signals?
More often than I can count (Score:2)
Web sites: online Japanese sword shops - more than a few have english versions of their pages, and often they can be useful even without it. Tourist info, local info about places you migh
*facedesk* (Score:2)
First thing I can think of ... (Score:2)
Google news has completely changed the way I get world news. I can see the same story covered from the perspective of lots of different countries/regions, and try to decide what the issue actually means. Rather than having your news filtered through your nation's lens, it's refreshing to be able to see how France, China, the Aussies, and e
We would lose just about everything (Score:2)
awful for at least 2 reasons (Score:2)
1. I do a little consulting work for people in other countries (Europe and one company in India)
2. I like the variety of news from international news sources
Sometimes I wonder if the "owners" want to screw stuff up in the U.S. A world-wide internet is necessary for business. Add to this what seems like a "dumbing down" of our school systems in the last few decades, and I have to ask, what gives?
On a tangent: the thing with software patents is similar: almost all money spent on softw
World news in the USA (Score:2, Informative)
Read [bbc.co.uk] and see what you're missing.
"Regionalized" != "Airgapped" (Score:2)
In general, the
you'd lose regardless (Score:2)
These countries are smart; they know that there isn't a chance in hell that the rest of the world is going to learn
Record (Score:2)
Depends on Where You Live (Score:2)
Perhaps the question isn't, "should the internet be regionalized?" but "should the US segregate its internet from the rest of the world?" It's an insanely stupid
Some People Apparently Think We Already Have One (Score:2)
Promote war (Score:2)
I am sure there are many people who may not see this connection. However, we must consider the FUD that propaganda departments spew. In fact the very existance of propaganda departments illustrates the idea.
One of the biggest benefits the internet confers upon people is the ability for everyone to freely and inex
Re:OK, what's your point? (Score:2)
You don't need to know who wants to region-code IP packets. These aren't the droids you're looking for. You can go about your business. Move along.
Re:Rediculous,Borderline nationalism (Score:2)
I've never heard that listed as a definition for Internet. The term was coined I believe by Vint Cerf, and he was using it to refer to a network of networks: internetworking.
It's inter-network as opposed to intra-network. The prefix "inter" has nothing to do with nations.
Re:You don't know what you got till it's gone (Score:3, Insightful)
No honestly, right now it is fairly hard to censor the internet, to squash voices, or to enforce any national law. If the internet was fragmented it would allow nations much more ability to mandate what is and isn't allowed in their country, (and possibly in and out of the country as well).
Isn't that what everyone is upset about with Google, Yahoo, and China? I'm not intending to sell tin-foil hats, but this seems to be a bureaucratic wet-d | https://slashdot.org/story/06/03/27/1347258/what-would-we-lose-from-a-regionalized-internet | CC-MAIN-2017-30 | refinedweb | 4,454 | 62.07 |
This section describes the known issues in this update.)
Oracle ASM Cluster File System (ACFS) is currently not supported for use with UEK R3. (Bug ID 16318126)
On some systems you might see ACPI-related error messages in
dmesgsimilar)
The following messages indicate that the BIOS does not present a suitable interface, such as
_PSSor
_PPC, that the
acpi-cpufreqmodule requires:
kernel: powernow-k8: this CPU is not supported anymore, using acpi-cpufreq instead. modprobe: FATAL: Error inserting acpi_cpufreq
There is no known workaround for this error. (Bug ID 17034535). (Bug ID 16946255)
The usage information for mkfs.btrfs reports
raid5and
raid6as possible profiles for both data and metadata. However, the kernel does not support these features and cannot mount file systems that usedirectoryto the kernel boot parameters, or disable enforcing of the SELinux policy by adding
enforcing=0. (Bug ID 13806043)
Commands such as du can show inconsistent results for file sizes in a btrfs file system when the number of bytes that is under delayed allocation is changing. (Bug ID 13096268). Although the limitation of the number of hard links in a single directory has been increased to 65535, the version of mkfs.btrfs that is provided in the
btrfs-progspackage does not yet support the compatibility flag for this feature. (Bug ID 16285431). (Bug ID 16569350)
When you overwrite data in a file, starting somewhere in the middle of the file, the overwritten space is counted twice in the space usage numbers that btrfs qgroup show displays. (Bug ID 16609467)
If you run btrfsck --init-csum-tree on a file system and then run a simple btrfsck on the same file system, the command displays a Backref mismatch error that was not previously present. (Bug ID 16972799)
Btrfs tracks the devices on which you create btrfs file systems. If you subsequently reuse these devices in a file system other than btrfs, you might see error messages such as the following when performing a device scan or creating a RAID-1 file system, for example:
ERROR: device scan failed '/dev/cciss/c0d0p1' - Invalid argument
You can safely ignore these errors. (Bug ID 17087097)
If you use the -s option to specify a sector size to mkfs.btrfs that is different from the page size, the created file system cannot be mounted. By default, the sector size is set to be the same as the page size. (Bug ID 17087232)
In some cases, it is possible to run the btrfs-convert command on a mounted file system. This may result in unexpected behaviour and can possibly cause a kernel panic. Make sure to unmount a file system before converting it to Btrfs. (Bug ID 18061751)
The btrfs subvolume delete command may result in a "
Directory not empty" error. This error message is incorrect. The actual reason that the subvolume cannot be deleted is that the subvolume is configured as the default subvolume. The default subvolume is the subvolume that is mounted when no subvolume is specified with the mount command. Before you can delete the subvolume, you need to configure a different default subvolume using the btrfs subvolume set-default command. (Bug ID 17661944)
When running Oracle Linux 6 with UEK R)
In UEK R2, the
dm-nfs module provided the
ability to create a loopback device for a mounted NFS file or
file system. For example, the feature allowed you to create
the shared storage for an Oracle 3 VM cluster on an NFS file
system. The
dm-nfs module provided direct
I/O to the server and bypassed the
loop
driver to avoid an additional level of page caching. The
dm-nfs module is not provided with UEK R3.
The
loop driver can now provide the same
I/O functionality as
dm-nfs by extending
the AIO interface to perform direct I/O. To create the
loopback device, use the losetup command
instead of dmsetup.
You can safely ignore the following message that might be
displayed in
syslog or
dmesg:
ERST: Failed to get Error Log Address Range.
The message indicates that the system BIOS does not support an Error Record Serialization Table (ERST). (Bug ID 17034576)
The inline data feature that allows the data of small files to be stored inside their inodes is not yet available. The -O inline_data option to the mkfs.ext4 and tune2fs commands is not supported. (Bug ID 17210654)
You can safely ignore the following firmware warning message that might be displayed on some Sun hardware:
[Firmware Warn]: GHES: Poll interval is 0 for generic hardware error source: 1, disabled.
(Bug ID 13696512))
The Unbreakable Enterprise Kernel uses the
deadline scheduler as the default I/O
scheduler. For the Red Hat Compatible Kernel, the default I/O
scheduler is the
cfq scheduler.
You can safely ignore messages such as
ioapic: probe
of 0000:00:05.4 failed with error -22. Such messages
are the result of the
ioapic driver
attempting to re-register I/O APIC PCI devices that were
already registered at boot time. (Bug ID 17034993) Internet Protocol over InfiniBand (IPoIB) driver supports
the use of either connected mode or datagram mode with an
interface, where datagram mode is the default mode. Changing
the mode of an InfiniBand interface by echoing either
connected or
datagram to
/sys/class/net/ib
is not supported. It is also not possible to change the mode
of an InfiniBand interface while it is enabled.
N/mode
To change the IPoIB mode of an InfiniBand interface:
Edit the
/etc/sysconfig/network-scripts/ifcfg-ibconfiguration file, where
N
Nis the number of the interface:
Note
To configure connected mode, specify
CONNECTED_MODE=yesin the file.
To configure datagram mode, either specify
CONNECTED_MODE=noin the file or do not specify this setting at all (datagram mode is enabled by default).
Before saving your changes, make sure that you have not specified more than one setting for
CONNECTED_MODEin the file.
To enable the specified mode on the interface, use the following commands to take down the interface and bring it back up:
#
ifdown ib#
N
ifup ib
N
(Bug ID 17479833).
To disable SELinux on the host:
Edit the configuration file for SELinux,
/etc/selinux/configand set the value of the
SELINUXdirective to
disabled.
Shut down and reboot the host system.
The
rootuser in a container can affect the configuration of the host system by setting some
/procentries. (Bug ID 17190287)
Using yum to update packages inside the container that use
initscripts can undo changes made by the Oracle template.
Migrating live containers (lxc-checkpoint) is not yet supported.
Oracle Database is not yet supported for use with Linux Containers. The following information is intended for those who want to experiment with such a configuration.
The following
/procparameter))
The following message might appear in
dmesg
or
/var/log/messages:
WARNING! power/level is deprecated; use power/control instead.
The USB subsystem in UEK Rand set the entry
MLX4_LOAD=yesin this file.
To make the change take effect, restart the RDMA service or reboot the system.
For the Unbreakable Enterprise Kernel,
kernel.sched_compat_yield=1 is set by
default. For the Red Hat Compatible Kernel,
kernel.sched_compat_yield=0 is used by
default.
Starting with UEK R2, the device mapper has had the capability to check whether the underlying storage device has advertised the need to flush the data that resides in the device's cache to its non-volatile storage. For a data integrity operation, such as fsync and sync, the operation will now need to include the time to flush the device's cache (if it is advertised). Such an operation will appear to be slower when compared to a previous older kernel, however this is the correct behavior. (Bug ID 17823743)
When upgrading or installing the UEK R)
This release removes the Transparent Huge Pages (THP) feature. Following extensive benchmarking and testing, Oracle found that THP caused a performance degradation of between 5 and 10% for some workloads. UEK release, 16823432)
The kernel functionality (
CONFIG_USER_NS)
that allows unprivileged processes to create namespaces for
users inside which they have root privileges is not currently
implemented because of a clash with the implementation of XFS.
This functionality is primarily intended for use with Linux
Containers. As a result, the
lxc-checkconfig command displays
User namespace: missing. (Bug ID 16656850)
When booting UEK R3 as a PVHVM guest, you can safely ignore the following kernel message:
register_vcpu_info failed: err=-38
(Bug ID 13713774)
Under Oracle VM Server 3.1.1, migrating a PVHVM guest that is running the UEK R3 kernel causes a disparity between the date and time as displayed by date and hwclock. The workaround post migration is either to run the command hwclock --hctosys on the guest or to reboot the guest. (Bug ID 16861041))
The system reports a message similar to the following if there is a problem loading an in-kernel X.509 module verification certificate at boot time:
Loading module verification certificates X.509: Cert 0c21da3d73dcdbaffc799e3d26f3c846a3afdc43 is not yet valid MODSIGN: Problem loading in-kernel X.509 certificate (-129)
This error occurs because the hardware clock lags behind the system time as shown by hwclock, for example:
#
hwclockTue 20 Aug 2013 01:41:40 PM EDT -0.767004 seconds
The solution is to set the hardware clock from the system time by running the following command:
#
hwclock --systohc
After correcting the hardware clock, no error should be seen at boot time, for example:
Loading module verification certificates MODSIGN: Loaded cert 'Slarti: Josteldalsbreen signing key: 0c21da3d73dcdbaffc799e3d26f3c846a3afdc43'
(Bug ID 17346862) | http://docs.oracle.com/cd/E37670_01/E51472/html/uek3_known_issues.html | CC-MAIN-2017-17 | refinedweb | 1,583 | 53 |
Apache CXF 2.1.1 Release Notes
Overview
Apache CXF 2.1.1 delivers the latest set of patches and bug fixes for Apache
CXF. This release fixes 74 JIRA issues that have been reported by users..
Bouncy Castle/JCE and Xalan.
You also need to have xalan available as the xmlsec code has direct
dependencies on xalan. However, all recent versions of xalan (2.5.0 - 2.7.1)
have bugs in them that prevent the JAX-WS TCK from passing if it's on the
classpath. Specifically, reading an EndpointReference via
EndpointReference.readFrom(Source) may not result in an EndpointReference that
is completely usable as namespace declarations may be lost.
The latest version of the WSS4J library that is used to implement WS-Security
requires the opensaml jar to be on the classpath. This is different than previous
versions that only required it if doing SAML assertions. When upgrading
to CXF 2.1.1, you will need to add the opensaml jar to your application.
Building the Samples: | https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=88821 | CC-MAIN-2019-39 | refinedweb | 170 | 69.48 |
When I was learning programming, back in the days of Turbo Pascal, I managed to list files in directory using
Every use case above has a unique set of challenges. For example we don't want to build a list of all files because it will take a significant amount of time and memory before we can start processing it. We would like to process files as they are discovered and lazily - by pipe-lining computation (but without clumsy visitor pattern). Also we want to short-circuit searching to avoid unnecessary I/O. Luckily in Java 8 some of these issues can be addressed with streams:
Code above is short, sweet and... doesn't compile. These pesky checked exceptions again. Here is a fixed code, wrapping checked exceptions for sanity:
FindFirst,
FindNextand
FindClosefunctions. First I came up with a procedure printing contents of a given directory. You can imagine how proud I was to discover I can actually call that procedure from itself to traverse file system recursively. Well, I didn't know the term recursion back then, but it worked. Similar code in Java would look something like this:
public void printFilesRecursively(final File folder) { for (final File entry : listFilesIn(folder)) { if (entry.isDirectory()) { printFilesRecursively(entry); } else { System.out.println(entry.getAbsolutePath()); } } } private File[] listFilesIn(File folder) { final File[] files = folder.listFiles(); return files != null ? files : new File[]{}; }Didn't know
File.listFiles()can return
null, did ya? That's how it signals I/O errors, like if
IOExceptionnever existed. But that's not the point.
System.out.println()is rarely what we need, thus this method is neither reusable nor composable. It is probably the best counterexample of Open/Closed principle. I can imagine several use cases for recursive traversal of file system:
- Getting a complete list of all files for display purposes
- Looking for all files matching given pattern/property (also check out
File.list(FilenameFilter))
- Searching for one particular file
- Processing every single file, e.g. sending it over network
final File home = new File(FileUtils.getUserDirectoryPath()); final Stream<Path> files = Files.list(home.toPath()); files.forEach(System.out::println);Remember that
Files.list(Path)(new in Java 8) does not look into subdirectories - we'll fix that later. The most important lesson here is:
Files.list()returns a
Stream<Path>- a value that we can pass around, compose, map, filter, etc. It's extremely flexible, e.g. it's fairly simple to count how many files I have in a directory per extension:
import org.apache.commons.io.FilenameUtils; //... final File home = new File(FileUtils.getUserDirectoryPath()); final Stream<Path> files = Files.list(home.toPath()); final Map<String, List<Path>> byExtension = files .filter(path -> !path.toFile().isDirectory()) .collect(groupingBy(path -> getExt(path))); byExtension. forEach((extension, matchingFiles) -> System.out.println( extension + "\t" + matchingFiles.size())); //... private String getExt(Path path) { return FilenameUtils.getExtension(path.toString()).toLowerCase(); }OK, just another API, you might say. But it becomes really interesting once we need to go deeper, recursively traversing subdirectories. One amazing feature of streams is that you can combine them with each other in various ways. Old Scala saying "flatMap that shit" is applicable here as well, check out this recursive Java 8 code:
//WARNING: doesn't compile, yet: private static Stream<Path> filesInDir(Path dir) { return Files.list(dir) .flatMap(path -> path.toFile().isDirectory() ? filesInDir(path) : singletonList(path).stream()); }
Stream<Path>lazily produced by
filesInDir()contains all files within directory including subdirectories. You can use it as any other stream by calling
map(),
filter(),
anyMatch(),
findFirst(), etc. But how does it really work?
flatMap()is similar to
map()but while
map()is a straightforward 1:1 transformation,
flatMap()allows replacing single entry in input
Streamwith multiple entries. If we had used
map(), we would have end up with
Stream<Stream<Path>>(or maybe
Stream<List<Path>>). But
flatMap()flattens this structure, in a way exploding inner entries. Let's see a simple example. Imagine
Files.list()returned two files and one directory. For files
flatMap()receives a one-element stream with that file. We can't simply return that file, we have to wrap it, but essentially this is no-operation. It gets way more interesting for a directory. In that case we call
filesInDir()recursively. As a result we get a stream of contents of that directory, which we inject into our outer stream.
Code above is short, sweet and... doesn't compile. These pesky checked exceptions again. Here is a fixed code, wrapping checked exceptions for sanity:
public static Stream<Path> filesInDir(Path dir) { return listFiles(dir) .flatMap(path -> path.toFile().isDirectory() ? filesInDir(path) : singletonList(path).stream()); } private static Stream<Path> listFiles(Path dir) { try { return Files.list(dir); } catch (IOException e) { throw Throwables.propagate(e); } }Unfortunately this quite elegant code is not lazy enough.
flatMap()evaluates eagerly, thus it always traverses all subdirectories, even if we barely ask for first file. You can try with my tiny
LazySeqlibrary that tries to provide even lazier abstraction, similar to streams in Scala or
lazy-seqin Clojure. But even standard JDK 8 solution might be really helpful and simplify your code significantly. | https://www.nurkiewicz.com/2014/07/turning-recursive-file-system-traversal.html | CC-MAIN-2019-39 | refinedweb | 853 | 51.34 |
7-segment displays, the kind found on old digital alarm clocks, can be great for Raspberry Pi projects, including those you make with Raspberry Pi Pico. You can use a 7-segment display to keep score in a game, show sensor data like temperature or distance numbers or to keep track of time. You can even show some letters.
There are many kinds of 7-segment displays on the market and they vary not only based on the number of digits and the color, but also on the controller board or lack thereof. Some cheap 7-segment displays have no controller and use separate pins for every single light. When you consider that each digit has seven different lights (hence the name “7-segment display”), that’s a lot of pins.
However, better 7-segment displays have controller boards which employ an I2C connection that uses just four pins, powered by a TM1637 controller board. Below, we’ll show you how to use one of these TM1637-powered 7-segment displays with a Raspberry Pi Pico.
What You’ll Need
- 7-segment display. There are so many models, but we used this one.
- Raspberry Pi Pico with soldered pin headers and MicroPython.
- Four female-to-female jumper cables
If you haven’t used your Pico before, see our article on how to set up a Raspberry Pi Pico and how to solder pins to your Raspberry Pico.
How to Connect a 7-Segment Display to Raspberry Pi Pico
The 7-segment display has four pins: CLK, DIO, GND and VCC. If you use female-to-female jumper wires, you don’t need a breadboard to do the connections.
Connect the following pins from the 7-segment display to the PIco.
- VCC pin to 3V3 on the Pico (physical pin 36, the fifth on the right side).
- GND pin to GND on the Pico (physical pin 34, the third on the right side).
- CLK pin to GP16 on the Pico (last pin on the right side).
- DIO pin to GP17 on the Pico (next-to-last pin on the right side).
You could choose to connect the CLK and DIO pins to any two GPIO pins on the Pico which support I2C SCL and SDA respectively and you can connect the GND pin to any of the Pico’s 8 GND pins. See the Raspberry Pi Pico pinout for details.
How to Code a 7-Segment Display in MicroPython
We’re going to rely heavily on the excellent TM1637 MicroPython library from Mike Causer and create a script which shows a variety of display options, which you can use in your own projects later on.
5. Download the tm1637.py file from Mike Causer’s TM1637 github project. You don’t need the other files.
6. Copy tm1637.py to your Pico’s root directory. Since the Pico with MicroPython doesn’t appear as a drive letter, the easiest way to do this is to open tm1637.py in Thonny or the IDE or your choice and save it from there.
7. Create a new MicroPython script in Thonny or the MicroPython IDE of your choice.
8. Import the necessary libraries.
import tm1637 from machine import Pin from utime import sleep
We will use the utime library to put a one-second “sleep” delay between each function so you have time to watch them on the display.
9. Create an instance of the tm1637.TM1637 object called “mydisplay” and enter the correct pin numbers for the CLK and DIO pins as parameters.
mydisplay = tm1637.TM1637(clk=Pin(16), dio=Pin(17))
10. Use the “show” method to display any four characters. These can be letters or numbers, but note that many letters, W for example, will look awkward. If you enter more than four characters, only the first four will be shown. Be sure to put the parameter string in quotes.
mydisplay.show(“Pico”) sleep(1)
11. Blank the screen by using “show” with four blank spaces (assuming you have four digits on your screen).
mydisplay.show(“ “) sleep(1)
Note that if you don’t blank the display, it will remain on when your program is finished executing. You don’t need to blank the display when changing it, but if you use another show command with less than the maximum number of characters, any characters you don’t replace will stay on the screen. For example, if you do show(“halo”) and then show(“20”), the screen will read 20lo.
12. Use the “number” method to show an integer. Do not put quotes around the parameter. You can display a negative or positive number, but if it’s a negative number, it has to reserve one character for the minus sign. Note that, if you enter a larger number than the available number of digits (ex: entering 12345 on four-digit display), the screen will read “9999” or “-999” for negative numbers.
mydisplay.number(-123) sleep(1)
Use the “numbers” method to show a time with the color visible. Enter two, two-digit numbers as parameters and the colon, provided your screen has one, will show in between them. This example will appear as 12:59.
13. Considering that you can use the “show” method to show numbers or letters, you might wonder why you’d want to employ the number method instead. One reason is that you don’t need to convert integers to strings and another is that the screen will only use the necessary amount of digits so you don’t need to enter blank spaces to align your number to the right.
mydisplay.numbers(12,59) sleep(1)
14. Adjust the brightness using the brightness method. You can enter a number that ranges from 0 (lowest) to 7 (highest) as the parameter.
#adjust the brightness to make it loewr mydisplay.brightness(0) sleep(1)
15. Use the “scroll” method to display scrolling text. Enter a string (in quotes) as the first parameter and add, “delay=” and a number of milliseconds to control the speed of the scroll. If you skip the delay parameter, it will default to 250ms.
mydisplay.scroll("Hello World 123", delay=200) sleep(1)
16. Use the “temperature” method to show a temperature in Celsius. This method adds the degree symbol and letter C after your digits. You enter either a one or two digit integer as the temperature and you can do negative temperatures but these can only be one digit.
mydisplay.temperature(99) sleep(1)
17. Blank the screen again so it doesn’t stay lit when the program is over.
mydisplay.show(“ “)
Here’s the final code
import tm1637 from machine import Pin from utime import sleep mydisplay = tm1637.TM1637(clk=Pin(16), dio=Pin(17)) # Show a word mydisplay.show("Pico") sleep(1) #blank the screen mydisplay.show(" ") sleep(1) #show numbers mydisplay.number(-123) sleep(1) #show a time with colon mydisplay.numbers(12,59) sleep(1) #adjust the brightness to make it loewr mydisplay.brightness(0) sleep(1) #show scrolling text mydisplay.scroll("Hello World 123", delay=200) sleep(1) #show temperature mydisplay.temperature(99) sleep(1) #blank the screen again mydisplay.show(" ")
There are other methods that Causer documents on his github page, including one that will convert numbers to hexadecimal format for you or take hex input. However, these are the main methods we think most people will need to get use with a 7-segment display and Raspberry Pi Pico. | https://www.tomshardware.com/uk/how-to/raspberry-pi-pico-7-segment-display | CC-MAIN-2021-43 | refinedweb | 1,246 | 73.37 |
Looks interesting (haven't read it yet as I'm at work, but this place needs a link ;o)
It's not this, and comes from here.
Posted to functional by andrew cooke on 2/25/04; 2:26:03 PM
The whole point of this paper is that reflect and reify somehow improve the encapsulation of monad operations. These they define as macros:
reflect
reify
(define-syntax reify
(syntax-rules ()
((reify (?var ?producer1)
?producer2)
(bind (?var (unit ?producer1))
?producer2))))
(define-syntax reflect
(syntax-rules ()
((reflect (?var) ?expression)
(mult (return (lambda (?var) ?expression))))))
(define-syntax reflect
(syntax-rules ()
((reflect (?var) ?expression)
(mult (return (lambda (?var) ?expression))))))
The thing is that, because of the monad laws, one has: (bind (V (unit E1)) E2) = (let ((V E1)) E2) and (mult (return E)) = E. Consequently, reify is essentially sugar for let, and reflect is sugar for lambda.
(bind (V (unit E1)) E2) = (let ((V E1)) E2)
(mult (return E)) = E
let
lambda
"Where's the beef?"
Filinski, in Representing Monads, defines reify and reflect by the
following rules (quoting Moggi):
For any expression E of type Ta, reflect(E) is a computation that
returns the value of type a and does the effect described by the
monad constructor T. For any general computation E of type a, reify(E)
is a "pure" value of type Ta.
a
reify(reflect(V)) === V
reflect(reify(E)) === E
Thus, according to Filinski, both reify and reflect apply to
expressions. In the Sobel et al. paper, reify and reflect are
binding forms. Furthermore, according to Filinski, reify and reflect
must be inverses. In the Sobel et al. paper, reify and reflect don't
even compose! One can't avoid the impression that reify and reflect in
the paper are mis-named: the reflect form in the paper yields a
lambda-expression -- a pure value. That's the job of reify!
In Scheme, the examples of reify and reflect are delay and force.
I contend that it is more insightful to view the running example of
the paper (and other examples in Section 2.2) as combinator parsing.
We have simple parsers (digit, empty) from which we can build more
complex parsers with sequencing and alteration combinators. The fact
that sequencing looks like 'bind' is just a coincidence (Monad is a
sufficiently general concept, so appears in many places. It is not
always insightful). Combinators neatly hide the plumbing details --
the input and the output streams. If we consider the parsing problem
in the paper to be an instance of combinator parsing, the issue of
monadic grammar disappears. We simply have a set of combinators, which
may combine parsing expressions of particular types. In a typeful
language, the type system reinforces the conventions. Instead of
monad laws, we have combinator laws, which are generally richer.
The paper will confuse the reader about monadic reflection and reification.
The reader was already confused about monadic reflection and reification :)
I'm not so sure that Sobel et. al. got it wrong. If you go back to Filinski, you'll see
Then reflect(E) (writing "reflect" for "mu") expresses the value of E:alpha + exn as a computation: we get an exception raising construct by raise E === reflect(inr E)
His type rule is:
Gamma |- E:T(alpha)
----------------------
Gamma |- reflect(E):alpha
Gamma |- reflect(E):alpha
But he's really using T(alpha) here as an abbreviation for alpha + exn (notice how his example is reflect(inr E), and we don't expect to be able to explicitly construct computations in the monad using something so mundane as inr). And the result type of reflect(E) is "a computation", so it's surely of a monadic type. Like in Moggi's metalanguage, all the types tau on the right hand side of the turnstile will be interpreted as T(tau).
In fact, if you go back to Moggi, you'll see that the semantics of reflect is g;mu_[alpha], where mu is the multiplication of the monad. Then, mu_[alpha] is an arrow from T(T(alpha)) -> T(alpha), so clearly no matter what g it's composed with, it will yield a T(alpha) in the semantics.
And likewise for reify ([.]), where Filinski does an explicit case on the value of a reified expression. We don't expect case to be able to see inside values of monadic type---they type T(alpha) in the rule is an abbreviation for alpha + exn.
Sobel et. al. are trying to say that we gain something by being explicit about the distinction between the left and right hand sides of
T(alpha) = alpha + exn
and using reflect to go from right to left and reify to go from left to right (even in combinators that are "in the know" about the monad, like orelse). Namely, what we gain is the ability to implement T(alpha) as something other than alpha + exn.
I'm pretty sure that you can get back the (sort of) inverse-ness of reify and reflect using the definitions from the Sobel paper if you write:
(reify (x (reflect (y) E)) x)
===> (lambda (y) E) as a parser value
(reify (x E) (reflect (y) (x y)))
===> (lambda (y) (E y)) as a parser value
(reify (x E) (reflect (y) (x y)))
===> (lambda (y) (E y)) as a parser value
Note that reflect has an extra lambda in its expansion (that could have been, but wasn't, written by the programmer), because otherwise "lambda" would have to be part of the syntax of reflect (for this monad).
In the Sobel et al. paper, reify and reflect are binding forms.
Weren't they in the Moggi paper too, where terms in the meta language and programs in the programming language all had a single free variable?
Frank Atanassow is right, I think. (The first definition of) reify is just a let that blesses the bound variable as something that can be applied to a token stream yielding a pair of new stream and either result or failure. And reflect is just sugar for a lambda, but they need to reflect macro form as a hook to add extra arguments later in the paper.
Later, they will eliminate a bunch of closure creation. And then they will implement reflect as a macro generating macro, and reify as a let (becuase the token stream is always available). But, (they claim that) they couldn't have done this without reify and reflect.
Anyway, what I think about this paper is that it is an interesting way to "discover" monads. Just write a bunch of functional programs that contain an encoding of imperative effects, and abstract the common patterns out.
Ah, that explains a few things. It looks like Sobel's page has not been updated since Sep. 2002, and probably not for a while before that. CiteSeer says his last publication was in 1999.
Kevin: Sobel et. al. are trying to say that we gain something by being explicit about the distinction between the left and right hand sides of T(alpha) = alpha + exn
That is the only sense I could make out of it too. But it's a trivial observation, and has nothing to do with monads or reflection. In Haskell, it just amounts to an admonition to make T (more) abstract:
T
data T alpha = T (Either alpha Exn)
which is standard practice anyway. There is not much point in defining two new operators for this, since they both factor through the data constructor T. | http://lambda-the-ultimate.org/classic/message11342.html | crawl-002 | refinedweb | 1,253 | 61.46 |
What is Redux and How Do I Learn it?
If you’ve spent any time working on JavaScript apps, especially in component-driven libraries like React, you have come across State. It is an essential part of React and is absolutely vital to know. You may be less familiar with the state-management tool Redux. Redux exists to make state easier to manipulate and use. This article will briefly explain the very basics of what state is and give some very useful suggestions for ways to learn about Redux and build on that base knowledge.
State is ‘data over time’. It is the status of things as they change and receive new information. State is simply: stored information that can be edited like any other variable. State is not in of itself a complicated concept to grasp or understand, or even especially difficult to implement into apps.
The React useState Hook makes it easy to edit and use State like so:
import React { useState } from ‘react’;const [currentState, setCurrentState] = useState('');
Once we import state in the first line, we can set it up in the second. ‘currentState’ simply declares the variable of what we want to label our state, while setCurrentState declares the setter method. Whatever you pass into the useState parenthesis will be the default value. Here we have set it as a blank string but we could easily have set it to null, 0 or false if we wanted our state to use integers, boolean values etc.
So far so simple. The issue with state in React, comes when we are trying to use state across different components. As state is a locally stored variable, not every component will have access to it unless you pass it down.
<NewComponent currentState={currentState} setCurrentState={setCurrentState} />
This works fine and well for most applications but can become unwieldy and complicated when you are dealing with large applications with lots of different child components each needing access to different states. The solution to apps like those is something called Redux.
Redux is a state-management tool for libraries like React and Angular that allow you to keep a store of all your state which can be accessed and edited by any component whenever necessary without needing to be passed down or up. It is a fantastic tool and can be a vital weapon in your JavaScript arsenal.
However, it is notoriously difficult to use and integrate into your app. But, intrepid coder, you will find below the links that will enable you to learn and master Redux and successfully store state at will!
The first and most important link before progressing is this article from the co-creator of Redux, Dan Abraham that explains what Redux and asks whether it is even necessary for you to use at all.
You Might Not Need Redux
People often choose Redux before they need it. “What if our app doesn’t scale without it?” Later, developers frown at…
medium.com
Once you have decided that yes, you need Redux, or no, but I want to learn it anyway. In my opinion the best place to start is with this excellent Scrimba series. It will teach you the process by showing you how to set it up and get things working while also giving a high-level overview of the concepts. The only downside is that Redux has changed significantly in the past few years and this perhaps dwells too long on past versions.
Once you have started working through that, I fully recommend reading the docs in full. The tutorial is good, if a little dense but will ensure you have a thorough understanding of everything.
Redux - A predictable state container for JavaScript apps. | Redux
Your Docusaurus site did not load properly. A very common reason is a wrong site baseUrl configuration. Current…
redux.js.org
Last but not least, I highly recommend Valentino Gagliardo’s thorough website and tutorial devoted to learning Redux. The videos are very informative and is a great way to round out the learning.
React Redux Tutorial for Beginners: The Complete Guide (2020)
When I first started learning Redux I wish I had some "Redux for dummies". I felt dumb because I couldn't wrap my head…
Armed with this knowledge from these resources you will be an expert in Redux in no time! | https://admshng.medium.com/what-is-redux-and-how-do-i-learn-it-464fae03841a | CC-MAIN-2022-40 | refinedweb | 724 | 61.97 |
Front end little witch 2022-06-23 18:36:01 阅读数:724
*
When we think 「 Impossible is possible 」 When , that 「 The impossible becomes possible 」, It will really happen -- Pygmalion effect*
Hello everyone , I am a 「 Seven eight nine 」.
today , And once again. Opened up a new field --「TypeScript Practical series 」.
This is the
These modules , New knowledge system .
This series is mainly aimed at
React + TS Of . And about the
TS The advantages and benefits of , I'm not going to repeat it , It's been said to suck .
「last but not least」, This series of articles is
TS + React Application articles for , For some basic, such as
TS All kinds of data types , Don't make too many introductions . There are many articles on the Internet .
Time will not wait for me , We began to .
*
**
TypeScriptSimple concept
Generic The concept and use of stay
ReactUse generics to define
hookand
props
TypeScriptWhat is it?
TypeScriptWhat is it?
*
**
TypeScriptyes ⼀ Species by Microsoft Open source programming language ⾔. It is
JavaScriptOf ⼀ individual 「 Superset 」, Essentially to
JSAdded optional 「 Static type 」 and 「 Class based ⾯ Programming objects 」.
TypeScript Provide up-to-date and evolving
JavaScript characteristic , Including those who come ⾃ 2015 Year of ECMAScript And features in future proposals ,⽐ Such as asynchronous function and
Decorators, To help build ⽴ Robust components .
About
ES and
JS Direct relation ,
*
stay 「 In the browser environment 」,*
JS = ECMAScript + DOM + BOM.
For more information, please refer to Previous post , We don't distinguish much here ,
ES and
JS The relationship of .
TypeScriptAnd
JavaScriptThe difference between
TypeScript
command ⾏ Of
TypeScript The compiler can make ⽤
npm Package manager to install .
npm install -g typescript
tsc -v
Version 4.9.x // TS The latest version
tsc helloworld.ts
helloworld.ts => helloworld.js
In the picture above, it contains 3 individual ts ⽂ Pieces of :
a.ts、
b.ts and
c.ts. these ⽂ Pieces will be
TypeScript compiler , Compile to... According to the configured compilation options 3 individual js ⽂ Pieces of , namely
a.js、
b.js and
c.js. about ⼤ Most make ⽤
TypeScript Developed Web term ⽬, We will also compile ⽣ Yes js ⽂ Piece in ⾏「 Packaging processing 」, And then in ⾏ Deploy .
TypeScript There are mainly 3 Big feature :
TypeScriptCan compile pure 、 concise
JavaScriptCode , And it can run on any browser 、
Node.jsEnvironment and any support
ECMAScript 3( Or later ) Of JavaScript In the engine .
JavaScriptDevelopers are developing
JavaScriptThe application uses efficient development tools and common operations such as static checking and code refactoring .
TypeScriptProvide up-to-date and evolving
JavaScriptcharacteristic , Including those from 2015 Year of ECMAScript And features in future proposals , For example, asynchronous function and Decorators, To help build robust components .
Generic yes
TS An important part of , This article will briefly introduce its concept and introduce it in
React Application in .
*
Generics are 「 Type parameterization 」: That is to say, the original specific type is introduced into ⾏ A parameterized*
Software ⼯ cheng in , We don't just create ⼀ To 、 Well defined
API, Also consider 「 Heavyweight ⽤ sex 」. Components can not only ⽀ Hold the current data type , At the same time ⽀ Hold on to future data types , This is creating ⼤ Type system provides you with ⼗ Flexible functions .
In image
C++/
Java/
Rust Such a tradition
OOP language ⾔ in , Sure 「 send ⽤ Generics to create repeatable ⽤ The components of ,⼀ Components can ⽀ Hold multiple types of data 」. such ⽤ You can With ⾃⼰ The data type of ⽤ Components .
*
Design generic 「 The key ⽬ Of 」 Is in 「 Provide meaningful constraints between members 」, These members can be : Instance members of a class 、 Class ⽅ Law 、 Function parameters and function return values .*
for instance , Will be standard
TypeScript type And
JavaScript object Compare .
// JavaScript object
const user = {
name: '789',
status: ' On-line ',
};
// TypeScript type
type User = {
name: string;
status: string;
};
As you can see , They are very similar .
*
The main 「 difference 」 yes
**
stay
JavaScriptin , It's about variables 「 value 」
stay
TypeScriptin , It's about variables 「 type 」
User type , Its state attribute is too Fuzzy 了 . A state usually has 「 Predefined values 」, For example, in this example, it can be
On-line or
offline .
type User = {
name: string;
status: ' On-line ' | ' offline ';
};
The above code assumes that we 「 We already know what kind of state there is 」 了 . If we don't know , The status information may change according to the actual situation ? This requires generics to handle this situation :「 It allows you to specify a type that can be changed according to usage 」.
But for us
User For example , Use one 「 Generic 」 It looks like this .
// `User` Now it's a generic type
const user: User<' On-line ' | ' offline '>;
// We can manually add a new type ( Free )
const user: User<' On-line ' | ' offline ' | ' Free '>;
It says
user The variable is of type
User The object of .
Let's continue to achieve this 「 type 」.
// Define a generic type
type User<StatusOptions> = {
name: string;
status: StatusOptions;
};
StatusOptions go by the name of Type variable , and
User Said to be The generic type .
In the example above , We used
<> To define generics . We can also use functions to define generics .
type User = (StatusOption) => {
return {
name: string;
status: StatusOptions;
}
}
for example , Imagine our
User Accepted a State array , Instead of accepting a single state as before . This is still easy to do with a generic type .
// Definition type
type User<StatusOptions> = {
name: string;
status: StatusOptions[];
};
// The way types are used remains the same
const user: User<' On-line ' | ' offline '>;
The above example can define a
Status type , Then use it instead of generics .
type Status = ' On-line ' | ' offline ';
type User = {
name: string;
status: Status;
};
This is the case in the simpler example , But there are many cases where this cannot be done . The usual situation is , When you want 「 A type is shared across multiple instances , And each instance has some differences 」: That is, this type is 「 dynamic 」 Of .
⾸ Let's define ⼀ A pass ⽤ Of
identity function , Functional 「 Type of return value 」 With its 「 Parameters are the same 」:
function identity (value) {
return value;
}
console.log(identity(1)) // 1
Now? , take
identity The function is adjusted appropriately , With ⽀ a
TypeScript Of
Number Parameters of type :
function identity (value: Number) : Number {
return value;
}
console.log(identity(1)) // 1
about
identity function We will
Number Type assigned to Parameters and Return type , Make this function 「 barely enough for ⽤ In this original type 」. But this function It is not extensible or universal ⽤ Of .
You can put
Number Switch to
any , In this way, the definition of which type of energy should be returned is lost ⼒, And in the process make 「 The compiler has lost type protection ⽤」. our ⽬ Mark is to let
identity Function can be applied to ⽤ On 「 Any particular type 」, To achieve this ⽬ mark , We can make ⽤「 Generic 」 To solve this problem , Concrete realization ⽅ The formula is as follows :
function identity <T>(value: T) : T {
return value;
}
console.log(identity<Number>(1)) // 1
notice
<T> grammar , Just 「 Like passing parameters ⼀ sample 」, The code above conveys what we want ⽤ Specific function calls ⽤ The type of .
Refer to ⾯ Graph ⽚, When we tune ⽤
identity<Number>(1) ,
Number Types are like parameters 1 ⼀ sample , It will 「 In the presence of
T Any position of the type is filled with 」. In the figure
<T> Inside
T go by the name of 「 Type variable 」, It's what we want to pass on to
identity Functional 「 Type placeholder 」, At the same time, it is assigned to
value Parameters ⽤ Instead of its type : here T Acting as type ,⽽ It's not specific Number type .
among
T representative
Type, When defining generics, it is common to ⽤ Make the first ⼀ Type variable names . But actually
T Sure ⽤ Any valid name replaces . except
T outside , The following are common ⻅ The meaning of generic variables :
It can also lead to ⼊ Want to define 「 Any number of type variables 」.⽐ If we quote ⼊⼀ A new type variable
U ,⽤ To extend our definition of
identity function :
function identity <T, U>(value: T, message: U) : T {
console.log(message);
return value;
}
console.log(identity<Number, string>(68, "TS It really smells good "));
Sometimes we may wish 「 Limit the number of types each type variable accepts 」, This is it. 「 Generic constraint 」 Works of ⽤. Next ⾯ Let's take ⼏ Case ⼦, Introduce ⼀ How to make ⽤ Generic constraint .
occasionally , We hope 「 There are some attributes on the type corresponding to the type variable 」. At this time , except ⾮ We explicitly define specific attributes as type variables , Otherwise, the compiler won't know they exist .
For example, when processing strings or arrays , We will assume that
length The attribute can be ⽤ Of . Let's make ⽤
identity Function and try to output the ⻓ degree :
function identity<T>(arg: T): T {
console.log(arg.length); // Error
return arg;
}
under these circumstances ,「 compiler 」 Will not know
T It does contain
length attribute , Especially when you can 「 Assign any type to a type variable T Under the circumstances 」. What we need to do is make the type variable
extends ⼀ A connection that contains the attributes we need ⼝,⽐ Like this :
interface Length {
length: number;
}
function identity<T extends Length>(arg: T): T {
console.log(arg.length); // Can get length attribute
return arg;
}
T extends Length ⽤ Yu tells the compiler , We ⽀ Persistence has been realized
Length Pick up ⼝ Any type of .
In the previous example , We only give an example of how generic types can be used to define regular function syntax , instead of ES6 Arrow function syntax introduced in .
// ES6 Arrow function syntax
const identity = (arg) => {
return arg;
};
The reason is in use
JSX when ,
TypeScript The handling of arrow functions is not as good as ordinary functions . According to the above
TS Handling functions , Write the following code .
// It doesn't work
const identity<ArgType> = (arg: ArgType): ArgType => {
return arg;
}
// It doesn't work
const identity = <ArgType>(arg: ArgType): ArgType => {
return arg;
}
The above two examples , In the use of
JSX when , It doesn't work . If you want to handle arrow functions , You need to use the following syntax .
// The way 1
const identity = <ArgType,>(arg: ArgType): ArgType => {
return arg;
};
// The way 2
const identity = <ArgType extends unknown>(arg: ArgType): ArgType => {
return arg;
};
The root cause of the above problems lies in :「 This is a
TSX(
TypeScript+
JSX) Specific syntax for 」. In the normal
TypeScript in , There is no need to use this workaround .
Let's take a look at
useState Function type definition of .
function useState<S>(
initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>];
Let's analyze the definition of this type .
useState) It accepts a called
SGeneric variables for
initialState( The initial state )
S( Incoming generics ) The variable of , It can also be a return type of
SFunction of
useStateReturns an array of two elements
S typeValue (
statevalue )
Dispatch type, The generic parameter is
SetStateAction<S>.
SetStateAction<S>Itself has received a message of type
SParameters of .
First , Let's see
SetStateAction.
type SetStateAction<S> = S | ((prevState: S) => S);
SetStateAction It's also a generic type , The variable it receives can be either a S Variable of type , It can also be a will S Function as its parameter type and return type .
It reminds me that we use
setState Definition
state when
then , Let's go on
Dispatch What happened? ?
type Dispatch<A> = (value: A) => void;
Dispatch Is a receive generic parameter
A, Functions that do not return any values .
Put them together , Is the following code .
// The original type
type Dispatch<SetStateAction<S>>
// After the merger
type (value: S | ((prevState: S) => S)) => void
It is an acceptance of a value
S Or a function
S => S, Functions that do not return anything .
Now that we understand the concept of generics , We can see how to React Apply it to your code .
*
**
HookIt's just ordinary JavaScript function , But in
ReactThere is a little extra call timing and rules in . thus it can be seen , stay
HookUse generics on and in common
JavaScriptFunctions are the same .
// Ordinary js function
const greeting = identity<string>('Hello World');
// useState
const [greeting, setGreeting] = useState<string>('Hello World');
In the example above , You can omit explicit generics , because
TypeScript It can be inferred from the parameter value . But sometimes
TypeScript You can't do that ( Or do something wrong ), This is the syntax to use .
We are only aiming at
useState A class
hook Analyze , We also have other hook Make a connection with
TS Relevant analysis and processing .
hypothesis , You are building a for a form
select Components . The code is as follows :
「 Component definition 」
import { useState, ChangeEvent } from 'react';
function Select({ options }) {
const [value, setValue] = useState(options[0]?.value);
function handleChange(event: ChangeEvent<HTMLSelectElement>) {
setValue(event.target.value);
}
return (
<select value={value} onChange={handleChange}>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
);
}
export default Select;
「 Component calls 」
// label Options
const mockOptions = [
{ value: ' Banana ', label: '' },
{ value: ' Apple ', label: '' },
{ value: ' Coconut ', label: '🥥' },
{ value: ' watermelon ', label: '' },
];
function Form() {
return <Select options={mockOptions} />;
}
hypothesis , about
select Options
value, We can accept String or number ,「 But you can't accept both 」.
Let's try the following code .
type Option = {
value: number | string;
label: string;
};
type SelectProps = {
options: Option[];
};
function Select({ options }: SelectProps) {
const [value, setValue] = useState(options[0]?.value);
....
return (
....
);
}
The above code does not satisfy our situation . as a result of , In a
select Array , You might have one
select The value of is Numeric type , And another one.
select The value of is String type . We don't want that , but
TypeScript Will accept it .
For example, the following data exists .
const mockOptions = [
{ value: 123, label: '' }, // Numeric type
{ value: ' Apple ', label: '' }, // String type
{ value: ' Coconut ', label: '🥥' },
{ value: ' watermelon ', label: '' },
];
And we can 「 Use generics to force the component to receive
select The value is either a numeric type , Or string type 」.
type OptionValue = number | string;
// Generic constraint
type Option<Type extends OptionValue> = {
value: Type;
label: string;
};
type SelectProps<Type extends OptionValue> = {
options: Option<Type>[];
};
「 Component definition 」
function Select<Type extends OptionValue>({ options }: SelectProps<Type>) {
const [value, setValue] = useState<Type>(options[0]?.value);
return (
....
);
}
Why should we define
OptionValue , Then add... In many places
extends OptionValue.
Imagine , We don't do this , And just use
Type extends OptionValue Instead of
Type.
select How does the component know
Type It can be a number or a string , Not the others ?
「 Sharing is an attitude 」.
Reference material :
「 The full text after , Now that I see this , If it feels good , Give me a compliment “ Looking at ” Well .」 | https://qdmana.com/2022/174/202206231835478413.html | CC-MAIN-2022-27 | refinedweb | 2,374 | 52.6 |
From a servlet running in IIS under Windows, is it possible to kick off an rsh command to run a script on a remote UNIX machine?
Created May 4, 2012
Vincent Cirel Just off the top of my head, the following (pseudo code) is how I'd stab at it; should point in the right direction anyway. If you want a response you'll need to create the corresponding DataInputStream.
Hope this helps.
Vincent
This assumes you have rsh set up on the host and you send an appropriate username with the command if required.This assumes you have rsh set up on the host and you send an appropriate username with the command if required.
import java.net.*
//create a Socket object connected to port 514 (shell/cmd port used by rsh)
Socket mySock = new Socket("destination host",514);
//get the output stream for the socket
DataOutputStream outStream;
outStream = new DataOutputStream(mySock.getOutputStream());
//construct the command string
String rshStr = "whatever command you want to send"
//send it on its way
outStream.writeBytes(rshStr);
outStream.write(13);
outStream.write(10);
outStream.flush();
Hope this helps.
Vincent | http://www.jguru.com/faq/view.jsp?EID=69592 | CC-MAIN-2019-39 | refinedweb | 186 | 60.75 |
[]() []() # NAME Template::Liquid - A Simple, Stateless Template System # Synopsis use Template::Liquid; my $template = Template::Liquid->parse( '{% for x in (1..3) reversed %}{{ x }}, {% endfor %}{{ some.text }}'); print $template->render(some => {text => 'Contact!'}); # 3, 2, 1, Contact! # Description The original the expensive parsing and compiling can be done once; later on, you can just render it by passing in a hash with local variables and objects. - It needs to be able to style email as well as HTML. # Getting Started. ## Parse. ## Render); # Standard Liquid Tags [Expanding the list of supported tags](#extending-template-liquid) is easy but here's the current standard set: ## `comment` Comment tags are simple blocks that do nothing during the [render]( %}
{{ post.title }}...
Freestyle!{% endif %}{% endfor %} Another way of doing this would be to assign true / false values to the variable: {% assign freestyle = false %} {% for t in collections.tags %}{% if t == 'freestyle' %} {% assign freestyle = true %} {% endif %}{% endfor %} {% if freestyle %}
Freestyle!{% %} For more, see [Template::Liquid::Tag::Capture](). # Standard Liquid Filters Please see [Template::Liquid::Filters](). # Whitespace Control In Liquid, you can include a hyphen in your tag syntax `{{-`, `-}}`, `{%-`, and `-%}` to strip whitespace from the left or right side of a rendered tag. See # Extending Template::Liquid Extending the Template::Liquid template engine for your needs is almost too simple. Keep reading. ## Custom Tags See the section entitled [Extending Template::Liquid with Custom Tags]() in [Template::Liquid::Tag]() for more information. Also check out the examples of [Template::LiquidX::Tag::Dump]() and [Template::LiquidX::Tag::Include]() now on CPAN.. ## Custom Filters # Why should I use Template::Liquid? - Template::Liquid? - You've found or written a template engine which fills your needs better than Liquid or Template::Liquid ever could. - You are uncomfortable with text that you didn't copy and paste yourself. Everyone knows computers cannot be trusted. # Template::LiquidX or Solution? I'd really rather use Solution::{Package} for extentions but Template::LiquidX really is a better choice. As I understand it, the original project's name, Liquid, is a reference to the classical states of matter (the engine itself being stateless). I wanted to use [solution]() because it's liquid but with bits of other stuff floating in it. (Pretend you majored in chemistry instead of mathematics or computer science.) Liquid tempates will _always_ work with Template::Liquid but (due to Template::LiquidX's expanded syntax) Template::LiquidX templates _may not_ be compatible with Liquid or Template::Liquid. # Author Sanko Robinson | https://web-stage.metacpan.org/release/SANKO/Template-Liquid-1.0.19/raw/README.md?download=1 | CC-MAIN-2022-27 | refinedweb | 406 | 57.47 |
Back in January, Sandi Metz introduced her rules for developers in a Ruby Rogues podcast episode episode. Around the time Sandi’s rules were published, the team I am on was starting a new project. This post details the experience of that team applying Sandi’s rules to the new application.
The rules
Here are the rules:
-is not allowed).
When to break these rules
Paraphrasing Sandi, “You should break these rules only if you have a good reason or your pair lets you.” Your pair or the person reviewing your code are the people who you should ask.
Think of this as rule zero. It is immutable.
100-line classes
Despite the large number of private methods we wrote, keeping classes short proved easy. It forced us to consider what the single responsibility of our class was, and what should be extracted.
This applied to specs as well. In one case, we found a spec file ran over the limit which helped us realize we were testing too many features. We split the file into a few, more focused, feature specs.
That made us realize that
git diffs wouldn’t necessarily show us when we exceed 100 lines.
Five lines per method
Limiting methods to five lines per method is the most interesting rule.
We agreed
if,
else, and
end are all lines. In an
if block with two branches, each branch could only be one line.
For example:
def validate_actor if actor_type == 'Group' user_must_belong_to_group elsif actor_type == 'User' user_must_be_the_same_as_actor end end
Five lines ensured that we never use
else with
elsif.
Having only one line per branch urged us to use well-named private methods to get work done. Private methods are great documentation. They need very clear names, which forced us to think about the content of the code we were extracting.
Four method arguments
The four method arguments rule was particularly challenging in Rails, and particularly in the views.
View helpers such as
link_to or
form_for can end up requiring many parameters to work correctly. While we put some effort into not passing too many arguments, we fell back to Rule 0 and left the parameters if we couldn’t find a better way to do it.
Only instantiate one object in the controller
This rule raised the most eyebrows before we started the experiment. Often, we needed more than one type of thing on a page. For example, a homepage needed both an activity feed and a notification counter.
We solved this using the Facade Pattern. It looked like this:
app/facades/dashboard.rb:
class Dashboard def initialize(user) @user = user end def new_status @new_status ||= Status.new end def statuses Status.for(user) end def notifications @notifications ||= user.notifications end private attr_reader :user end
app/controllers/dashboards_controller.rb:
class DashboardsController < ApplicationController before_filter :authorize def show @dashboard = Dashboard.new(current_user) end end
app/views/dashboards/show.html.erb:
<%= render 'profile' %> <%= render 'groups', groups: @dashboard.group %> <%= render 'statuses/form', status: @dashboard.new_status %> <%= render 'statuses', statuses: @dashboard.statuses %>
The
Dashboard class provided a common interface for locating the user’s collaborator objects and we passed the dashboard’s state to view partials.
We didn’t count instance variables in controller memoizations toward the limit. We used a convention of prefixing unused variables with an underscore to make it clear what is meant to be used in a view:
def calculate @_result_of_expensive_calculation ||= SuperCalculator.get_started(thing) end
Great success
We recently concluded our experiment as a success, published results in our research newsletter, and have incorporated the rules into our best practices guide. | https://thoughtbot.com/blog/sandi-metz-rules-for-developers | CC-MAIN-2021-21 | refinedweb | 592 | 57.98 |
So I have this weird issue in my app, where after the first time someone connects with Metamask, it all works just fine, but once the user refreshes/disconects etc, anything after the first sign in, I can no longer get his wallet address or tokens balances.
It is important to note that this only happens after the app is being BUILT and served (both locally and on vercel, both have that issue!). No such issues when its being run in dev mode.
The only way for me to again get information about currencies and things like that is for the user to disconnect (from Metamask!) and reconnect, and then it repeats, on the first sign in I’ll get them and then I won’t.
Here is a minimal code to reproduce it:
import { useMoralis, useNativeBalance, useERC20Balances } from 'react-moralis' import { useEffect } from 'react' export default function Home() { const { authenticate, enableWeb3, isAuthenticated, logout, user, account, } = useMoralis() const { data: nativeBalance } = useNativeBalance() const { data: tokensBalance } = useERC20Balances() console.log(user?.attributes?.ethAddress) console.log('account', account) console.log('nativeBalance', nativeBalance) console.log('tokensBalance', tokensBalance) useEffect(() => { const authAndEnable = async () => { try { await authenticate() await enableWeb3() } catch (e) { console.log(e) } } if (isAuthenticated) { authAndEnable() } }, []) return ( <main> <button onClick={isAuthenticated ? logout : authenticate}> {isAuthenticated ? 'Disconnect' : 'Connect'} </button> </main> ) }
This code goes into pagse/index.js in a brand new next app, created with:
create-next-app .
The only packages installed are:
npm i moralis react-moralis @walletconnect/web3-provider
npm run build && npm run start and there you have it.
I have just installed it, so I should be with the latest versions of the packages:
"dependencies": { "@walletconnect/web3-provider": "^1.7.0", "moralis": "0.0.176", "next": "12.0.7", "react": "17.0.2", "react-dom": "17.0.2", "react-moralis": "^0.3.11" },
Here’s a short video that I made to show it: | https://forum.moralis.io/t/built-nextjs-app-does-not-get-user-data-from-usenativebalance-react-hook-after-a-refresh-but-works-fine-in-dev/6425 | CC-MAIN-2022-27 | refinedweb | 309 | 50.02 |
I’m trying to use Sentry in a typescript app that will run in the browser, so I’m including it like:
import * as Sentry from "@sentry/browser";
This gives me a compiler error,
Cannot find module '@sentry/browser'. ts(2307), even though I’ve updated my package.json to include both
@sentry/browser and
@sentry/types. I’ve been trying to figure out this error for a while, but I found a reference to this error being thrown if TypeScript can’t find an ambient declaration file for a third-party library (). Is this the probable cause, and does one of these declaration files exist somewhere?
Thanks! | https://forum.sentry.io/t/ambient-typescript-declaration-file/7816 | CC-MAIN-2019-43 | refinedweb | 108 | 51.99 |
.
If you would like to receive an email when updates are made to this post, please register here
RSS
Instead of re-hashing information I've found elsewhere I figured a pre-reqs post would be good. One of
A very neatly explained example.
Great work!!!
Hi,
I have tryied this example.Iam able to gat the data from the excel but unable to write the data into the excel by using "SetCellA1" property.
anyone can help on this.
Thanks&Regards,
Amar...
What error are you getting? Can you share the code you are running?
Hi Shahar,
Iam not getting any error.i folowed the same steps which u have given.
this is the code which iam writing data into the excel which is in Sharepoint server 2007 using excel webservices.
Code:
---------
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim mystat() As MyExcelWebReference.Status
Dim targetpath As String
Using es As New MyExcelWebReference.ExcelService()
targetpath = ""
es.PreAuthenticate = True
es.Credentials = System.Net.CredentialCache.DefaultCredentials
sessionid = es.OpenWorkbook(targetpath, String.Empty, String.Empty, status)
If (sessionid = "") Then
MsgBox("Error in Opening Workbook")
Else
es.SetCellA1(sessionid, "Sheet1", "A1", "Amar")
End If
es.CloseWorkbook(sessionid)
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Code
Please look into this and give me the code sample.
Oh.
Are you expecting to see the value change inside the Excel workbook inside sharepoint?
Thanks for the fast response...
yes i want to write some data into the excel located in the share point server 2007.
can you give me the points.
Amar....
Ezcel Services is not an authoring environment. It was not meant in this version to "Save Back" to the SP server.
It's still possible, but requires a few more steps.
1. Call the GetWorkbook() method on the proxy to get back a byte array represnting your workbook.
2. Use the SharePoint OM to save that byte array back to the server.
Thanks Shahar,
please can you give me the sample code steps for this.
once again thanks for the response.
Regards,
I can, but it may actually take me a little while to do this. Don't have time for posting articles right now and while it's not complex, it's a fair amount of code.
Until I get to do it, I suggest you search for information on how to use the SPFile.SaveBinary() method and take a look at the GetWorkbook() method of Excel Services.
s
Thanks for the info..
I will check the details...
Hi All,
I need some syntax to know the Active excelsheet name which i have opened using excel webservices.
please give me the code samples for that.
i want to see the active sheet neme when i open the excel in "view in browser" option in sharepoint server.
Can you elaborate on "i want to see the active sheet neme when i open the excel in "view in browser" option in sharepoint server"?
Not sure I undestand what you mean.
I have published my excel sheet into the sharepoint server 2007.
in that sheet in one cell i have placed one formula(i.e udf function) to get the activesheet name.
now when i want to go and see the excel in "view in browser" option in Sharepoint server 2007t then i want to get the active sheet name in the given cell whare i have given the formaula.
please help me out on this.
Amar...
What is the UDF that returns the ActiveSheet name exactly? I wasn't aware that we supported something like that.
(Which, of course, does not mean much, since there are many Excel functions I am not aware of. :))
I need one excel inbuilt funtion to get the Activesheet name.
that only i want to write in the UDF to get the Active sheet name.
Amar..
There is no such feature.
Can you explain what you need it for? It may help us in a future release.
Thanks...
I used the information in this blog to work with the excel services API within MOSS 2007 and was able to do a variety of activities with the exposed web service.
I am trying to access the same web service from a RTM Project Server website. The website exposes the particular webservice but I cannot add the reference itself. The Add Reference button is disabled and I get the following error messages:
<<
The document at the url was not recognized as a known document type.
The error message from each known type may help you fix the problem:
- Report from 'DISCO Document' is 'Root element is missing.'.
- Report from 'WSDL Document' is 'There is an error in XML document (0, 0).'.
- Root element is missing.
- Report from 'XML Schema' is 'Root element is missing.'.
>>
Is this an issue specific to Project Server RTM?
I then tried to access the excelservice webservice(the wsdl) of a RTM MOSS 2007 website and got the following error:)).
When I tried to add this webservice it allowed me but w/o the wsdl document.
I've never faced such problems with the Beta2 versions of MOSS.
I haven't found any info on these issues elsewhere and so any help would be appreciated.
How does a workflow work in Excel services?Basically i would like to know how the excel workbooks published on to the server behave when a workflow is started.Will the documents be visible to particular user only after it is approved by the initiatir or some other approver?
Thanks,
Vandana
Anirudh:
As for the first question: Excel Services is only enabled on the Enterprise version of MOSS. As far as I know, Project server is a different SKU that does not support it.
For more help on that, you can try accessing the forums:
As for the second question: What is it that you are doing exactly when you say "I then tried to access the excelservice webservice of a RTM MOSS 2007 website"? Where do you get that COM error you describe?
Vandana:
It all depends on what workflow you apply to the document library in question. There is no inherent process that happens for Workbooks on the server.
Thanks for the reply.I need bit more clarification on workflows.
I have used approval workflow which routes the documenst thru all the workflow participants.
whai i feel is once a document is approved then only it should go to next level for further processing.
but i find no such restriction in excel services.Is there any locking mechanism either thru custom workfkows or with predefined workflows wherein a workbook is viewed only if it approved by a particular user?
First off thanks for the prompt reply!
:)
Well its a disappointment if exceservices is not supported for project server, because even the project web access websites created under Project Server offer that excelservice webservice,i.e. you can see it when you try to add the web reference.
However it doesn't let you add this reference(button disabled) and the errors are printed in the web service despcrription txtbox.
After that I tried to access a webservice of a MOSS RTM site (on the same machine) and got the COM error.I got a workaround for that(it was a site specific error)
That was not the main issue; I really needed the excelserviceAPI for Project server. Are you sure it is not supported?
:(
Anirudh,
I am double-checking. But I think Excel Services comes only as part of the enterprise version.
Vandana,
I sent an email in the internal alias to see if something comes up.
Both:
Consider using the Excel Services forums () for questions such as this - you will get more eyes on them.
Anirudh,
Excel Services only comes as part of the MOSS for Internet Sites or the Enterprise packages. For more info, please follow this link:
Hi All,
I have created a approval workflow and i have added approvers name as administrator,spuser1 and i have assighned the work flow to the test document.after that i have loged in to the sharepoint server as another user.when i want to open the test document without approving the document logedin user able to open and edit the document but it should display some type of message like "it is not yet approved by the administrator workflow is in process".
is there any locking is available for the document when workflow is processing.
please anybody can give the flow of the work flow and approval steps and workflow conifiguration.
regards,
I want to know how to auto schdule my excel files in sharepoint server 2007.is there any provision given by sharepoint server 2007 to schdule the files and also programatically how can set the schduler.In sharepoint there is one dll i.e Microsoft.SharePoint.SPSchedule
how can we work on this iam not clear.can anybody can send sample code and help on this.
Can you explain what "Auto Scheduling" means? What's the expected behavior? What do you want them to auto schecule to?
Hi Sahar,
While opening the workbook I am getting "The file that you selected could not be found. Check the spelling of the file name and verify that the location is correct" error, but the path of the excel that I am giving is correct. How can I resolve this.
Can we refresh the document that is stored in Sharepoint under Excel trusted Location by calling Refresh method that is available with Excel services workbook? Is this possible?
I am getting the Error while opening the workbook, error is "You do not have permissions to open this file on Excel Services." The excel file that I am opening is in trusted location in sharepoint. Do we need to give any permissions to that document in sharepoint document library.
How do I can resolve this?
Here is the full code
ExcelService currentService = new ExcelService();
string targetPath = "";
Status[] outStatus;
currentService.Credentials = System.Net.CredentialCache.DefaultCredentials;
string sessionId = currentService.OpenWorkbook(targetPath, "en-US", "en-US", out outStatus);
Thanks in Advance,
Sasya
Can you choose "View in WebBrowser" in the drop down on the file?
View in WebBrowser" in the drop down on the file is working from Sharepoint document library.
But I am getting the error while accessing using Excel web services.
How do I resolve this error?
The excel sheet that I am trying to access from Excel Service also has Data Connections, which are used to pull data from database(SQL server).
Thanks
I am using Excel services for refreshing the excel sheet and then trying to save refreshed document to the Sharepoint library.Below is the thing that I am trying out:
1. Opening the workbook from Sharepoint trusted location.
2. Refreshing the excel report(Has Pivot Tables and Pivot Charts).
3. Writing refreshed data to an external file.
Here is the code:
ExcelService currentService = new ExcelService();
string targetPath = "";
string sessionId = currentService.OpenWorkbook(targetPath, "en-US", "en-US", out outStatus);
currentService.Refresh(sessionId, "Employees");
byte[] contents = currentService.GetWorkbook(sessionId, WorkbookType.FullWorkbook, out outStatus);
using (BinaryWriter binWriter =
new BinaryWriter(File.Open(@"C:\Test.xlsx", FileMode.Create)))
{
binWriter.Write(contents);
}
currentService.CloseWorkbook(sessionId);
I have modified my data source by adding new records,
But even after the refresh also the excel report is not getting refreshed. When I check Text.xls it is as same as the Source excel and not updated with the latest data from data source.
When I refreh the Connection from Excel the sheet is getting refreshed with the latest data from my datasource.
Is there anything I am missing here?
Any help will be appreciated.
Sasya:
RE: Failure of EWA
What's the error you are saying?
RE: Api question.
Hmm. That's very strange.
1. What does the connection shunt information to? (PivotTable?)
2. What happens if you call .RefreshAll() instead of .Refresh()?
Thanks for the response,
ConnectionString Info:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=SolutionMetaData;Data Source=xxxx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=Test;Use Encryption for Data=False;Tag with column collation when possible=False
CommandType:Table
CommandText:DataBase.TableName(Sample.Employees)
From C# Code for Excel Services:
If I call .Refresh by passing in second parameter as empty then it will refresh all the connections(Source:MSDN) I have tried the one below, but still it doesn't refresh.
currentService.Refresh(sessionId, "");
If I am refreshing the report from Excel client by using Refresh or RefreshAll from Connections Tab I am able to see the updated report in excel. But which is not happening from Excel web services.
I have a problem opening a workbook from a remote machine using Excel web services.
I am getting the following error:
URL authorization failed for the request
I am using the default credentials for Excel web services in code.
from X machine I am calling openworkbok for the url on machine MySite
URL passed in as parameter for OpenWorkBook is :
Thanks in advance
SL
SL:
Can you navigate to
?
If I try to access the url I am getting the error from machine x as well as machine Mysite, and Just it is displaying that an Error has occurred.
In eventViewer I didnt see any message related to that.
But on Mysite I can view without any error in WebBrowser by clicking View in WebBrowser link in the dropdown in Document library.
But If I am accessing ExcelServices.asmx on MySite machine with, I am able to access it without any error.
And in IIS for Office Server Web Services is configured with both Annonymous and Windows authentication.
MySite/_vti_bin/ExcelServices.asmx is also configured with both Annonymous and Windows authentication.
Sahara,
I have strucked with the Data refresh problem using Excel services using C# code. It is not working as documented in MSDN if my document has data connections to external data sources.
Sasya,
If you choose the "Refresh All Connections" from the EWA toolbar does it work?
(So, load the file in EWA and select the "Refresh ALL" and see if you get the new information you expect).
SL,
Excel Services API isn't accessible to anonymuos users, so you either must authenticate by supplying a network credentials (e.g. CredentialsCache.DefaultCredentials), or if you'd like you can modify the permissions of the anonymous user so that it has the "UseRemoteApi" permission. You can alter the permissions of the anonymous user from OM, or you can grant anonymous users full access to websites.
I hope this helps.
Hi Levin,
Here is the code that I am using:
ExcelService currentService = new ExcelService();
string targetPath = "";
currentService.Refresh(sessionId, "");
In my code I am using CredentialsCache.DefaultCredentials, but still OpenWorkBook is throwing out an error. And annonymous access in IIS is configured with Service account.
And I have tried running this code from the machine MySite, I am still getting the error.
Hi Anirudh,
if you have created a site collection then use the url reference as:
http://<server>/sites/<sitename>/_vti_bin/excelservice.asmx
Regards
Majeti
I have deployed a web application which uses excel web service on a sharepoint site. I have some named items on the excel sheet. How can i programatically get the list of all the named items/parameters defined in there.
Sush
You cannot. The only workarounds you have available (afaik) are:
1. Know the names before hand.
2. Place the names in a hidden sheet and have a well known range name for the range that contains all the named ranges. Then use that to get the names.
Hi there,
My project/app is called Webexcel1. I added a webreference called ES. But it doesn't recognize the namespace ES.
I tried it with the first using and the second one.
...
//using Webexcel1.ES;
using System.Web.Services.Protocols;
excelService.Credentials = System.Net.CredentialCache.DefaultCredentials;
Thanks!
Frank
Already solved my problem. It was due to a lack of knowledge in VS. I had the using declarations in the wrong spot of my project. Basics....
Works fine now.
Thanks and good luck.
Thanks for nice article.
But i am getting an Soap Exception error "An error has occured" message. in foolowing line
string test = es.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus);
can anyone help me why i am getting this exception and how i can solved it.
Thanks in advance.
hi!
my servlet return excel file i am getting excel file for java script request,but let me know how do open or display excel file through ajax responseText
regards
Thana
That's not something you can do today.
The only thing you can do is use AJAX to get data from Excel Services.
is it necessary to install office 2007 and devloper's machine or they can access from share point server. if Office 2003 is present on the local system
what are the minimum requirements for developer machine
if share point server machine has share point 2007 and excel 2007
You dont need anything installed on the Developer machine - just a connection to the Excel Services SharePoint.
I'm running into a soap exception error that a few of you mentioned previously. I get a "You do not have permissions to open this file on Excel Servcies" error when on the line of code where the ExcelService.OpenWorkbook function is called. I'm passing into the function the default credentials and a valid location. I've added the location of the xlsx workbook as a trusted WSS file location but i still get this error. I'd like to know if there are any possible explanations for this error. Thanks in advance guys.
Can you open the file via EWA?
When you run into issues like that, that's the first thing you should check - that will tell you whether the issue is with the server or with your software.
I can open it via EWA. Sorry bout leaving that part out before. I'm thinking it might have something to do with either the default credentials I'm passing into the function. Or that it has to do with the workbook location. The workbook is located in a content database path ().
Can i set security on Sheet level in a published workbook in Excel Services? My intension to publish a workbook with four sheets( i.e. user1,user2,user3,Admin). Every user have only access to his/her sheet only.
But Admin can view all sheets as well as by using excel built-in formulas he can go for some calculations by taking input from some/all other user sheets information.
Does it possible in Excel Services?
Jason:
If your user can open it in a browser, they should be able to open it through the API. What type of application is this?
Phaneendra:
We do not support this level of granularity with security - sorry.
I am facing a similar kind of issue regarding SOAP exception at OpenWorkBook method.
i am able to open the sheet in browser, i.e. it is working fine in EWA, but not coming up using web service.
I have checked that the workbook is stored at the trusted location. also I have checked the permission of the user. It's not working even by providing the Full Control.
What else could be the possible reason for this SOAP Exception?
Can you paste the skeleton of your code (everything relevant up to and including the OpenWorkbook call)?
Here is that snippet of code:
private void button1_Click(object sender, EventArgs e)
ExcelService proxyService = new ExcelService();
proxyService.SoapVersion = SoapProtocolVersion.Soap12;
proxyService.Credentials = System.Net.CredentialCache.DefaultCredentials;
Status[] status = null;
string SessionId = null;
string pathWorkbook = "";
SessionId = proxyService.OpenWorkbook(pathWorkbook, String.Empty, String.Empty, out status);
status = proxyService.SetCellA1(SessionId, "Calculator", "Loan", textBox1.Text);
status = proxyService.SetCellA1(SessionId, "Calculator", "Rate", textBox2.Text);
status = proxyService.SetCellA1(SessionId, "Calculator", "Years", textBox3.Text);
status = proxyService.CalculateWorkbook(SessionId, CalculateType.CalculateFull);
object result = null;
result = proxyService.GetCellA1(SessionId, "Calculator", "Payment", true, out status);
if (result != null)
textBox4.Text = result.ToString();
proxyService.CloseWorkbook(SessionId);
Its just a small application for calculation.
SessionId = proxyService.OpenWorkbook(pathWorkbook, String.Empty, String.Empty, out status);
this line of code is throwing the SOAP exception.
hey guys i have s problem........
While using UDF's i get the return values in a data table.
Now i wannt to show this entire table in the excle sheet as it is.
How can I do that?
Can you further explain what the issue is?
what do you mean by Data table? What tdo you mean "as it is"?
The OpenWorkbook() is throwing the following exception:
"Excel Web Services could not determine the Windows SharePoint Services site context of the calling process"
Please note:
1> I'm using Excel Web Reference not static binding
2> The excel file is in trusted location.
3> I'm able to browse the excel file using IE.
Please let me know what colud be the problem? | http://blogs.msdn.com/cumgranosalis/archive/2006/03/24/ExcelServicesHelloWorld.aspx | crawl-002 | refinedweb | 3,513 | 66.94 |
In yr code twiddling yr bits
Added.
def range2d(range_x, range_y): """Creates a 2D range.""" range_x = list(range_x) return [ (x, y) for y in range_y for x in range_x ] def xrange2d(range_x, range_y): """Iterates over a 2D range.""" range_x = list(range_x) for y in range_y: for x in range_x: yield (x, y)
Here's how you might use
range2d to iterate over the coordinates in an image.
for x, y in range2d(xrange(width), xrange(height)): #Do something with x, y
The
xrange2d function returns a generator rather than a list, but works the same.
Next up we have two functions to help with power of two textures;
is_power_of_2 returns
True if a given value is a power of 2, and
next_power_of_2 returns a power of 2 that is greater than or equal to a given value. These may be useful if you are working with OpenGL which requires power of 2 textures. I know newer versions of OpenGL support non-power of 2 textures, but it is a good idea to stick to power of 2 dimensions for compatibility.
def is_power_of_2(n) """Returns True if a value is a power of 2.""" return log(n, 2) % 1.0 == 0.0 def next_power_of_2(n): """Returns the next power of 2 that is greater than or equal to n""" return int(2 ** ceil(log(n, 2)))
There is actually bit-twiddling magic that could replace both of these functions, but I don't want to make any assumptions about which is faster in Python. The bit-twiddling code to calculate the next power of 2 is particularly suspect. It may generate just a dozen or so instructions in C, but I suspect that the Python overhead would make it slower than doing the float math. I may be wrong, but I lack the motivation to do the tests. The following is C *spit* code to find the next power of 2.
unsigned int v; // compute the next highest power of 2 of 32-bit v v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++;
If you are going for a job interview in the games industry, memorizing that code may be worthwhile, but you will never need it again!
Ok. Thats your lot. Go play nicely.
l.
Master time with PyGame
A_2<<!
BBCode module moves to Google Code
Postmarkup, my BBCode parser module now has a new permanent home on google code (). It's more than adequate for my needs now, just wish I had time to work on my TurboGears site! I thought I would have more spare time since becoming a full time Python contractor, but I'm as busy as a... sorry, too busy to think of similie.
Proud parent
The triops are just over 2 weeks old now, and as cute as a button. Tragically one hatchling died a few days ago, but the 7 that are remaining are doing well. Have a look at the photos.
(not actual size)
- | http://www.willmcgugan.com/2007/6/ | CC-MAIN-2014-52 | refinedweb | 501 | 78.89 |
Help:Etiquette
Contents
Edits[edit]
- Minor edit (spelling, grammar, adding refs/cats etc.):
- Checking the minor edit box signifies that the current and previous versions differ only superficially (typographical corrections, etc.), in a way that no editor would be expected to regard as disputable.
- Any edit that changes the meaning of an article is not a minor edit, even if the edit concerns a single word, and it is improper to mark such an edit as minor.[1]
- If it's an idiomatic difference (American vs. Real English, say) then pass by on the other side and ignore it. No one really cares that the yanks don't like silent letters/brits are afraid to use "...ize".
- If it's intended to be humorous as it stands - respect others' warped minds and ignore it (unless you think that you can improve the comic intent or it really, really detracts from the factual content).
- If you still want to edit then go ahead.
- Don't forget to check "This is a minor edit" and explain ("sp"," typo","ref", etc.) in the "Summary" box. This helps those sad individuals who feel the need to watch recent changes like hawks.
- Non-controversial edit (explanatory sentence or paragraph or clarification of ambiguity):
- If your amendment doesn't materially alter the tone, meaning or direction of the article then do it.
- Leave "This is a minor edit" unchecked - minor edits are really about altering one or two characters, e.g., a spelling correction.
- Give a short explanation in the "Summary" box. This makes it useful if you need to justify your addition and will save people questioning why you did something (even if it isn't controversial, some people are just like that).
- Controversial edit:
- Explain your point in the article's "talk" page first. Wait for replies. Then go with the flow.
- In the case of an article where one person did most of the work (check in "History"), contact them by commenting in their "talk" page. Again wait for reply and discuss on the article's "talk" page.
- If you get no responses in what you think is a reasonable amount of time, a day or so, you can flag it up at the saloon bar. Again, wait for replies. The controversial aspects of RW articles
are alwaysmay be thrashed out on talk pages first, since edit wars are unproductive and usually piss people off far more than discussion.
- If you cannot agree on an amendment it might be that alternate points should be made elsewhere in the article, or perhaps in a new article cross-referenced with the current one. If you can back a point up well, then there will always be some place where it can be placed.
- Don't start an "edit war", it's ugly, time wasting and counterproductive (although sometimes amusing to third parties).
- Undoing previous edit:
- Only use "rollback" to remove blatant vandalism, or any other self-explanatory reversion (such as when someone blanks a page, or adds "4 HOT SEX, see THIS LINK!!!123" to a page). This sort of rollback can also apply to talk pages.
- When reverting a good faith edit, use "undo" and state your reason(s) in the "Summary" box, such as "that was an intentional misspelling".
- Often a good faith edit that doesn't resonate well can still hold information that is interesting. If it's just the style or wording that you think is wrong, then improve it yourself, stating reasons in the summary page. Do not just go straight to a user's talk page and tell them they're useless.
- When reverting substantial edits, discuss your reasons on the talk page - a summary of "see talk" is usually sufficient. Copy the material that has been changed and place it on the talk page so everyone can see at a glance what the problems are. A difflink is generally considered okay for this purpose.
Don't be afraid of ridicule: you're as entitled to your
stupid brilliant opinion as anyone else.
Don't crowd other editors[edit]
If you see someone else making a lot of edits to one article in a short time, it might be that they're trying out something; let them finish before jumping in with your edits or comments. There are two methods you can use to help avoid edit conflicts in articles that you're developing:
Use a sandbox[edit]
If you're working on a new article or making extensive modifications to an existing one then it may be a good idea to work in a sandbox created in your userspace. Editors will normally avoid editing articles in userspace that doesn't belong to them, so you'll have more freedom to develop your article free of conflicting edits and criticism. A sandbox is created like any other page, but you must follow the format "User:Yourname/Name of your sandbox" (where Yourname is your username or IP address, and Name of your sandbox is entirely up to you). Here's an example:
This page probably won't be found, so you'll see an option to create a new page. This'll give you a private page that can be used for your edits. Once you're happy with the article, either relocate the page to the article name of your choice, or just copy and paste the code from it. You can create multiple sandboxes, and the naming is entirely up to you. For example:
As advised in our Help:Namespace article, you should not edit articles in the namespace of another user, but you can use talk pages to offer suggestions and solicit feedback.
- Tip: Be careful when adding categories to articles in your userspace, since your articles will then appear in category pages. Ideally you should add categories when you're ready to move your article in to its new home.
Add a "Work in progress" template[edit]
Template:WiP can be used to alert editors to your ongoing work, thus reducing the chance that someone will sneak in to modify something. Note that this template is only intended to be present in articles for specific periods of time (normally measured in hours). The template contains a warning to this effect.
Making edits easier to find[edit]
On long pages, especially long "talk" pages, your edit will be easier for others to find if you use the section "edit" link. Not only does this reduce the chance of edits conflicts (another person editing one section while you edit another will not cause an edit conflict), but the "arrow" link that shows up on "recent changes" and "watchlists" will go directly to that section. | https://rationalwiki.org/wiki/Help:Etiquette | CC-MAIN-2022-21 | refinedweb | 1,117 | 60.24 |
We are going to build a simple Front End that will use Scatter for logging in and authorising actions on the EOS blockchain
Once upon a time, the only wallet I knew was the one that carries my lunch money. Today there are numerous wallets out there, but instead of keeping your money they keep your private keys. Now among all the wallets out there I have chosen to work with Scatter due to it’s popularity among the EOS community. Most of the EOS Dapps being built these days, almost all of them supports Scatter. Scatter has also become increasingly popular among Ethereum and Tron, making it a solid investment for your future Dapp development.
Setting up Scatter
Scatter used to come in the form of a Chrome plugin, but now it has officially dropped that in favour of a full native app. If you have not installed Scatter, the first step you need to do is download it from its GitHub page here.
For the purpose of this guide we are going to import our EOS account we created on the CryptoKylin testnet the other day into our Scatter wallet. If you have no idea on how to create a testnet account, I have already written about it on my first guide under the EOS Account section, click here.
Now once you have your testnet account name and private key, fire up Scatter. On your first run it will ask you to create a password. You will need this password to unlock your wallet when ever you want to use it again at a later time.
Since we are planing to import an EOS testnet account, we must add the testnet details to Scatter first. The way to do this is to go to the Settings -> Networks. You will find the Settings button (shape of a gear icon) on the top right corner. Once again you need to key in your password.
Under the “Your Networks” tab, click on the Add button. Key-in the details according to the screenshot above. At the time of this writing these inputs are still valid, however to confirm that you have the latest inputs you should always ask in their telegram group here.
Import Keys
Ok now go back to the main interface of Scatter. Click on the “Add Keys” button on the bottom left corner.
You will see 3 options, click on the “Import Key” button.
Another 3 options will be shown, click on the first button “Text” since we have our private key in the text format. Go ahead and paste your testnet private key. Since every account you create on the testnet comes with an Owner and Active key, for simplicity sake you can just import your Active key.
Since we have already added the CryptoKylin details under the networks settings, Scatter automatically links your private key to your account name on the CryptoKylin testnet. You can view this under the Linked Accounts tab. Optionally you can give a nicer name for this key under the “Key Name” text box above. I am going to name it youracc[email protected]
At this point, we have completed all the setup necessary for Scatter to work with our Front End. Here is a summary of the main tasks we have accomplished so far:
- Created a testnet account
- Added the testnet details to Scatter
- Imported our testnet private key to Scatter
In the next section we will develop the Front End so it will talk with Scatter nicely. You will want to keep Scatter app running in the background so that our Front End detects it.
Front End
In my previous guide, I have written about building a simple Front End for EOS. It was a simple Dapp that is able to login the user with their account name and private key. To make this Dapp more practical, we are going to modify it so that it can work with Scatter.
When ever an action needs to be performed on the blockchain; for example logging in, with Scatter the user does not need to key in their private key every time. On the front-end side we do not need to cache their private key anymore, as this could cause vulnerability issues.
By using Scatter, this is how it is going to work from now on: every time we need to perform an action, we invoke Scatter from it’s javascript API. Scatter will then request the user for their permission on which key to use to perform the action. After the user has authorised then Scatter will return us a signature object that we can use to sign the transaction on the blockchain. Super simple, clean and more secure!
I have modified our previous front-end to now work with Scatter. Let’s get started by cloning my latest Github project and I will walk you through the main changes. Open terminal and type this:
$ git clone
Once all the files have been cloned to your local machine. Get into the project directory and install all the dependencies
$ cd eos-scatter
$
npm install
To avoid any babel/webpack issues with our Vue project, type this:
npm i -D @babel/runtime
VUEX
The first thing we are going to do is store the status of our login with VUEX. VUEX is quite similar to Redux as it is both inspired by FLUX, accept it’s more suited for Vue. I find overall using VUEX more simpler than Redux, however both these state management framework are equally good in my opinion.
//store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
loggedIn: false
},
mutations: {
loginStatus(state, status) {
state.loggedIn = status;
}
},
getters: {
loggedIn: state => state.loggedIn
},
actions: {}
});
Here I created a state called loggedIn and set it to false, then I created a mutation called loginStatus that just changes the value for loggedIn. Lastly I added a getter so we can retrieve the value of our loggedIn state.
Ok let’s see how we are going to access this newly created state on the UI part. I have modified the AppTopBar.vue component to include a Logout button.
The logout button has been wired to the handleLogout method and it calls the $store mutation named loginStatus. This action will set our loggedIn state to false. Pretty simple logic here. Now let’s go through the most important part which is the API calls to work with Scatter.
Scatter API
From early on I have stored all EOS related methods in a class called EosService. We are going to extend this class so that it is able to talk with Scatter.
//EosService.js
import { Api, JsonRpc } from 'eosjs';
import ScatterJS from 'scatterjs-core';
import ScatterEOS from 'scatterjs-plugin-eosjs2';
const endpoint = ''; // kylin
const network = {
blockchain: 'eos',
protocol: 'https',
host: 'api.kylin.alohaeos.com',
port: 443,
chainId: '5fff1dae8dc8e2fc4d5b23b2c7665c97f9e9d8edf2b6485a86ba311c25639191'
};
class EosService {
constructor(dappName, contractAccount) {
this.dappName = dappName;
this.contractAccount = contractAccount;
ScatterJS.plugins(new ScatterEOS());
this.rpc = new JsonRpc(endpoint);
window.ScatterJS = null;
}
connect = async () => {
await ScatterJS.scatter.connect(this.dappName).then(connected => {
if (!connected) return console.log('Failed to connect with Scatter!');
this.scatter = ScatterJS.scatter;
});
await this.scatter.getIdentity({ accounts: [network] }).then(() => {
this.account = this.scatter.identity.accounts.find(
e => e.blockchain === 'eos'
);
});
if (this.account === null) return false;
return true;
};
transaction = async (action, data) => {
this.api = this.scatter.eos(network, Api, { rpc: this.rpc });
const resultWithConfig = await this.api.transact(
{
actions: [
{
account: this.contractAccount,
name: action,
authorization: [
{
actor: this.account.name,
permission: this.account.authority
}
],
data: {
...data
}
}
]
},
{
blocksBehind: 3,
expireSeconds: 30
}
);
console.log(resultWithConfig);
return true;
};
}
export default EosService;
To work with Scatter, we first need to import 2 libraries: ScatterJS and ScatterEOS. We then specify the constants to store the endpoint and network details, in our case we will be using the testnet details. We will be only needing to main methods here, which is the connect and transaction.
In the connect method we simply try to link a Scatter account with our Dapp. Scatter will then prompt the user to select an account they would like to use with our Dapp.
In the transaction method, we are invoking an action on the EOS smart contract. What Scatter will do in this case is to prompt the user with a dialog to allow or deny this action.
Wrapping Up
For the final section of this guide let’s have a look at the Login page where we use our EosService.
Here we simply import our EosService, initialise our class and pass in the parameters into the class constructor. We then call the connect() method and the transaction() method passing in the name of the action we want to call on the smart contract and it’s input data. If it’s successful the method will return true and we change our loginStatus state to true and route the user to our main page.
If you open the chrome developer tools you should be able to see the transaction details printed out on the console.
Congratulations! we have successfully integrated Scatter to your Dapp. We have reached the end of this guide, but I would love to hear what you guys are working on. If you need help don’t be afraid to reach me.
read original article here | https://coinerblog.com/how-to-integrate-scatter-with-your-eos-front-end-696a27df12a1/ | CC-MAIN-2019-18 | refinedweb | 1,554 | 72.87 |
Contents
Introduction
In this article, we will go through the tutorial of Seaborn distplot which is a kind of distribution plot for univariate distribution of observation. We will cover the syntax of sns.distplot() and its parameter along with different examples of it like rugplot, KDE, etc.
So let’s start the tutorial and learn about this visualization.
Syntax of Distplot in Seaborn
seaborn.distplot(a=None, bins=None, hist=True, kde=True, rug=False, fit=None, hist_kws=None, kde_kws=None, rug_kws=None, fit_kws=None, color=None, vertical=False, norm_hist=False, axlabel=None, label=None, ax=None, x=None)
- a : Series, 1d-array, or list.
This parameter takes the data for building the plot.
- bins : argument for matplotlib hist(), or None, optional
Using this parameter, we set the value of bins.
- hist : bool, optional
This parameter will tell whether a normed histogram has to be build or not.
- kde : bool, optional
Through this, we can decide whether kernel density estimate plot should be plotted or not.
- rug : bool, optional
Through this, we can decide whether rug plot should be plotted or not.
- hist_kws : dict, optional
These are the keyword arguments for hist() function
- kde_kws : dict, optional
These are the keyword arguments for kdeplot() function
- rug_kws : dict, optional
These are the keyword arguments for rugplot() function
- color : matplotlib color, optional
Here we can provide the color for the plot apart from the curve.
- vertical : bool, optional
If set to true, then the values will be placed on y-axis.
- norm_hist : bool, optional
This helps in displaying histogram as density instead of count.
- axlabel : string, False, or None, optional
Here we can provide the names for axis of the plot.
Seaborn Distplot Example
1st Example – Distplot with KDE and Histogram
In this first example, we are importing the necessary libraries. Then, we generate random data that is consequently used for plotting distplot. We assign a color scheme with the help of the color parameter.
import seaborn as sns, numpy as np sns.set_theme(); np.random.seed(0) x = np.random.randn(125) ax = sns.distplot(x, color="r")
import matplotlib.pyplot as plt import seaborn as sns, numpy as np ax = sns.distplot(x, rug=True, hist=False)
3rd Example – Horizontal Distplot in Seaborn
The 3rd example will show how can we plot a horizontal distplot. Here we just have to use the vertical parameter which is set to True for plotting horizontal distplot.
ax = sns.distplot(x, vertical=True)
4th Example – Distplot with Rug, KDE and Histogram plot
In this 4th example, we are combining the distplot with rug, KDE, and histogram plot. We have specified the color for rug plot, line width and color for KDE plot, and histogram type, line width, alpha, color for histogram plot.
ax = sns.distplot(x, rug=True, rug_kws={"color": "g"}, kde_kws={"color": "k", "lw": 3, "label": "KDE"}, hist_kws={"histtype": "step", "linewidth": 3, "alpha": 1, "color": "y"})
Conclusion
It’s time to end this seaborn tutorial on distplot. In this we looked at the syntax of distplot, parameters that affect the distplot in various ways, different examples of distplot like rug, KDE, etc. are also shown.
Reference: | https://machinelearningknowledge.ai/seaborn-distplot-explained-for-beginners/ | CC-MAIN-2022-33 | refinedweb | 522 | 55.44 |
So I have a couple of problems with this assignment and I need a bit of help. The first is Went ever I input the name of a college or university that I know is on the list, it causes an infinite loop and repeats the menu forever. This will only happen if I type the name of a college or university(I could type giberrish and it wouldn't cause an infinite loop to occur). The last problem is how do I stop the program from displaying the two statements such as the "This institution is/isn't the list. I only want the program to display one of these statements whenever the user inputs the name of a college/university; not the whole entire list.
Note1: I need to mention that this menu has to have a vector of strings and array read from a file an into seperate functions.
Note2: If you're wondering why there are empty if/else statements, it's because I'm trying to fix this problem before I advance.
Note3: I've posted 2 txt files for you look to at.
#include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdlib> using namespace std; void collegesUniversities() { ifstream campuses; campuses.open("colleges.txt"); vector<string> schoolVector; string schools; cout << "\nEnter the name of your college/university. "; cin >> schools; if(!campuses) cerr << "Error opening file. "; else { while(getline(campuses,schools, '\n')) { schoolVector.push_back(schools); } } for(size_t i=0; i < schoolVector.size(); i++) { cout << schoolVector.at(i) << '\n'; if(schools != schoolVector[i]) cout << "\nThis institution is on the list. "; else cout << "\nThis institution isn't on the list. "; } campuses.close(); } int main() { int choice; cout << "Welcome to my college and university search program.\n"; cout << "\nPress any button to continue.\n "; system("pause>nul"); do { cout << "\nPress 1 to enter possible colleges and universities."; cout << "\nPress 2 to find out how many colleges and universities"; cout << " appear in your state.\n"; cout << "Press 3 to find the total amount of colleges and"; cout << " universities in our list. "; cout << "\nPress 4 to quit. "; cin >> choice; if(choice == 1) { collegesUniversities(); } else if(choice == 2) { } else if(choice == 3) { } else if(choice == 4) { cout << "\nThank you for using my program. "; cout << "Have a great day.\n "; } else { cerr << "\nError, Invalid input. "; cout << "Only integers from 1 through 4 are allowed.\n"; } } while(choice != 4); }
Edited 2 Years Ago by Freddy Kreuger | https://www.daniweb.com/programming/software-development/threads/486697/problems-with-my-menu-please-read-description | CC-MAIN-2016-50 | refinedweb | 403 | 67.35 |
Post your Comment
Passing Arrays In Jsp Methods
Passing Arrays In Jsp Methods
... will become
dynamic.
In this example of jsp for passing arrays in Jsp...;
<TITLE>Passing Arrays In Jsp Methods</TITLE>
</HEAD>
<
arrays
arrays using arrays in methods
Java use arrays in methods
import java.util.*;
class ArrayExample{
public static int getMaxValue(int[] arr){
int maxValue = arr[0];
for(int i=1;i < arr.length;i
arrays
that the getter and setter methods are already defined in the Country class, write
Writing code with multiple Class Methods and String Arrays
Writing code with multiple Class Methods and String Arrays So what I am trying to do is create a code that lists music artists names using user...
In these classes I need to create string arrays that contain artist names, and be able
Arrays -- Examples
Java NotesArrays -- Examples
This applet shows a number of methods that use arrays. The source code for
the methods is also given below.
This applet...(...) and
java.util.Collections.sort(...) methods.
Here are some questions that you should
Java Arrays Tutorials
The java.util.Arrays class helps the programmers to manipulating the arrays. It provides the methods to easily manipulate the arrays. Methods provided...(). Browse the following code to Learn Java Arrays in detail
Arrays
];.
Library methods for arrays
Static methods for manipulating arrays...
Java NotesArrays
Java arrays are similar to ideas in mathematics
An array...++, which had a good reason for
using zero (pointer arithmetic on arrays
Comparing Arrays
Comparing Arrays : Java Util
This section show you how to determine the given arrays
are same or not. The given program illustrates you how to compare arrays
according
arrays - Java Beginners
instead of public
3. It should have set and get methods for the name properties.... It is generally considerered a risky practice to create get and set methods for an array... contents). Instead, we can control the array through properties and methods
Arrays - Java Beginners
) with the following methods:
promptUser // prompts user for int input
loadArray // fills
Java Method with arrays
);
//methods
public static int[] intArray(int size) {
if (size < 0... SmallestIndex {
//variables
//methods
public static int SmallestIndex(int
arrays - Java Beginners
and the smallest values by using the above three methods.
? The program prints the largest
Arrays
arrays
Creating methods in servlets - JSP-Servlet
Creating methods in servlets I created servlet and jsp file.I Instantiated 3 objects and Defined 2 methods in my servlet, first method should write...
--%>
JSP Page
Post your Comment | http://roseindia.net/discussion/20707-Passing-Arrays-In-Jsp-Methods.html | CC-MAIN-2014-10 | refinedweb | 413 | 54.12 |
Red Hat Bugzilla – Bug 136859
inconsistent processing of /etc/profile.d/
Last modified: 2014-03-16 22:49:44 EDT
Changing a users shell between tcsh and bash can change when files
under /etc/profile.d/ get processed. This inconsistency can cause
several headaches for sysadmins.
The case in question is when someone uses ssh to launch a remote
command that isn't a shell script.
As an example, create the following file in your home directory:
[sean@head4 sean]$ cat env.py
#!/usr/bin/python
import os
print os.environ['G_BROKEN_FILENAMES']
Then ssh in and run it, like this: 'ssh <host> ./env.py' If your
shell is set to bash, it will traceback and say that os.environ
doesn't have the key 'G_BROKEN_FILENAMES'. If you shell is set to
tcsh, it'll print out '1'.
The problem seems to come from /etc/bashrc checking $SHLVL before
processing /etc/profile.d/*.sh Its trying to guess if its a login
shell (and if /etc/profile already processed the files). However, in
the case I outlined above, it guesses wrong.
If you replace /etc/bashrc with the FC3 version, does it behave?
Created attachment 105840 [details]
Fix this bug for FC3 version
I tried the /etc/bashrc from setup-2.5.35-1.noarch.rpm and the problem was
still there.
However, when I moved the /etc/profile.d/*.sh processing out of the 'if [
"$PS1" ]' it then started working as I'd expect. I included a patch of the
changes I made to the fc3 version of setup.
a) that looks obviously correct
b) that's changing behavior that's been that way for years. Makes me
nervous. :)
Fixed in 2.5.37-1. | https://bugzilla.redhat.com/show_bug.cgi?id=136859 | CC-MAIN-2018-22 | refinedweb | 285 | 77.64 |
The method
Thread.yield:
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
So in the following code:
public class Test implements Runnable { private int stopValue; public Fib(int stopValue){ this.stopValue = stopValue; } @Override public void run() { System.out.println("In test thread"); for(int i = 0; i < stopValue; i++){ c = i + 1; } System.out.println("Result = "+c); } public static void main(String[] args){ int defaultStop = 1024; if(args.length > 0){ defaultStop = Integer.parseInt(args[0]); } Thread a = new Thread(new Fib(defaultStop)); System.out.println("In main"); a.setDaemon(true); a.start(); Thread.yield(); System.out.println("Back in main"); } }
I expect that I should see:
In mainthen
In test thread
and the rest would be undefined. But I don't understand why sometimes I only see:
In main and
Back in main and not any print statement from
Test thread?
yield() is a hint to the OS scheduled but doesn't provide any guarantees in terms of scheduling. It doesn't always pause very long. If you call it repeatly it might only take a few micro-seconds.
Starting a thread takes time and even if you main thread pauses briefly, it may finish before the background thread starts.
As you can see, yield() pauses very briefly.
long start = System.nanoTime(); long runs = 20000000; for (int i = 0; i < runs; i++) Thread.yield(); long time = System.nanoTime() - start; System.out.printf("Thread.yield() took an average of %,d ns.%n", time / runs);
prints
Thread.yield() took an average of 148 ns.
by comparison, System.nanoTime take longer on my machine.
long start = System.nanoTime(); long runs = 20000000; for (int i = 0; i < runs; i++) System.nanoTime(); long time = System.nanoTime() - start; System.out.printf("System.nanoTime() took an average of %,d ns.%n", time / runs);
prints
System.nanoTime() took an average of 656 ns.
Both times will vary from OS to OS and machine to machine.
The main process might have exited before the thread got a chance to start. There is no guarantee that
Thread.yield() will force the thread to run in any particular time. If the thread did not start, then the
setDaemon() would have no effect.
Well, the yield() probably does nothing at all because the set of ready threads is less than the number of cores, in which case both threads can run anyway and main() will just continue to run on to the core it was running while the OS issues, (quite likely queues), a call to its intercore driver to run the new thread on another CPU core. Then there's the interaction with 'System.out.println' - an output stream call that is probably protected with a mutex.
I cannot quickly find any understandable explanation of what yield() actually does in differing environments/CPU/OS - one of the reasons I have never used it. The other is that I can't think of any use for it no matter how it works.
Try replacing your Thread.yield() with:
try { Thread.sleep(500); } catch (InterruptedException ex) { System.out.println(ex); }
@Peter's answer is a good one but I wanted to add some additional information as an answer.
First, as mentioned elsewhere, the
a.setDaemon(true) causes the JVM to not wait for the
Thread a to finish before quitting. If your real question is how to make sure that the
Thread a does it's work before the JVM shuts down then removing the
setDaemon(true) may be the solution. Daemon threads can be killed when the JVM exits. Non-daemon threads will be waited for. So the
main() method might return and the main thread might exit but your
Thread a would still run to completion.
In terms of
Thread.yield(), as you mention, the javadocs state:
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
This, however, is somewhat misleading. For example, if you have 2 threads running and 2 or more processors on your architecture, then the
yield() will effectively be a no-op. There are no other threads in the run queue that are waiting for processor resources so the main thread would be quickly rescheduled and would continue running with minimal pause.
Even if your are running on a single CPU system and your
Main does
yield(), your
Thread a goes to do a
System.out which is IO. The IO may block causing thread execution to switch back to
Main immediately.
When it comes down to it, only in very unique circumstances is a use of
yield() necessary. I've done a lot of multithreading programming and I've never used it. Trusting that the JVM thread scheduling will "do the right thing" in terms of time slicing is always recommended unless you have profiler output or expert advice to the contrary.
Similar Questions | http://ebanshi.cc/questions/2143066/how-does-yield-work-here | CC-MAIN-2017-04 | refinedweb | 811 | 68.06 |
Problem Formulation
Given a filename and an integer
n.
How to read the first
n lines of the file in your Python script?
Here’s an overview of the solutions:
Method 1: Store Head in a List of Strings
To read the first
n lines of a given file and store each line in a list of strings, you can use list comprehension expression
[next(file) for x in range(n)].
- The expression
next(file)gets the next line of the file.
- The context
for x in range(n)repeats this
ntimes.
Here’s a code script in a file
'code.py' that reads the first
n=4 lines of itself:
n = 4 filename = 'code.py' with open(filename) as my_file: head = [next(my_file) for x in range(n)] print(head)
The output is:
['n = 4\n', "filename = 'code.py'\n", '\n', 'with open(filename) as my_file:\n']
Method 2: Store Head in a String
You can also store the first n lines of a file in a single string using the following idea:
- Create an empty string variable
head = ''
- Open the file with
open(filename)
- Iterate
ntimes using a for loop
- Appending the next line in the file to the end of the string head using string concatenation.
Here’s the specific code:
n = 4 filename = 'code.py' head = '' with open(filename) as my_file: for x in range(n): head += next(my_file) print(head)
The
print() function gives the following output:
n = 4 filename = 'code.py' head = ''
Method 3: Slicing and readlines()
If performance is not an issue for you, you can read the whole file using the
readlines() function and then use slicing to access only the first
n lines. For example,
file.readlines()[:n] would return a list of the
n first lines in the
file.
n = 4 filename = 'code.py' with open(filename) as file: head = file.readlines()[:n] print(head)
The output of this code snippet is:
['n = 4\n', "filename = 'code.py'\n", '\n', 'with open(filename) as file:\n']
This is not a very performant way to read the head of a file because you first read the whole file before throwing away everything but the first
n lines. Thus, you should only use it if the files are relatively small and you don’t care too much about performance.
To learn everything you need to know about slicing, check out my book “Coffee Break Python Slicing”—bundled with my popular “Coffee Break Python” book here for a reasonable price. 🙂
Method 4: Pandas
A simple and straightforward solution that doesn’t require explicit file I/O is provided by the pandas library. To read the first
n lines of a file, you can use the pandas call
pd.read_csv(filename, nrows=n).
For example, to read the first five lines of the file
'file.csv', the following two-liner will do:
import pandas as pd head = pd.read_csv('file.csv', nrows=5)
You can check out my book “Coffee Break Pandas” to become a pandas expert using a fun puzzle-based learning approach.. | https://blog.finxter.com/how-to-read-first-n-lines-of-a-file-in-python/ | CC-MAIN-2022-21 | refinedweb | 510 | 69.92 |
VTK Coding Standards
From KitwarePublic
General Coding Standards (excluding any preceding vtk). For local variables almost anything goes. Ideally we would suggest using abbreviation and capitalize the abbrevi.
-.
-class'sTypeMacro(vtkBox,vtkImplicitFunction); void PrintSelf(ostream& os, vtkIndent indent); ... }
- STL usage:
- STL is for implementation, not interface. STL references should be contained in a .cxx class or the private section of the .h header file.
- Use the PIMPL idiom to forward reference/contain STL classes in classes. STL is big, fat, and slow to compile so we do not want to include STL headers in any .h files that are included in public VTK header files.
- Use the std:: namespace to refer to STL classes and functions (except for iostreams as mentioned below)
- For an example of STL usage, see the VTK FAQ.
- If you do need to include STL files within a VTK header, you must add a comment after it so that the automated repository commit checks will accept your changes:
#include <vector> // STL Header <additional Comment here>
- When using anything declared in iostream, do not use std::. Examples include cerr, cout, ios... Do not include the iostream header. It is already included.
- Do not use 'id' as a variable name in public headers as it is a reserved word in Objective-C++.
- Long smart pointer definitions should break after the equals sign and have two spaces preceding the next line
vtkSmartPointer<vtkXMLPolyDataWriter> writer = vtkSmartPointer<vtkXMLPolyDataWriter>::New(); }
Documentation Standards
Remaining questions
- Where do default values go (with the set/get functions or with the variable definition?)
Standard Set/GetMacros
The documentation style for this type of pair is very straight forward. There MUST be a single //Description for the pair and a brief description of the variable that is being set/get.
// Description: // Set / get the sharpness of decay of the splats. This is the // exponent constant in the Gaussian equation. Normally this is // a negative value. vtkSetMacro(ExponentFactor,double); vtkGetMacro(ExponentFactor,double);
Set/GetVectorMacros
The documentation style for vector macros is to name each of the resulting variables. For example
// Description: // Set/Get DrawValue. This is the value that is used when filling data // or drawing lines. vtkSetVector4Macro(DrawColor, double); vtkGetVector4Macro(DrawColor, double);
produces in the doxygen:
virtual void SetDrawColor (double, double, double, double)
We must therefore name the variables in the description, like
// Description: // Set/Get the color which is used to draw shapes in the image. The parameters are SetDrawColor(red, green, blue, alpha) vtkSetVector4Macro(DrawColor, double); vtkGetVector4Macro(DrawColor, double);
Set/GetMacros + Boolean
There must be a single description for this triple of macros. For example:
// Description: // Turn on/off the generation of elliptical splats. vtkSetMacro(NormalWarping,int); vtkGetMacro(NormalWarping,int); vtkBooleanMacro(NormalWarping,int);
SetClamp/GetMacros
The description must describe the valid range of values.
// Description: // Should the data with value 0 be ignored? Valid range (0, 1). vtkSetClampMacro(IgnoreZero, int, 0, 1); vtkGetMacro(IgnoreZero, int);
Testing Standards
- When adding a new concrete class, a test should also be added in
...VTK/Package/Testing/Cxx/
- The name of the file for the test should be ClassName.cxx where the name of the class is vtkClassName.
- Each test should call several functions, each as short as possible, to exercise a specific functionality of the class. 1,000 lines in main() is very hard to maintain...
- The "main()" function of the test file must be called TestClassName(int, char*[])
Questions
- Do we bother covering deprecated classes?
- Is there a way to mark deprecated classes as deprecated so they do not show up on the coverage dashboards?
- What is our target coverage percentage? 70%?
- How to test abstract classes?
- Can we create a system that checks for the existence of a test file for every concrete class? This would be a great place to start to improve coverage.
- When should a new "test prefix" be started? By adding tests to a list like this:
CREATE_TEST_SOURCELIST(ArrayTests ArrayCxxTests.cxx
they show up when running ctest as:
Start 33: Array-TestArrayBool
- If arguments are not required, should you use
TestName(int vtkNotUsed(argc), char *vtkNotUsed(argv)[])
or
TestName(int, char*[]) | http://www.paraview.org/Wiki/VTK_Coding_Standards | crawl-003 | refinedweb | 679 | 57.57 |
it is OOPL! not a pure OOPL though, but still... uh, heck, whatever...!!! ya, it's hard to believe some things he said. but let's give this guy the benefit of the doubt. who knows....???
Printable View
it is OOPL! not a pure OOPL though, but still... uh, heck, whatever...!!! ya, it's hard to believe some things he said. but let's give this guy the benefit of the doubt. who knows....???
So sorry to disappoint a few but I did teach middle school kids the very basic concepts of procedural programming, which was about all I really knew! We managed to handle the primative data types, learned about loops and conditional statements.. mostly just staying safely inside the main function. Then we "branched" out to use functions - with formal and actual parameters. But still no OOP stuff. At least we had a language that allowed structure and had an input statement!
So, I did teach them andthey did well but now I want to move to Java and I have no frame of reference for classes and objects. Guess I was just barely scratching the surface of programming but I never got far enough to make classes in C++ , heck we didn't even get to multi-dimensiion arrays.
I picked up several Java books and they almost all are written by professional programmers who have never taught someone lower the advanced college students.
If someone received only a C in a science course, would you never offer them other science courses? How about the C student in Math, or English? So why does it seem that Computer Programming is geared only for the engineering types. Couldn't - shouldn't - everyone benefit from learning some programming concepts? Then way not make programming something more attainable for the masses but making it easier to learn? Trouble is - we all don't have the same background. I came from the Social Studies field and tried my hand at programming computers. Sure I didn't get far but I'm still trying.
" The object is the fundamental entity in a Java program. The object is define by a class, which can be thought of as the data type of the object. Classes can be created from other classes using inheritance. " -- and this is just stuff from chapter 2 !
Trying teaching these concepts to Middle School kids with no programming and little math background and see how far you get before you are deep into creating other examples to get the idea across. What is your pay depended upon getting these concepts across? Would you still give those definitions and assume that they were self-evident?
I'm still struggling and still looking at books and on-site tutorials- awaiting that ahh haa moment.
Maybe my C++ procedural background has ruined me for OOP. But I'll keep looking ! Thanks anyways:rolleyes:
I don't see why it would have ruined it. When I started learning programming in java classes weren't even mentioned specifically until half way through the course. I'd been making classes without even realising it, but they weren't used to their full potential until object oriented concepts were brought into the equation half way through the term.
Basically (as has been mentioned, and I think you're beginning to understand), a class describes an abstract structure. I'll try and give a few examples using real world concepts.
THink of an abstract concept like vehicle. This is abstract because it doesn't fully describe something that is real. If I say vehicle you can't visualise one object that you can be sure i'm talking about. You can however think of some things you know a vehicle will have. A vehicle will be able to move, it will be able to stop and it will be able to carry passengers.
Now let's try and make the concept less abstract. Imagine a car. This is still abstract because there are many different types of car, but it isn't quite as abstract as simply saying vehicle. Since it is a vehicle you know it can do all the same things a vehicle can, ie move, stop and carry passengers. You also know that a car has doors, a chasis, an engine, a boot (trunk if you're american), wheels etc...
Now make it totally concrete. Think of a specific car *insert make of car here here*. This specific car is totally concrete, and has a very specific definition that makes it different to all other cars. Somewhere the manufacturer of this car will have a blueprint that fully defines the car, and this will be used to make many copies of the car in the factory.
The above example is a great analogy to classes in OOP. The class contains definitions that all objects of the class have to adhere to. If the class is abstract it can't have any objects made from it (just like you can't make a "vehicle" object from my example above because it is too vague). But the abstract class can be used to set down some general guidelines.
You can then extend this general class and make it more concrete and specific. The extended class will inherit all the information that the abstract class had, and it will define some knew information of its own. Eventually a class will be defined which is concrete enough to make an object from (just like the specific make of car was concrete enough to go out and buy from my example above). This class will have all the information necessary to make a specific object.
Just like each car the manufacturer makes is unique even though it is the same make, so are the objects you make from a class unique. The cars will be different colours, have different number of miles on the clock, be owned by different people etc. This is the same with objects in java. The variables they hold will have different values, they will all be doing seperate things etc.
Obviously i've run over a lot of concepts there rather quickly, but hopefully I made it easy enough to understand. I didn't mention any syntax specific things either, which is another thing that needs to be learned. OOP isn't actually all that complicated because it aims to represent real world things as much as possible.
erm.. mike.. I know he'll appreciate the post, etc, and to ArchAngel too, but this is america, and not sure what age range a mid-school student is, i took a quick look. gave me a pretty bit hint:
Quote:
17 Ways to Keep Your Middle-Schooler Turning the Pages
Try these tips for keeping your preteen's interest and skills on track.
pre-teen? you want to discuss concepts like abstraction, concretion and OO programming with a 12 year old? *%&@ that! these kids barely have enough algebra to figure out x+y where x=5 and y=10
fastfinger: sack off the merest idea of teaching them OO.. their logic just isnt advanced enough; it's barely graspable by the average university student
just give them this:
and remember, that when comparing strings, use:and remember, that when comparing strings, use:Code:
public class MyProgram{
public static void print(String s){
System.out.println(s);
}
public static String read(){
try{
return new java.io.BufferedReader(System.in).readLine();
}catch(Exception e){
return "<<Problem reading from keyboard>>";
}
}
public static String ask(String s){
System.out.print(s);
return read();
}
public static void main(String[] argv){
//WRITE YOUR CODE HERE
}
}
string1.equals(string2)
not string1 == string2
-
now is not the time to be teaching OO to kids.. ask them (the kids) how many would be comfortable to write a recipe for something their mother cooks.. if they can do that, they can write a program.. at 12, most kids want to do this (BASIC) :
10 print "simon is a nerd"
20 goto 10
run
well I wasn't answering the question so that he could repeat what I said to the kids (i didn't notice that he was teaching kids so young by the way). I was answering it so that he personally could understand the concepts. Most people who teach kids (even pre teen kids) need to learn way more than they're teaching the kids. I was just giving a very brief introduction to the concepts leaving out any syntax issues. Sorry if it was beyond what you need.
Hi fastfinger, sounds like you have quite a bit on your shoulders. I just thought I would maybe put in my ideas.
Firstly I also started with C and then C++ and then moved onto Java and the procedural C programming was a good introduction and the C++ was a slight step towards OOP. I think C and C++ are quite important to bring across the simple things like if-clauses, while-loops etc. If you have programmed in C++ then you may have used STRUCTS, these are basically the equivalent to classes in Java.
Many question to classes can be explained by the "is a" and "has a" relationship.
You may have a class Car which describes all the characteristics an automabile has. Now this Car Object "is a" Vehicle and "has a" model number, color etc.
A vehicle could be a boat or something so a Car must differ from the class Vehicle but has all the characteristics of a vehicle.
The class Car will now inherit all the properties and methods from Vehicle and add on more.The class Car will now inherit all the properties and methods from Vehicle and add on more.Code:
public class Vehicle
{
String color;
String modelNum;
public Vehicle (String inColor, String inModel)
{
color = inColor;
modelNum = inModel;
}
}
public class Car extends Vehicle
{
int noWheels;
public Car (String inColor, String inModel, int inWheels)
{
// call Constructor from superclass (here Vehicle)
super (inColor, inModel);
noWheels = inWheels
}
}
Now you have a class which will represent an Object when it is instantiated for example in your main method:
Java::
Car myCar = new Car ("red", "325i", 4);
// this Object can now be accessed using myCar. like:
System.out.println("The color of my car is:"+myCar.color);
// or reset the values like:
myCar.color = "yellow";
System.out.println("The color of my car is:"+myCar.color);
// Now it will print that your car is yellow.
Hope this helps you a little. | http://forums.devx.com/printthread.php?t=138614&pp=15&page=2 | CC-MAIN-2016-18 | refinedweb | 1,749 | 72.26 |
Use your Arduino board with Python.
Project description
Use your Arduino board with Python.
Overview
Nanpy is a library that use your Arduino as a slave, controlled by a master device where you run your scripts, such as a PC, a Raspberry Pi etc.
The main purpose of Nanpy is making programmers’ life easier, providing them a powerful library to create prototypes faster and make Arduino programming a game for kids.
from nanpy import ArduinoApi a = ArduinoApi() a.pinMode(13, a.OUTPUT) a.digitalWrite(13, a.HIGH)
I know, there are a lot of projects able to do that, but hey, Nanpy can do more!
Nanpy is easily extensible and can theoretically use every library, allowing you to create how many objects you want. We support OneWire, Lcd, Stepper, Servo, DallasTemperature and many more…
Let’s try to connect our 16x2 lcd screen on pins 7, 8, 9, 10, 11, 12 and show your first “Hello world”!
from nanpy import Lcd lcd = Lcd([7, 8, 9, 10, 11, 12], [16, 2]) lcd.printString('Hello World!')
really straightforward now, isn’t it? :)
Serial communication
Nanpy autodetects the serial port for you, anyway you can manually specify another serial port:
from nanpy import SerialManager connection = SerialManager(device='/dev/ttyACM1')
and use it with your objects
from nanpy import ArduinoApi a = ArduinoApi(connection=connection) a.pinMode(13, a.OUTPUT) a.digitalWrite(13, a.HIGH)
You can specify how many SerialManager objects you want and control more than one Arduino board within the same script.
How to build and install
First of all, you need to build the firmware and upload it on your Arduino, to do that clone the nanpy-firmware repository on Github or download it from PyPi.
git clone cd nanpy-firmware ./configure.sh
To install Nanpy Python library on your master device just type:
pip install nanpy
How to contribute
Nanpy still needs a lot of work. You can contribute with patches (bugfixing, improvements,
Do you want to support us with a coffee? We need a lot of caffeine to code all night long! if you like this project and you want to support us, please donate using Paypal
License
This software is released under MIT License. Copyright (c) 2012-2016 Andrea Stagi stagi.andrea@gmail.com
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/nanpy/ | CC-MAIN-2022-27 | refinedweb | 406 | 61.77 |
Asked by:
DFS replicates some reparse points but not others
- Hi,
I am using DFS Replication between 2 systems running Windows Storage Server 2003 Service Pack 2. On the source system, the application files (*.EXE) to be replicated are stubbed (set to a 4KB reparse point that contains the file metadata and the actual data is stored on a removable RDX cartridge). When DFS replication runs, it is able to replicate some of the stubbed files but not all of them. I get an error 4406 that says:
"The DFS Replication service encountered an unsupported reparse point in a replicated folder. This reparse point will not be replicated because the replication of this type of reparse point is not supported by the DFS Replication service.
"
I've searched the MS-FRS2 document that explains that certain types of reparse points can be replicated but others can't. So my question is, why can some files with a .EXE extension get replicated but others can't? What else do I need to know about these .EXE files to help me understand why some won't replicate?
Thanks,
Paul
Question
All replies
- Hi Paul,
To ensure that this is the issue you can:
- Look in DFSMGMT.MSC under Namespaces and you'll likely see that this path is shared to match what is in the Namespace Servers tab
- Use FSUTIL to dump the reparse data against this folder's contents. For example:
1. DIR C:\DfsRoots\Public <-- will see a junction pointed folder here.
2. FSUTIL reparsepoint query C:\DfsRoots\Public\SomeJunctionFolder
Reparse Tag Value : 0x8000000a
Tag value: Microsoft
Tag value: DFS
Reparse Data Length: 0x00000000
Please don't replicate data in the DFS Namespace root EVER - this guidance is unchanged from DFS/FRS on 2000/2003 RTM.
DFS-R just stops you from destroying data like you could in the past,
Set up the empty DFS Root target folders, then create Folder (Link) Targets and replicate *that* set of data instead.
This is by design behavior.
There should never, exever be any data in the Root Target folders cept what is automatically created by DFS Namespaces (DFSN).
It should consist only of shares which have been reparse pointed to allow DFSN to operate.
It is also possible that there is a non-MS reparse point.
Using FSUTIL like above will (hopefully) show you a 3rd party TAG in that scenario.
More info on Reparse Points:
More info on reparse points and DFSR (DFSR FAQ):
This posting is provided "AS IS" with no warranties, and confers no rights.
- Marked as answer by David Shen Wednesday, January 20, 2010 8:14 AM
- Unmarked as answer by PBratach Wednesday, February 03, 2010 10:09 PM
- David,
Thank you for the previous response. I am not replicating data in the DFS namespace root, I am replicating files in a shared folder. The files are then stubbed with the reparsepoint tag 0x16 (HSM). According to the DFS Design page ( ) files with reparsepoint tag of HSM are supposed to have their contents replicated. But in my case that is not happening. Here is the FSUTIL output from the file and the Event Viewer error. My question is, why can't this file that has a reparsepoint tag of HSM be replicated?
Thanks,
Paul
C:\Documents and Settings\Administrator>fsutil reparsepoint query "D:\ArchiveVaultFolders\ISV_ReadWrite_1\DFSTEST100108-A\New Folder100113\Mimosa\ENT\SETUP\I386\EXCHANGE\BIN\esebcli2.dll"
Reparse Tag Value : 0x00000016
GUID : {EBAFF6E3-F21D-4496-8342-58144B3D2BD0}
Reparse Data Length: 0x00000018
Reparse Data:
0000: 02 00 00 00 00 00 00 00 ca f1 aa a7 6b 4a 35 00 ............kJ5.
0010: 00 00 00 00 00 00 00 00 ........
C:\Documents and Settings\Administrator>
==================================================================
Here is the error from Event Viewer:
Event Type: Error
Event Source: DFSR
Event Category: None
Event ID: 4406
Date: 1/27/2010
Time: 1:38:24 PM
User: N/A
Computer: ISV-TEST-1
Description:
The DFS Replication service encountered an unsupported reparse point in a replicated folder. This reparse point will not be replicated because the replication of this type of reparse point is not supported by the DFS Replication service.
Additional Information:
File Path: esebcli2.dll
Replicated Folder Root: D:\ArchiveVaultFolders\ISV_ReadWrite_1\DFSTEST100108-A
Replicated Folder Name: InfiniVaults
Replicated Folder ID: 0DEC009E-2D37-4500-96F8-1428741B01FA
Replication Group Name: DFSTEST100108-A
Replication Group ID: 3C90ED09-5390-43EC-A15F-D2CA44871E08
Member ID: 24ED6BB8-1EA9-4349-9802-52B26079FD8A
For more information, see Help and Support Center at.
================================================================================================
Hi PBratach,
I was told that no reparse points are replicated with DFS. Did you ever resolve this issue?
We have an issue where the Enterprise Vault Reparse Points are being deleted by DFS, causing a nightmare in our office! We didn't really care that they weren't being replicated as generally remote offices weren't accessing the old files, and if they did they could just access the share from our main office (just that it would be a little bit slower for them)
It would be great to know if you got them to replicate. | http://social.technet.microsoft.com/Forums/windowsserver/en-US/831c2440-ce5e-474b-a926-92bd69402fa3/dfs-replicates-some-reparse-points-but-not-others?forum=winserverfiles | CC-MAIN-2014-10 | refinedweb | 843 | 60.85 |
Let's start by talking about Rename. I view Rename as being one of the “Tier 1” refactorings – the refactoring we absolutely must provide, and which must be of the highest quality. They must be fast, reliable, and easy to use. You’re going to use them often, and we want you to like them a lot.
There’s also an option to see a preview of the changes before they get applied. I think you’ll use the preview the first time, and then turn if off. You don’t need it when the refactoring tool is reliable; you’ve got more important things to do.
Just about anything. The UI is pretty much the same for namespaces, types, fields, locals/args, and methods. For methods we will offer to rename overloads as well.
I argued that we should not support fixing up comments. Our refactorings are designed to be reliable – you can know that when you use them, the result will be what you expect. But we can’t really do comment fixup reliably, since it’s prose, not C# -- the semantics aren’t well defined.
Consider:
class C
{
// 'i' is my favorite variable.
int i;
int F(int i) // <--- rename 'i' here
{
return i == 0 ? 1 : i * F(i);
}
}
Go to the marked line & rename ‘i'. If you ask us to update comments, we’ll change the one on the field, as well. That’s probably not what you wanted, but there’s no way for us to know that.
In my not-at-all-humble opinion, if you want to update comments, you should use Find & Replace in Files, instead of the Rename Refactoring. Find/Replace is not very smart, but you expect that, and you already know how to manage it to get the result you want.
However, every time we showed people Rename, their first question was “Will you fix up comments, too?” So, we are including an option to fix up strings.
Normally, no.
If you’re a Refactoring purist, I’ll tell you that we applied the definition of Refactoring (specifically, the “leaves its behavior unchanged” part). If you could toggle off a specific reference, the behavior would change. (Specifically, your code would go from legal to C# to not legal C#.)
If you’re a Refactoring pragmatist, I’ll tell you that Find & Replace in Files has appropriate user interaction model for this kind of activity.
If you elect to Search in Comments, then you get some checkboxes for the comments.
Yes, but only if they’re C# projects. If you have VB and C# projects in the same solution, the VB references won’t be updated.
We have some smarts about renaming between the forms designer, the editor, and the solution explorer. For example, if you follow 1-class-per-file, and you rename a file, it’ll rename the class, too.
Reading this blog, do you think we’re making the right choices in our Rename design?
Are we providing the functionality you expect?
Are there parts of this feature description that look like a waste of our efforts?
When commenting, say where you put yourself on the “Refactoring Purist” scale. | http://blogs.msdn.com/b/jaybaz_ms/archive/2004/04/08/110167.aspx | CC-MAIN-2015-40 | refinedweb | 532 | 73.88 |
I'll announce two new releases as soon as I get confirmation that this
mailing list is working again. I haven't got through since friday, but as
the university's mail infrastructure is based on microsoft products, I
will not be surprised if they simply need to reboot a couple of machines
come monday morning.
The changelogs are:
Pre-release 3.0.16-pre2
-----------------------
* Added german translation by Michael Waider.
* Added a security update for avoiding script injection. Note that
this involved prohibiting the characters <, >, ', $ and \. Also
legitimate uses of these characters have been blocked, which might
cause some problems. This is a temporary solution for the immediate
problem, and it will likely be reworked before 3.0.16 proper is
released.
* Changed strategy for multi-page submitting, to work around bug where
their sizes were limited by the maximum length of the GET string.
This was inspired by a patch received from Matthias Helletzgruber
ages ago.
and
Development release 3.2.0-pre4
------------------------------
* Applied patch from Matthew Buckett for fixing erronous error
messages about MULTICHOICE (this tag has been merged into CHOICE)
* Applied patch from Matthew Buckett for better error messages
when Session directory isn't properly setup.
* Fixed bug where multipaging would not work when client refused
cookies (especially IE)
* Fixed a bug where variable-carrying CUSTOM blocks would not save
data when in a multipage context.
* Added MAILCOPY tag for sending a mail with data to a specified
address.
* Added outline for new CATI tag. Functionality will be added
later.
* Applied patch from BugAnt for basics of IMPORT tag (tag able to
import values as variables from database fields)
* Applied patch from Buckett for backwards-compatibility with older
survey.conf files
* Applied patch from BugAnt for working around script injection in
HTML tables export. (replace html tags with escape sequences)
* Corresponding for SQL export
* Corresponding for XML export
* Script injection detection code for action parameter
* Sanity parse in DBI save method.
* Added german translation by Michael Waider.
* Added option in installer for setting PerlSendHeader to on or off.
This should ensure better Apache2 compatibility.
* Applied patch from Matthew Buckett for better layouting of SQL
export and addition of GRANT clause.
* Applied patch from Matthew Buckett for better XML export.
* Changed a lot of "print content-type to $r->content_type()".
I'm pushing off documentation updates and CSS updates to get these out
through the door. Also, I'll publish a security advisory separately on
this list and on bugtraq as soon as the releases are online.
// Joel
Skickat av Joel Palmius <joel.palmius <at> mh.se>
till survey-discussion | http://article.gmane.org/gmane.comp.apache.mod-survey.general/638 | crawl-002 | refinedweb | 433 | 58.08 |
On Sun, 1 Jun 2008, Paul Mundt wrote:> This still needs to be virt_to_head_page() I think.> > I don't have my nommu boards at home, so I'll test at the office tomorow> morning and let you know.Yes, I messed that up. Thanks a lot for your help, Paul! Pekka[PATCH] nommu: kobjsize fixFrom: Christoph Lameter <clameter@sgi.com>The kobjsize() function is broken with SLOB and SLUB. As summarized by PaulMundt: The page->index bits look like they are being used for determining compound order, which is _completely_ bogus, and only happens to "work" in a few cases. Christoph and I have repeatedly asked for someone to explain what the hell those tests are there for, as right now they not only look completely bogus, but they also stop us from booting on SLOB. So far no one has provided any input on why those page->index BUG_ON()'s have any right to exist. So while having 2 out of 3 SLAB allocators in a bootable state might seem like progress, I'd rather see kobjsize() fixed correctly. Even my initial patches worked for all 3. If no one can speak up to defend those bits, they should be killed off before 2.6.26. Whether this is done in combination with your patch or Christoph's patch or whatever else doesn't matter.You can find the discussion here:: Paul Mundt <lethal@linux-sh.org>Cc: David Howells <dhowells@redhat.com>Cc: Matt Mackall <mpm@selenic.com>Signed-off-by: Christoph Lameter <clameter@sgi.com>Signed-off-by: Pekka Enberg <penberg@cs.helsinki.fi>---diff --git a/mm/nommu.c b/mm/nommu.cindex dca93fc..935887b 100644--- a/mm/nommu.c+++ b/mm/nommu.c@@ -109,16 +109,23 @@ unsigned int kobjsize(const void *objp) * If the object we have should not have ksize performed on it, * return size of 0 */- if (!objp || (unsigned long)objp >= memory_end || !((page = virt_to_page(objp))))+ if (!objp)+ return 0;++ if ((unsigned long)objp >= memory_end)+ return 0;++ page = virt_to_head_page(objp);+ if (!page) return 0; if (PageSlab(page)) return ksize(objp); - BUG_ON(page->index < 0);- BUG_ON(page->index >= MAX_ORDER);+ if (WARN_ON(!PageCompound(page)))+ return 0; - return (PAGE_SIZE << page->index);+ return PAGE_SIZE << compound_order(page); } /* | https://lkml.org/lkml/2008/6/1/28 | CC-MAIN-2016-18 | refinedweb | 369 | 68.16 |
Feature #12057open
Allow methods with `yield` to be called without a block
Description
Trying to figure out how
yield works in Python, i had the following idea.
Allow a method with
yield to be called without a block. When a method encounters
yield, if no block is given, the method returns an
Enumerator object.
def f yield 'a' yield 'b' end e = f puts e.next # => a puts e.next # => b
It seems that this is what
yield in Python does, but in Python a function with
yield cannot take a block. Why not to have both?
Updated by alexeymuranov (Alexey Muranov) over 5 years ago
Or maybe not an iterator but a delimited continuation?
Probably the following behavior is more natural:
def f ['a', 'b', 'c'].each do |c| puts yield c end return 'd' end c, v = f puts v # : a c, v = c.call("(#{ v })") # : (a) puts v # : b c, v = c.call("(#{ v })") # : (b) puts v # : c v = c.call("(#{ v })") # : (c) puts v # : d c, v = f puts v # : a v = c.call("(#{ v })") {|v| "[#{ v }]"} # : (a) # [b] # [c] puts v # : d
So by default "
yield" would be just "return-with-current-delimited-continuation", but if a block is given, all references to "
yield" in the method would be rebound to run that block.
By analogy to "
yield from" in Python 3.3, a method
yield_from can be created to work as follows:
def f [1, 2, 3].each do |i| yield i end nil end def g yield_from f yield 0 end c, v = g puts v # : 1 c, v = c.call puts v # : 2 c, v = c.call puts v # : 3 c, v = c.call puts v # : 0 v = c.call('The End') puts v # : The End
"
yield_from nil" does nothing.
P.S. It looks like what Python does is a bit more complicated and rather nonlogical (probably searching for "
yield" keyword at the definition time).
Updated by shyouhei (Shyouhei Urabe) about 5 years ago
What OP wants can be done using enumerator.
require 'enumerator' def f Enumerator.new do |y| y.yield 'a' y.yield 'b' end end e = f puts e.next # => a puts e.next # => b
Or, I might be failing to understand the request. Might it be "if block is present call it, but if absent no error" request? If so, following one line addition solves such request.
def f return enum_for(__method__) unless block_given? # this yield 'a' yield 'b' end e = f puts e.next # => a puts e.next # => b
Either way, I see no need to extend the language.
Also available in: Atom PDF | https://bugs.ruby-lang.org/issues/12057 | CC-MAIN-2021-31 | refinedweb | 437 | 85.28 |
: ...
Series overview [ID:823] (Free) (1/9)
in series: Batteries included - The Python standard library
video tutorial by Lucas Holland, added 08/08
video I give you an overview of what I cover in the series. In addition to that, I also walk you through a crash course on modules in Python. NOTE there are some loud audio noises on occasion, please excuse the bumps on the microphone!
- python
- beginners
- programming
- http
- basics
- time
- introduction
- part
- cover
- notes
- modules
- available
- maths
- overview
- paths
- html
- library
- date
- filters
- audio
- interpreter
- os
- mathematical
- mathematics
- preview
- filesystem
- crashcourse
- regularexpressions
- directorylisting
- glob
- operatingsystem
- platformindependent
- commandlinearguments
- noise
Got any questions?
Get answers in the ShowMeDo Learners Google Group.
Video statistics:
- Video's rank shown in the most popular listing
- Video plays: 1606 (since July 30th)
- Plays in last week: 1
- overview
Nice easy basic lesson, i'll definetly watch rest of ithis
good revision
very good, thank you
Looks like a very comprehensive series. Exciting!
this is great material!
Very useful. One problem with the video is the background noise, which is a distraction
Excellent information. Well organized.
pretty good, i did not know it was a bad thing to import *, but now i understand that its better to use objects with their full namespace.
lots of typing but clean...
Cool stuff. I am learning python right now and these look quite useful I will check the rest of the :)
malcolm
Very good introduction. Nice microphone work ;-)
John
great video...
thank you!
Couldn't you move your mic less and don't drop it during tutorial?
I look forward to the rest of your series; however I'm surprised that you didn't remake the introduction to make a video without the several very startling episodes of mic noise.
Hi Lucas, I've just blogged about your series:
Ian.
Your video has been edited. This is an automatic post by ShowMeDo.
Thanks for your positive feedback, gasto, I really appreciate it!
I am glad you are making Club ShowMeDo screencasts. This will help give learners more reasons to join ShowMeDo and keep it self-maintainable.
This series seems to be very promising.. | http://showmedo.com/videotutorials/video?name=3070000 | CC-MAIN-2014-42 | refinedweb | 357 | 63.19 |
#include <hallo.h> Mark Brown wrote on Tue Sep 04, 2001 um 09:30:53AM: > > Hm. Someone see this as bothering, others just want to have control > > about created files. > > MAKEDEV is a conffile. Did I miss something? cat /var/lib/dpkg/info/makedev.conffiles /etc/init.d/makedev > The discussion is about the requirement to ask permission being replaced > by a requirement to notify the user. #106280 in case we're looking at > different things. There are many proposals and comments, but no clear decisions. > > Yes. 11.6 is clear, and your postinst violates it, and this is exactly > > what the "serious" severity means. > > On the other hand, policy is supposed to reflect what we actually do. Yes, it should. But it is frozen now. >. Gruss/Regards, Eduard. -- "Millionen von Fliegen, die um den Dreck schwirren, können sich nicht irren" (Auswertung der Win-95 Verkaufszahlen, in Chip 8/96)
Attachment:
pgpvoQoZSaVLg.pgp
Description: PGP signature | https://lists.debian.org/debian-policy/2001/09/msg00028.html | CC-MAIN-2014-15 | refinedweb | 156 | 69.07 |
11 January 2010 10:18 [Source: ICIS news]
SINGAPORE (ICIS news)--Malaysia’s Titan Petchem will reschedule the maintenance of its No 2 cracker, which will be taken off line for 30 days sometime in the fourth quarter, an industry source said on Monday.
The cracker, which is now running at its nameplate capacity of 400,000 tonnes/year, was originally planned for a shutdown in June, he added.
At present, Titan’s No 1 cracker of 300,000 tonnes/year is also operating at full steam because of a bullish naphtha market.
“Both crackers are operating at 100 percent,” said the source.
Benchmark naphtha crack spread soared to $170.63/tonne (€118/tonne) above Brent crude futures, the strongest since 22 Dec amid robust petrochemical demand in ?xml:namespace>
( | http://www.icis.com/Articles/2010/01/11/9324277/malaysias-titan-petchem-reschedules-cracker-maintenance-to-q4.html | CC-MAIN-2014-41 | refinedweb | 130 | 59.94 |
React, make state apply to single element in loop
I have 3 circles that should change src of image when toggled, currently all circles toggle the src when one is clicked. I could use some help with how to get that problem fixed.
This is what i got right now
this.state = { fillCircle: false }; circleHandler = () => { this.setState({ fillCircle: !this.state.fillCircle }); }; render() { let circles = []; for (var i = 0; i < 3; i++) { circles.push( <img key={i} ); } return ( <div> {circles} </div> );
This is because each of those elements needs it's own state. Write a separate component for each circle. Then you would do
circles.push(<CircleComponent key={index} />)
Inside CircleComponent you would have your state for each Component and toggle for each one of them. Don't forget about keys as well.
Conditional Rendering – React, In React, you can create distinct components that encapsulate behavior you you can render only some of them, depending on the state of your application. like if or the conditional operator to create elements representing the current state, State Updates May Be Asynchronous. React may batch multiple setState () calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. manipulate state with a functional approach.
Didn't try it, but you should get the concept.
this.state = { fillCircle: [false,false,false] }; circleHandler = (i) => { this.setState((prev) => { if(prev.fillCircle[i] == false)prev.fillCircle = [false,false,false] // <-- prev.fillCircle[i] = !prev.fillCircle[i]; return prev.fillCircle; }); }; render() { let circles = []; for (var i = 0; i < 3; i++) { circles.push( <img key={i} ); } return ( <div> {circles} </div> );
How to For Loop in React (With Examples), Although we can write a for loop in React, ES6 provides the more We can add state to functional components, therefore I like to always use functional Our functional React component returns a single div element with some JSX inside. a set of <li> tags for each element in the array, thus creating a list:..
@Dille Please try below code this should solve your problem.
this.state = { activeCircle: null }; circleHandler = (i) => { this.setState({ activeCircle: i}); }; render() { let circles = []; for (var i = 0; i < 3; i++) { circles.push( <img key={i} ); } return ( <div> {circles} </div> );
React Design Patterns and Best Practices: Design, build and deploy , Design, build and deploy production-ready web applications using standard The function used to validate the condition receives the props, state, and Loops. A very common operation in UI development is to display lists of items. JSX has been built in such a way that it only abstracts the creation of the elements, In React, this element can have a state. And anytime the state changes, a new React element is created. React compares these elements and figures out what has changed. Then, it reaches out to the real DOM and updates only the changed object. Let’s render the React element inside of the real DOM for us to see.
How to Work with and Manipulate State in React, The state object is an attribute of a component and can be accessed with this can import and use in their application without having to jump through hoops. We can't setState in render() either, because it'll create a circular (setState >render >setState…) loop and, in this case, React will throw an error. To set the initial state, use this.state in the constructor with your ES6 class React.Component syntax. Don’t forget to invoke super() with properties, otherwise the logic in parent ( React
How to loop inside React JSX, If you have a set of elements you need to loop upon to generate a JSX partial, you can create a loop, and then add JSX to an array:. Learn how to loop & output from arrays of data in React. Help spread the word about this tutorial! Iterating and displaying data is a very common part of building applications. In React (and other frameworks), the most basic way of doing this is hard coding the entries into your HTML ( view code ): But what if our names were in an array, and
React Design Patterns and Best Practices, Loops. A very common operation in UI development is to display lists of items. Suppose you have a list of users, each one with a name property attached to it. To create an unordered list to show the users, you can do the following: <ul> we have to show and hide elements according to the state of the application, and. | http://thetopsites.net/article/52735604.shtml | CC-MAIN-2020-34 | refinedweb | 758 | 63.8 |
KTextEditor
#include <commandinterface.h>
Detailed Description
Extension interface for a Command.
Introduction
The CommandExtension extends the Command interface allowing to interact with commands during typing. This allows for completion and for example the isearch plugin. If you develop a command that wants to complete or process text as the user types the arguments, or that has flags, you can have your command inherit this class.
If your command supports flags return them by reimplementing flagCompletions(). You can return your own KCompletion object if the command has available completion data. If you want to interactively react on changes return true in wantsToProcessText() for the given command and reimplement processText().
Definition at line 138 of file commandinterface.h.
Constructor & Destructor Documentation
Virtual destructor.
Definition at line 144 of file commandinterface.h.
Member Function Documentation
Return a KCompletion object that will substitute the command line default one while typing the first argument of the command
cmdname.
The text will be added to the command separated by one space character.
Implement this method if your command can provide a completion object.
- Parameters
-
- Returns
- the completion object or NULL, if you do not support a completion object
Fill in a
list of flags to complete from.
Each flag is a single letter, any following text in the string is taken to be a description of the flag's meaning, and showed to the user as a hint. Implement this method if your command has flags.
This method is called each time the flag string in the typed command is changed, so that the available flags can be adjusted. When completions are displayed, existing flags are left out.
- Parameters
-
This is called by the command line each time the argument text for the command changed, if wantsToProcessText() returns true.
- Parameters
-
- See also
- wantsToProcessText()
Check, whether the command wants to process text interactively for the given command with name
cmdname.
If you return true, the command's processText() method is called whenever the text in the command line changed.
Reimplement this to return true, if your commands wants to process the text while typing.
- Parameters
-
- Returns
- true, if your command wants to process text interactively, otherwise false
- See also
- processText()
The documentation for this class was generated from the following file:
Documentation copyright © 1996-2016 The KDE developers.
Generated on Sat Dec 3 2016 01:32:45 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/4.x-api/kdelibs-apidocs/interfaces/ktexteditor/html/classKTextEditor_1_1CommandExtension.html | CC-MAIN-2016-50 | refinedweb | 409 | 55.95 |
Overview
In this article, I will show you a very easy way to set up a system to play Ogg Vorbis (.ogg) files through the use of the Ogg Vorbis SDK and OpenAL. I choose OpenAL because I want my example code
to be as cross-platform as possible. The example code should compile and run under Windows and Unix/Linux. It should not be too difficult to substitute OpenAL with other audio API such as DirectSound
or fmod. I have included a small sample OGG file (Bomb.ogg) in case you do not have one handy.
What is Ogg Vorbis?
Ogg Vorbis (or just OGG) is an open-source audio compression format similar to MP3. (Actually, the file .ogg file format can contain other things, but let's just assume it is audio data for the
rest of this article.) One of the biggest advantages it has over MP3 is that it is patent-free. This means you do not need to pay a license fee in order to encode or decode OGG files. I don't know
about you, but to me, that is a very big plus!
If you want to know more about Ogg Vorbis, I urge you to read the Ogg Vorbis FAQ.
Getting Started
First, head over to Ogg Vorbis Home to download a copy of the SDK. If you are feeling adventurous, you can even download the source files and compile them
yourself. (Hey, it is open-source!) The SDK is cross-platform, so you can develop your application under Windows or Unix/Linux.
The Ogg Vorbis SDK comes in the form of header files and DLLs (so under Unix/Linux). Just put the header files (ogg/ogg.h, vorbis/vorbis.h, vorbis/vorbisfile.h, and vorbis/vorbisenc.h) and add the
include path to your favorite compiler environment (I use Visual Studio .NET 2003). The DLL (or .so) files (ogg.dll, vorbis.dll, vorbisfile.dll, and vorbisenc.dll) should be somewhere in the PATH.
Under Windows, you will also need to add the import libraries (ogg.lib, vorbis.lib vorbisfile.lib, and vorbisenc.lib) to your project so they can be linked to your application.
As the name of this article implies, I use OpenAL (Open Audio Library) as the underlying API to actually generate the sound through the speakers. There already
exist other resources concerning OpenAL (for example, here), so I will not spend too much time on explaining OpenAL in this
article. I will just assume that you have the OpenAL SDK correctly configured on your system.
Initialization
Here, I will just show the relevant code to setting up OpenAL for audio output. If something looks unfamiliar to you, please feel free to refer to other resources.
#include < AL/al.h > #include < AL/alut.h > #include < vorbis/vorbisfile.h > #include < cstdio > #include < iostream > #include < vector > #define BUFFER_SIZE 32768 // 32 KB buffers using namespace std; int main(int argc, char *argv[]) { ALint state; // The state of the sound source ALuint bufferID; // The OpenAL sound buffer ID ALuint sourceID; // The OpenAL sound source ALenum format; // The sound data format ALsizei freq; // The frequency of the sound data vector < char > bufferData; // The sound buffer data from file // Initialize the OpenAL library alutInit(&argc, argv); // Create sound buffer and source alGenBuffers(1, &bufferID); alGenSources(1, &sourceID); // Set the source and listener to the same location alListener3f(AL_POSITION, 0.0f, 0.0f, 0.0f); alSource3f(sourceID, AL_POSITION, 0.0f, 0.0f, 0.0f);
Decoding OGG files
Opening file for binary reading
At this point, the system is all ready to go. The one thing that is missing is the actual sound data! OK, let's write a function that can load OGG files into memory.
void LoadOGG(char *fileName, vector < char > &buffer, ALenum &format, ALsizei &freq) { int endian = 0; // 0 for Little-Endian, 1 for Big-Endian int bitStream; long bytes; char array[BUFFER_SIZE]; // Local fixed size array FILE *f; // Open for binary reading f = fopen(fileName, "rb");
Up to this point, things should look very familiar. The function simply uses the fopen() function to open the given file for binary reading.
Opening file for decoding
Next, we declare some variables that the Ogg Vorbis SDK uses.
vorbis_info *pInfo; OggVorbis_File oggFile;
Then comes the act of passing control over to the SDK. Note that there is no need to call fclose() anymore once this is done.
ov_open(f, &oggFile, NULL, 0);
Information retrieval
After opening the file for decoding, we can extract a little bit of information about the compressed audio data in the file. At the very least, we need to know the number of channels (1 for mono
and 2 for stereo) and the sampling frequency of the audio data. We can do it like this:
// Get some information about the OGG file pInfo = ov_info(&oggFile, -1); // Check the number of channels... always use 16-bit samples if (pInfo->channels == 1) format = AL_FORMAT_MONO16; else format = AL_FORMAT_STEREO16; // end if // The frequency of the sampling rate freq = pInfo->rate;
Decoding the data
Now we are ready to decode the OGG file and put the raw audio data into the buffer. We use a fixed size buffer and keep on reading until there is no more data left, like this:
do { // Read up to a buffer's worth of decoded sound data bytes = ov_read(&oggFile, array, BUFFER_SIZE, endian, 2, 1, &bitStream); // Append to end of buffer buffer.insert(buffer.end(), array, array + bytes); } while (bytes > 0);
Clean up
Now all the audio data has been decoded and stuffed into the buffer. We can release the file resources (resource leaks are bad!).
ov_clear(&oggFile); }
Note that there is no need to call fclose(). It is already done for us. Neat.
Playing the sound
It is now time to get back to our main(). The next step is to upload the raw audio data to the OpenAL sound buffer and attach the buffer to the source.
// Upload sound data to buffer alBufferData(bufferID, format, &bufferData[0], static_cast < ALsizei > (bufferData.size()), freq); // Attach sound buffer to source alSourcei(sourceID, AL_BUFFER, bufferID);
Finally! We are ready to play the sound! Let's do that!
// Finally, play the sound!!! alSourcePlay(sourceID); // This is a busy wait loop but should be good enough for example purpose do { // Query the state of the souce alGetSourcei(sourceID, AL_SOURCE_STATE, &state); } while (state != AL_STOPPED);
After the sound is finished playing, we should clean up.
// Clean up sound buffer and source alDeleteBuffers(1, &bufferID); alDeleteSources(1, &sourceID); // Clean up the OpenAL library alutExit(); return 0; } // end of main
We are done!
To run the example program, just supply the name of the OGG file you want to play. For example, "SimpleOGG
Bomb.ogg"
Conclusion
Ogg Vorbis is a very nice alternative to the MP3 audio compression format. Its biggest selling point is that it is patent-free. Using the Ogg Vorbis SDK and OpenAL, it is very easy to add the
ability to play OGG files in an application, as this article has demonstrated. I hope this article has been useful to you.
Obviously, there is more to Ogg Vorbis than what I have shown you in this article. For example, you can program an OGG encoder right in your application. For long background music, you should also
consider streaming the OGG data rather than loading everything into one big chunk. Given a typical 1:10 compression ratio, a piece of 5-minute music can easily eat up 50+ MB of memory if the entire
file is decoded! There won't be a lot of room left for other things! These are topics best left for future articles.
TangentZ
tangentz@hotmail.com | http://www.gamedev.net/page/resources/_/technical/game-programming/introduction-to-ogg-vorbis-r2031 | CC-MAIN-2015-18 | refinedweb | 1,275 | 64.41 |
You can't do text processing on a control like that, but you shouldn't need to since the property control will output the xhtml from the editor which should already be encoded. Does the html source of the rendered page seem to be encoded correctly if you view it in the browser?
I was so sure the editor encoded the chars, but I tried it now and it doesn't. The problem is you can't do htmlencode on the whole xhtml-property because you will also encode the HTML and see "<p>" etc in the output whilst losing the formating information.
What you need to get tinyMCE to encode the chars is to set its init option "entity_encoding" to "numeric". There is probably a simpler way to do this, but the only thing I can think of is to create a plugin for tinyMCE which does this.
Do it by creating a class and decorating it with the EPiServer.Editor.TinyMCE.TinyMCEPluginNonVisual attribute where you specify the option. I uploaded a code sample:
As noted there I don't know the side effects.
Hm ok, thank you! It just seems a bit strange that this problem hasnt come up before (or maybe it has). Is it so far fetched to be able to develop an Epi template that an editor can use to make a newsletter page and then send it via Outlook.
Iam not blaiming epi here though. We had a newsletter before that we coded in html in notepad+, we had to encode åäö etc for it to display properly in outlook. So I guess the same thing applys when a page is done in Epi. But is there no way around it?
Can I build something so the webserver sends the mail with all the images?
Hi Henrik,
I think in the code behind while saving the content it is saved in Encoded format as a result when the page is fetched again the encoded text is binded to the page. By saying this I mean that somewhere while setting the property in the code behind file you might have coded as Server.HTMLEncode(XHTML edtor control.Text). So the encoded content is published in the page .
Regards,
S.K. SreeRaghavendra
Sreeraghavendra SK: Thank you, but I dont really understand, sorry. Iam rather new to this.
I did some testing however. Just created an ordinary html file in my project and gave it meta charset=utf-8, and saved it with Unicode (UTF-8 without signature) - Codepage 65001, the page has some swedish characters in a p tag. The page is displayed fine in Outlook! But when I do the same with my masterpage and the one and only template it wont work - the swedish characters get messed up in Outlook.
Hi Sreeraghavendra SK.
Hm, I didnt write any code behind in particular for that aspx page. I thougt it would be enough to just write the <%= Server.HTMLEncode() %> in the aspx file? Maybe not though? He he. As I said, Iam rather new to this.
Here is the actual example by the way.
# In the aspx file, NewsLetterCulturumStart.aspx, I have a property, it looks like this:
<EPiServer:Property in edit mode it is a xhtml edit box.
# The code behind file, NewsLetterCulturumStart.aspx.cs, have this code (wich I believe is the default code for a newly created template):
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using EPiServer;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Web.WebControls;
namespace NYK.NewsLetter.Pages
{
public partial class NewsLetterCulturumStart : EPiServer.TemplatePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
One question I have! To use the code <%= Server.HTMLEncode() %> in the aspx file (for anything) you have to write code behind code? Very important question! Because I thougnt that <% ... %> meant that it was enough to have the code in the aspx file only. Like this for instance worked fine, just in the aspx file:
<% if(CurrentPage.LanguageBranch.ToString()=="sv"){ %>
<% } else { %>
<% } %>
Thank you very much and maybe we can take it from here. =)
Hi Henrik,
You can also add the HTMLEncode text in the aspx page as well. you can add it as:
<%=HttpContext.Current.Server.HtmlEncode("some string text")%>
But in case you want the swedish alphabets to get displayed as it is instead of the encoded values.... you need to use Server.HtmlDecode instead of HtmlEncode.
Hope this helps. :)
Regards,
S.K. SreeRaghavendra
Hi Sreeraghavendra SK! Ok thank you. Yeah I tried
<%=HttpContext.Current.Server.HtmlEncode("some string text")%>
with ÅÄÖ åäö in the string and the source code displayed their code: Å Ä Ö å ä ö
So, wouldnt it be far fetched to be able to use this thing to make every "swedish character" (ÅÄÖ åäö) to get converted to the respective code? Is it something I can do in the code behind file, you think?
I see that you mention I should use decode instead of encode, why?
For fun I tested <%=HttpContext.Current.Server.HtmlDecode("Å")%> and I had expected a Å in the source code for the page but no, just Å.
But anyway, some how, in the code behind file, you have a solution so every swedish character get coded in the unicode(?) numbers - thus will be displayed correctly in outlook?
Hi!
Is there a way to use HTMLEncode like this?
<%= Server.HTMLEncode("<EPiServer:Property") %>
What I want to do is find a way to convert åäö ÅÄÖ to html-code for the text that editors write in an XHTML edit box. Maybe there is another way?
The problem I have is that I'am working on a newsletter template, the editor work with it and then, in IE, use the "Send page as mail" function. But the swedish characters get messed up (I have tried different charset) in Outlook.
Thanks! | https://world.episerver.com/forum/developer-forum/Developer-to-developer/Thread-Container/2011/8/ServerHTMLEncode-for-a-property/ | CC-MAIN-2020-29 | refinedweb | 987 | 76.11 |
What kind of exception below Java program will throw?
class Test{
int i=10;
public void disp(){
System.out.println("i val is.."+i);
}
}
public class ExceptionDemo {
public static void main(String[] args) {
Test t=null;
t.disp();
}
}
It will not throw any exception, but it may give compile time error.
It will throw NullPointerException, which is a checked exception.
It will throw, NullPointerException, which is an un-checked exception.
it will print i val is..10
Here Test t=null; and we are trying to access t.disp() which is potentially doing null.disp() which will throw NullPointerException, and this is an un-checked exception, which we have to debug and fix rather than handling it by try-catch block.
Back To Top | http://skillgun.com/question/3014/java/exceptions/what-kind-of-exception-below-java-program-will-throw-class-test-int-i10-public-void-disp-systemoutprintlni-val-isi-public-class-exceptiondemo-public-static-void-mainstring-args-test-tnull-tdisp | CC-MAIN-2016-30 | refinedweb | 124 | 70.7 |
Validating REST API using Spring
In this post, we will discuss in details of Validating REST API using Spring. It is important to validate incoming data in the REST web services that can cause trouble in the business process or logic. Read our previous article, for understanding basics of building REST API using Spring.
Introduction
When building REST API, we expect RESTful service to have a certain structure or format. We expect REST API request to follow this structure and constraints. We can not assume that API request will follow structure and constraints. How to handle if REST request is not meeting constraints.
We need to think about following questions while designing our REST API.
- How should I validate REST API data?
- What message should I send if data validation fails?
One of the fundamental principles of RESTful services is to think about “Consumers” while designing your REST web services. We should keep in mind below design principles for validating REST API in Spring.
- REST API should return a clear message indicating what was wrong int he request.
- API should try to provide information on what can be done to fix the error.
- Well defined response status.
Spring MVC provides a number of build in options for REST API date validation. We will cover different options in this post.It is up to your requirement to determine which approach fulfill your use case.
1. Simple Spring MVC Validation
If our REST API is using @RequestParam or @PathVaraible, Spring provides out of the box support for validating it. Here is a simple use case for validating REST data using Spring
@GetMapping("/greeting") public Greeting sayHello(@RequestParam(value = "name") String name){ return new Greeting(1, "Hello "+name); }
This is the simplest validation provided by Spring MVC. It will validate incoming request. Spring will send a detailed message back to the consumer in case we are missing required data in the REST API.
If we run our application without passing name in the request parameter, Spring will send a detailed error response back to the consumer.
{ "timestamp": 1517983914615, "status": 400, "error": "Bad Request", "exception": "org.springframework.web.bind.MissingServletRequestParameterException", "message": "Required String parameter 'name' is not present", "path": "/greeting" }
We will talk about customizing error response in our exception handling post.
2. REST Validation using Bean Validation (JSR303)
Real life REST API’s are more complex than a simple method with few parameters. Enterprise REST API involve complex domain models and also require the ability to validate REST API data.
Spring MVC provides build in support for JSR303 (Bean Validation). Bean Validation comes with an extensive list of validation available out of the box along with the ability to create custom validations.
With Spring Bean Validation support, we need to annotate out DTO with required annotations and build in validation support will ensure to validate incoming data before passing it to our business layer.
For the list of build in validation, please refer to Hibernate Validator.
Here is our sample customer DTO
public class Customer { @NotNull(message = "Please provide first Name") private String firstName; @NotNull(message = "Please provide last Name") private String lastName; @NotNull @Min(value = 18, message = "Age should be equal or more than 18") private int age; @Email(message = "Please provide valid email address") private String email;Email() { return email; } public void setEmail(String email) { this.email = email; } }
before we move ahead, let’s discuss what we are trying to validate in our DTO
- We will not accept null values for firstName and lastName (You can also add @notEmpty annotation from Hibernate validator)
- Age should not be null and should be greater than or equal to 18.
- We need a valid email address for the customer.
Bean Validation provides us a way not only to validate REST API request but also provide consumer-centric error messages.
We are using the hard-coded message in the class itself, but Spring provides the way to use a localized properties file for localized messages.
@RestController @RequestMapping("/api/rest") public class CustomerController { @PostMapping("/customer") public ResponseEntity<?> createCustomer(@Valid @RequestBody Customer customer){ HttpHeaders responseHeader = new HttpHeaders(); return new ResponseEntity<>(customer, responseHeader, HttpStatus.CREATED); } }
If we run our code, with following input
{"firstName":"Umesh","lastName":null,"age":"18","email":"[email protected]"}
We will get following response back from our REST API.
timestamp": 1518066946111, "status": 400, "error": "Bad Request", "exception": "org.springframework.web.bind.MethodArgumentNotValidException", "errors": [], "message": "Validation failed for object='customer'. Error count: 1", "path": "/api/rest/customer"
If we will send all values in correct format and data type, REST API will send success response back to the consumer
<
HTTP : 201 Created { "firstName": "Umesh", "lastName": "Awasthi", "age": 18, "email": "[email protected]" }
3. Custom Spring Validator
JSR 303 bean validation provides a number of out of the box validator. For enterprise applications, we will get into a situation where out of the box validator will not fulfill our business requirements.
Spring provides flexibility to create our own custom validator and uses these custom validations. Please read Spring MVC Custom Validator for more detail.
You can use same domain object for different endpoints. Let’s take the example of our customer.
- If we are creating a new customer, we do not need customer id and it can be null.
- For updating customer, we need customer id to identify customer for the update.
For such use cases, you don’t need 2 separate objects but can use Grouping constraints feature provided by JSR 303.
Summary
In this post, we discussed different options for Validating REST API using Spring. Validating data is essential for the Spring REST API. Data validation perform data sanity and provide additional security check for data insertion.
We discussed build in validation support from Spring and Spring MVC along with an option to create customer validator in Spring if out of the box validator is not sufficient for the business needs.
In our next articles on building REST API with Spring, we will discuss REST Resource Naming Best Practices. | https://www.javadevjournal.com/spring/spring-rest-api-validation/ | CC-MAIN-2021-43 | refinedweb | 993 | 54.22 |
Details
- Type:
Improvement
- Status:
Closed
- Priority:
Minor
- Resolution: Duplicate
- Affects Version/s: None
- Fix Version/s: 1.6.5, 1.7.0-beta1
- Component/s: None
- Labels:None
- Number of attachments :
Description
A long requested feature has been to be able to rename featureTypes, as datastores like ArcSDE can have long kind of nasty names, and often people just want something more friendly than what's in their database. Right now we make people use a view.
There is now code to rename features, used in the WFS datastore, that can actually accomplish this. We should make use of it. A UI configuration would obviously be ideal, but is a bit ambitious with our current stuff. Instead we can just make this an option for power users, by making it a configuration option only in info.xml. Call it something like displayName or outputName
Activity
Yeah, this has been a long requested feature, and indeed has had a few patches, but they only worked against WMS. We should find those issues and link them to this one.
This is just a trivial case of the community-schema support, all we would need to do would be to allow a internal feature model to be propagated from the wrapped data store.
And you would get the ability to rename any attributes, or put them into externally defined namespaces (eg gml:name) for free.
Adding configuration options will increase the hurdle for backwards compatibility.
Indeed using community-schema datastore would give all those benefits out of the box.
Yet, the drawback being it can't handle transactions.
I'd suggest, for the time being, if FT aliasing is a short term need, to use a very simple wrapper, yet isolating the functionality enough to easy the transition to community-schema datastore whenever we're able to
a) have a ui for it. Even if its not for the full community-schema capabilities but just for aliasing attribute names
b) unroll transactions over the community-schema ds to the underlying one(s). (Someday I'd like to get this out of the box by the use of hibernate-spatial or similar)
This is a great idea. Especially for KML when the feature type names are long and obscure, they start to look crazy in google earth. | http://jira.codehaus.org/browse/GEOS-1366 | CC-MAIN-2014-15 | refinedweb | 383 | 59.64 |
Interrog:
__published
-promiscuous
forcetype
The first method is the most common approach. It is conventional to define a PUBLISHED macro that will expand to public when compiling the C++ code and __published macro when parsing the source with Interrogate, as follows:
PUBLISHED
public
// dtoolbase.h defines the PUBLISHED macro if the CPPPARSER macro is defined
#include "dtoolbase.h"
class MyBufferClass {
PUBLISHED:
// This method is publicly accessible to Python and C++
void set_data(const string &str);
public:
// C++-only method
char *get_buffer();
};.
-s.
-S
There are a few steps involved in generating Python wrappers using interrogate.
interrogate -module test -oc test_igate.cxx -od test.in -python-native test.h
interrogate_module -module test -oc test_module.cxx -python-native test.in
-module.
-python-native
-module test.
Interrogate provides a selection of several interface makers:
You can also specify a combination of any of those. If all are omitted, the default is -c. | https://www.panda3d.org/manual/index.php/Interrogate | CC-MAIN-2018-09 | refinedweb | 149 | 52.36 |
view raw
So I am trying to learn Spark using Python (Pyspark). I want to know how the function
mapPartitions
[ [1, 2, 3], [3, 2, 4], [5, 2, 7] ]
mapPartitions
mapPartition should be thought of as a map operation over partitions and not over the elements of the partition. It's input is the set of current partitions its output will be another set of partitions.
The function you pass map must take an individual element of your RDD
The function you pass mapPartition must take an iterable of your RDD type and return and iterable of some other or the same type.
In your case you probably just want to do something like
def filterOut2(line): return [x for x in line if x != 2] filtered_lists = data.map(filterOut2)
if you wanted to use mapPartition it would be
def filterOut2FromPartion(list_of_lists): final_iterator = [] for sub_list in list_of_lists: final_iterator.append( [x for x in sub_list if x != 2]) return iter(final_iterator) filtered_lists = data.mapPartition(filterOut2FromPartion) | https://codedump.io/share/wkQ0TU8qN5WM/1/how-does-the-pyspark-mappartitions-function-work | CC-MAIN-2017-22 | refinedweb | 164 | 54.02 |
So, I just recently deleted my previous post from last night and I've been working with it to consolidate and try to touch up my screw-ups...boo...
Anywho, I am basically trying to read in values from .dat files from a folder that is in the current directory of the program. I am running Linux if that matters...
So, kind instructions to those who are willing to help:
1.) make a new directory in your home folder "FOLDER", make a folder named "DATA" inside "FOLDER", and then make up two .dat files with whatever integers you want, and however many integers you want.
2.) Next, copy and paste this .cpp code into "FOLDER" and try compiling/running.
The instructions I have told you are exactly where my .dat files are and my .cpp code. When I run the program, I get this error:
What is wrong with it? I don't understand...What is wrong with it? I don't understand...Enter directory with files available for use: InputFiles/
Error(2) opening InputFiles/
Here is my code, and I apologize sincerely for the long post. If you see any errors (which I'm sure there will be plenty!!), do not be bashful. Let me know! Oh, and my CalcMax() function isn't complete FYI, but I can do that on my own time. If you are using Windows/Mac, please change the instructions as necessary...Thank you in advance for all the help!!! Let me know ASAP please!
Code:#include <sys/types.h> #include <dirent.h> #include <errno.h> #include <vector> #include <string> #include <iostream> #include <fstream> #include <cstdlib> #include <cstring> using namespace std; typedef vector<string> stringVector; //Defines a vector of string values const int MAX_SIZE = 31; void OpenInputFile(ifstream&, string); void OpenOutputFile(ofstream&, string); int ReadArray(ifstream&, int[]); float CalcAverage(int[], int array_size); float CalcMax(int array[], int array_size); int getDir(string dir, stringVector &files);] << endl; indiv_file.open((dir + files[i]).c_str()); /*if (indiv_file.fail()) { cout << "Fail"; return 0; }*/ OpenInputFile (indiv_file, (dir+files[i])); array_size = ReadArray(indiv_file, array); average_temp = CalcAverage(array, array_size); //maximum_temp = CalcMax(array, array_size); while (indiv_file >> array[count]) { cout << array[count]; count++; if(count == MAX_SIZE) break; } for (int j = 0; j < array_size; j++) { cout << array[j] << " "; } } indiv_file.close(); } return 0; } //-------------------------------- int getDir (string dir, stringVector &files) { DIR *dp; struct dirent *dirp; if((dp = opendir(dir.c_str())) == NULL) { cout << "Error(" << errno << ") opening " << dir << endl; return errno; } while ((dirp = readdir(dp)) != NULL) { files.push_back(string(dirp->d_name)); } closedir(dp); return 0; } //--------------------------------------- void OpenInputFile(ifstream &in_file, string file_name) { in_file.open(file_name.c_str()); if (in_file.fail()) { cout << "Failed to open file." << endl; exit(1); } } | https://cboard.cprogramming.com/cplusplus-programming/114341-reading-dat-files-folder-current-directory.html?s=9d9490820633c1abaaa8ab1668c9c0e1 | CC-MAIN-2019-43 | refinedweb | 436 | 59.8 |
import "github.com/elves/elvish/pkg/cli/addons/listing"
Package listing provides the custom listing addon.
Start starts the custom listing addon.
type Config struct { // Keybinding. Binding cli.Handler // Caption of the listing. If empty, defaults to " LISTING ". Caption string // A function that takes the query string and returns a list of Item's and // the index of the Item to select. Required. GetItems func(query string) (items []Item, selected int) // A function to call when the user has accepted the selected item. If the // return value is true, the listing will not be closed after accpeting. // If unspecified, the Accept function default to a function that does // nothing other than returning false. Accept func(string) bool // Whether to automatically accept when there is only one item. AutoAccept bool }
Config is the configuration to start the custom listing addon.
type Item struct { // Passed to the Accept callback in Config. ToAccept string // How the item is shown. ToShow ui.Text }
Item is an item to show in the listing.
Package listing imports 2 packages (graph) and is imported by 1 packages. Updated 2019-12-31. Refresh now. Tools for package owners. | https://godoc.org/github.com/elves/elvish/pkg/cli/addons/listing | CC-MAIN-2020-16 | refinedweb | 190 | 60.31 |
Brick::Profile - the validation profile for Brick
This class turns a profile description into a ready-to-use profile object that has created all of the code it needs to validate input. In Brick parlance, it creates the bucket and the bricks that need to go into the bucket based on the validation description.
The validation profile is an array of arrays. Each item in the array specifies three things: a label for that item, the name of the method to run to validate the item, and optional arguments to pass to the the method.
For instance, here's a simple validation description to check if a user is registered with the system. This profile has one item:
@profile = ( [ username => is_registered => { field => form_name } ], );
The label for the item is
username. When Brick reports the results of the validation, the label
username will be attached to the result for this part of the validation.
The method that validates this item is
is_registered. When you create the profile, Brick will look for that method in either it's included methods in Brick::Bucket classes or the ones you load with
Brick::add_validator_packages. This method is called a "brick" because it's one piece of the entire validation.
Additionally, Brick will pass the optional arguments, in this case
{ field = form_name }>, to
is_registered. A brick merely creates a closure that will run later, so the optional arguments are for the initialization of that closure. The validation doesn't happen until you
apply it.
Create a new profile object tied to the Brick object.
Return the class name to use to access class methods (such as bucket_class) in the Brick namespace. If you want to provide an alternate Brick class for your profile, override this method.
Examine the profile and complain about irregularities in format. This only checks the format; it does not try to determine if the profile works or makes sense. It returns a hash whose key is the index of the profile element and whose value is an anonymous hash to indicate what had the error:
format - the element is an arrayref name - the name is a scalar method - is a code ref or can be found in the package $brick->bucket_class returns args - the last element is a hash reference
If the profile is not an array reference,
lint immediately returns undef or the empty list. In scalar context,
lint returns 0 for format success and the number of errors (so true) for format failures. If there is a format error (e.g. an element is not an array ref), it immediately returns the number of errors up to that point.
my $lint = $brick->profile_class->lint( \@profile ); print do { if( not defined $lint ) { "Profile must be an array ref\n" } elsif( $lint ) { "Did not validate, had $lint problems" } else { "Woo hoo! Everything's good!" } };
In list context, it returns a hash (a list of one element). The result will look something like this hash, which has keys for the elements that lint thinks are bad, and the values are anonymous hashes with keys for the parts that failed:
%lint = ( 1 => { method => "Could not find method foo in package", }, 4 => { args => "Arguments should be a hash ref, but it was a scalar", } );
If you are using
AUTOLOAD to generate some of the methods at runtime (i.e. after
lint has a chance to check for it), use a
can method to let
lint know that it will be available later.
TO DO:
Errors for duplicate names?
Turn the profile into a textual description without applying it to any data. This does not add the profile to instance and it does not add the constraints to the bucket.
If everything goes right, this returns a single string that represents the profile.
If the profile does not pass the
lint test, this returns undef or the empty list.
If you want to do something with a datastructure, you probably want to write a different method very similar to this instead of trying to parse the output.
Future notes: maybe this is just really a dispatcher to things that do it in different ways (text output, hash output).
If you don't want to use this class, you can specify a different class to use in your Brick subclass. Override the Brick::profile_class() method to specify the name of the class that you want to use instead. That might be a subclass or an unrelated class. Your class will need to use the same interface even though it does things differently.
TBA
Brick::Tutorial, Brick::UserGuide
This source is in Github:
brian d foy,
<bdfoy@cpan.org>
You may redistribute this under the terms of the Artistic License 2.0. | http://search.cpan.org/dist/Brick/lib/Brick/Profile.pm | CC-MAIN-2018-22 | refinedweb | 785 | 68.6 |
Build a Secure To-Do App with Vue, ASP.NET Core, and Okta
I
localhost:5000. } })
This file sets up Vue, and serves as the main entry point (or starting point) for the whole JavaScript application.
Next, create
router.js:
import Vue from 'vue' import Router from 'vue-router' import store from './store' import Dashboard from './components/Dashboard' Vue.use(Router) const router = new Router({ mode: 'history', base: __dirname, routes: [ { path: '/', component: Dashboard } ] }) export default router
The Vue router keeps track of what page the user is currently viewing, and handles navigating between pages or sections of your app. For now, this file sets up the router with only one path
/ and associates it with a component called Dashboard.
You might be wondering what
store and
Dashboard"> <template v- <h2>Welcome!</h2> <p>Log in to view your to-do list.</p> </template> <template v- <h2>{{name}}, here's your to-do list</h2> <input class="new-todo" autofocus <ul class="todo-list"> <todo-item</todo-item> </ul> <p>{{ remaining }} remaining</p> </template> </div> </template> <script> import TodoItem from './TodoItem' export default { components: { TodoItem }, computed: { name () { if (this.$parent.userInfo) { return this.$parent.userInfo.given_name } else { return 'Hello' } },', { $auth: this.$auth,. Don’t worry about
$store and
$auth yet. You’ll add these pieces in a few minutes.> export default { props: ['item'], methods: { toggleTodo (data) { data.$auth = this.$auth this.$store.dispatch('toggleTodo', data) }, deleteTodo (data) { data.$auth = this.$auth this.$store.dispatch('deleteTodo', data) } } } < one.
The Dashboard and TodoItem components (and the router configuration) refer to something called
store or
$store. I’ll explain what the store is, and how to build it, in the next section. Later, you’ll also add
$auth, which is a plugin that keeps track of whether a user is currently logged in. Before you get there, you need to build one more component.
Create a file called
App.vue in the
components folder:
<template> <div class="app-container"> <div class="app-view"> <router-view /> <template v- <button v-on:Log out</button> </template> <template v-else> <button v-on:Log in</button> </template> </div> </div> </template> <script> export default { name: 'app', data: function () { return { authenticated: false, userInfo: null } }, created () { this.checkAuthentication() }, watch: { // Every time the route changes, check the auth status '$route': 'checkAuthentication' }, methods: { async checkAuthentication () { let previouslyLoggedIn = this.authenticated this.authenticated = await this.$auth.isAuthenticated() let justLoggedIn = !previouslyLoggedIn && this.authenticated if (justLoggedIn) { this.$store.dispatch('getAllTodos', { $auth: this.$auth }) this.userInfo = await this.$auth.getUser() } let justLoggedOut = previouslyLoggedIn && !this.authenticated if (justLoggedOut) { this.userInfo = null this.$store.commit('clearTodos') } }, async logout () { await this.$auth.logout() await this.checkAuthentication() // Navigate back to home this.$router.push({ path: '/' }) } } } <; min-height: 200px; padding: 20px 25px 15px 25px; margin: 30px; position: relative; box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 5px 10px 0 rgba(0, 0, 0, 0.1); } </style>
The App component is responsible for two things:
- Providing the base HTML and CSS used by the app.
- Keeping track of whether the user is logged in, using the
$authplugin. (This will be covered a little later.)
The
<router-view> element provides a place to render the Vue router’s active route. Right now, there’s only one route:
/ which will render the Dashboard component in the
<router-view>.
Navbars and other UI elements that should exist outside of the current router view can be placed in this component. For now, the component will just show a simple button to log in or out, depending on the value of the
authenticated variable in the component code.
How does Vue know that the App component should be used as the “base” HTML and CSS for the app? If you look back at
boot-app.js, you’ll see this line:
import App from './components/App'
This statement loads the App component, which is then passed to Vue in
new Vue(...). This tells Vue that it should load the App component first.
You’re all done building components! It’s time to add some state management and authentication. First, I’ll explain what state management is and why it’s useful.
Add Vuex for state management
Components are a great way to break up your app into manageable pieces, but when you start passing data between many components, it becomes, all. The real meat of Vuex is in mutations and actions, but you’ll write those in separate files to keep everything organized.
Create a file called
mutations.js:
export const state = { todos: [] } export const mutations = { loadTodos(state, todos) { state.todos = todos || []; }, clearTodos(state) { state.
This app uses the Vuex store to keep track of the to-do list (the
state.todos array). The Dashboard component accesses this data with computed properties like:
todos () { return this.$store.state.todos },
The mutations defined here are only half the story, because they only handle updating the state after an action has run. Create another file called
actions.js:
import axios from 'axios' export const actions = { async getAllTodos({ commit }, data) { // Todo: get the user's to-do items let fakeTodoItem = { text: 'Fake to-do item' } commit('loadTodos', [fakeTodoItem]) }, async addTodo({ dispatch }, data) { // Todo: save a new to-do item await dispatch('getAllTodos', data.$auth) }, async toggleTodo({ dispatch }, data) { // Todo: toggle to-do item completed/not completed await dispatch('getAllTodos', data.$auth) }, async deleteTodo({ dispatch }, data) { // Todo: delete to-do item await dispatch('getAllTodos', data.$auth) } } mutation with the real items returned from the API.
Add identity and security with Okta
Okta is a cloud-hosted identity API that makes it easy to add authentication, authorization, and user management to your web and mobile apps. You’ll use it in this project to:
- Add login to the Vue app
- Require authentication on the backend API
- Store each user’s to-do items securely
To get started, sign up for a free Okta Developer account. After you activate your new account (called an Okta organization, or org), click Applications at the top of the screen. Choose Single-Page App and click Next. Change the base URI to, and’ll connect your frontend code (the Vue app) to Okta.
Add the Okta Vue SDK
The Okta Vue SDK makes it easy to add Okta authentication to your Vue app. Add it with
npm:
npm install --save @okta/okta-vue
Once it’s installed, update
router.js and some new code (highlighted here with comments):
import Vue from 'vue' import Router from 'vue-router' import store from './store' import Dashboard from './components/Dashboard' // Import the Okta Vue SDK import Auth from '@okta/okta-vue' Vue.use(Router) // Add the $auth plugin from the Okta Vue SDK to the Vue instance Vue.use(Auth, { // Replace this with your Okta domain: issuer: 'https://{yourOktaDomain}/oauth2/default', // Replace this with the client ID of the Okta app you just created: client_id: '{clientId}', redirect_uri: '', scope: 'openid profile email' }) const router = new Router({ mode: 'history', base: __dirname, routes: [ { path: '/', component: Dashboard }, // Handle the redirect from Okta using the Okta Vue SDK { path: '/implicit/callback', component: Auth.handleCallback() }, ] }) // Check the authentication status before router transitions router.beforeEach(Vue.prototype.$auth.authRedirectGuard()) export default router
Replace
{yourOktaDomain} with your Okta org URL, which you can find on the Dashboard page in the Developer Console. Next, paste the Client ID you copied from the application you created a minute ago into the
client_id property.
Try it out: run the server with
dotnet run and try logging in with the email and password you used to sign up for Okta:
The Log in button uses the Okta Vue SDK to redirect to your Okta organization’s hosted login screen, which then redirects back to your app with tokens that identify the user. The
/implicit/callback route you added to the router handles this redirect from Okta and calls the
Auth.handleCallback() function in the Okta Vue SDK. This function takes care of parsing the tokens and letting your app know that the user logged in.
Tip: If you need to fix bugs or make changes in your JavaScript code, you don’t need to stop and restart the server with
dotnet run again. As soon as you modify any of your Vue or JavaScript files, the frontend app will be recompiled automatically. If you make a change to the Dashboard component (for example), it’ll appear instantly in the browser (almost like magic).
Try logging in, refreshing the page (you should still be logged in!), and logging out. That takes care of authenticating the user on the frontend! Later, you’ll update the store to make secure, authenticated calls to your backend API using the same tokens you just obtained.
Great job so far! You’ve set up Vue.js, built components and routing, added state management with Vuex, and added Okta for authentication. The next step is adding the backend API with ASP.NET Core. Grab a refill of coffee and let’s dive in!
Build an API with ASP.NET Core
The user’s to-do items will be stored in the cloud (via Okta).
- A pair of controllers in the aptly-named Controllers folder.
In ASP.NET Core, Controllers handle requests to specific routes in your backend application soon, to your controllers. }, data) { let response = await axios.get('/api/todo') if (response && response.data) { let updatedTodos = response.data commit('loadTodos', updatedTodos) } },
The new action code uses the axios library to make a request to the backend on the
/api/todo route, which will be handled by the
GetAllTodos method on the backend may be fake, but you’ve successfully connected the backend and frontend! The final step is to add data storage and token authentication to the app. You’re almost there!
Add token authentication to the API
When the Okta Vue SDK handles a login via Okta, it saves a token called an access token in your frontend app. You can attach this access token to calls to your backend API to make them secure. Before you do that, you have to tell your ASP.NET Core project to use token authentication. Open up the
Startup.cs file and add this code to the
ConfigureServices method:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = "https://{yourOktaDomain}/oauth2/default"; options.Audience = "api://default"; });
Make sure you replace
yourOktaDomain with your Okta Org URL (find it in the top-right of your Okta developer console’s Dashboard).
You’ll]")] // Add this attribute: [Authorize] public class TodoController : Controller { // Existing code... }
With the code you’ve added to the
Startup class, plus the
[Authorize] attribute on the controller, requests to
/api/todo now require a valid access token to succeed. If you tried running the app now and looking at your browser’s network console, you’d see a failed API request:
Since your frontend code isn’t yet attaching a token to the request, the
TodoController is responding with 401 Unauthorized (access denied).
Open up
actions.js once more and add a small function at the top that attaches the user’s token to the HTTP
Authorization header:
const addAuthHeader = async (auth) => { return { headers: { 'Authorization': 'Bearer ' + await auth.getAccessToken() } } }
Then, update the code that calls the backend in the
getAllTodos function:
let response = await axios.get('/api/todo', await addAuthHeader(data.$auth))
The Okta Vue SDK (the
$auth plugin) isn’t available in the context of the store, so it’s being passed in as part of the
data payload when the action is dispatched. You can see how this works in
App.vue:
if (justLoggedIn) { this.$store.dispatch('getAllTodos', { $auth: this.$auth }) // ...
Refresh the browser (or start the server) and the request will succeed once again, because the frontend is passing a valid token.
Add the Okta .NET SDK
Almost done! The final task is to store and retrieve the user’s to-do items in the Okta custom profile attribute you set up earlier. You’ll use the Okta .NET SDK to do this in a few lines of backend code.
Stop the
dotnet server (if it’s running), and install the Okta .NET SDK in your project: = "https://{yourOktaDomain}",ktaDomain continues...? It’s time to replace it with a new service that uses Okta to store the user’s to-do items. Create
OktaTodoItemService.cs in the Services folder: only store primitives likes strings and numbers, but you’re using the
TodoModel type to represent to-do items. This service serializes the
TodoModel }, await addAuthHeader(data.$auth)) await dispatch('getAllTodos', { $auth: data.$auth }) }, async toggleTodo({ dispatch }, data) { await axios.post( '/api/todo/' + data.id, { completed: data.completed }, await addAuthHeader(data.$auth)) await dispatch('getAllTodos', { $auth: data.$auth }) }, async deleteTodo({ dispatch }, data) { await axios.delete('/api/todo/' + data.id, await addAuthHeader(data.$auth)) await dispatch('getAllTodos', { $auth: data.$auth }) }
Start the server once more with
dotnet run and try adding a real to-do item to the list:
Build Secure Apps with ASP.NET Core and Vue.js out some other recent posts:
- The Lazy Developer’s Guide to Authentication with Vue.js
- Build a Cryptocurrency Comparison Site with Vue.js
Happy coding! | https://developer.okta.com/blog/2018/01/31/build-secure-todo-app-vuejs-aspnetcore | CC-MAIN-2019-22 | refinedweb | 2,177 | 58.58 |
This is the code for CHIRP's internal web applications. The apps are hosted on Google's App Engine, under the 'chirpradio' project. For the chirpradio developer dashboard, go to: For the end-user landing page, go to: Helpful documentation: * App Engine Python API * Django 1.0: Be sure you are looking at the right version of the book! We are using version 1.0. CODING CONVENTIONS ================== Please follow the conventions outlined in PEP 8. OVERVIEW OF THE TREE ==================== There are part of the common infrastructure. djzango.zip Django 1.0.2-final, zipped up. We never want to change this. appengine_django/ From google-app-engine-django, AppEngine helper & glue code. common/ Code & data shared by all apps. django-extras/ A tree that is merged into the django namespace. We put our own glue code here. This should be kept small and simple. __init__.py main.py manage.py Launchers for Django. settings.py Global configuration for Django. urls.py Main URL file. auth/ Our own custom authentication & account management system. media/ext_js/[package name] External third-party Javascript packages (like JQuery) live under this directory. These are places where all applications store data. media/[application name]/{js, css, img}/ templates/[application name]/ These are applications that are running in production. (None so far) These are applications that are under development. landing_page/ Where you end up when you go to "/". Currently a test page. volunteers/ Volunteer tracking. ADDING A NEW APPLICATION ======================== Every application has a name that looks like this: "landing_page". Your code lives in a directory with the same name. Your templates go under the directory templates/[application name]. Your media files go under the directory media/[application name]. All of your URLs are automatically mapped to be under To make your URLs visible, you need to: (1) Update the top-level urls.py to include your urls. (2) Add your application to INSTALLED_APPS in settings.py. THIRD-PARTY CODE ================ Some of the files in this directory and all of files under the appengine_django/ subdirectory are based on rev 81 of the google-app-engine-django Subversion repository. All files in django.zip are taken from Django 1.0.2-final. It was constructed by running the following commands: zip -r django.zip django/conf -x 'django/conf/locale/*' These commands were taken from | https://bitbucket.org/kumar303/chirpradio/src/0f3404eef0e5?at=tip | CC-MAIN-2015-32 | refinedweb | 385 | 62.24 |
well, I'm using a book called "Learn C++ in 21 days" and it's working out great so far. The only problem is that when I type in the code from the book, letter for letter, many errors pop up. Is this book made for a previous version of C++? It was writtin at least 5 years ago, and the verion of C++ I'm using is "Dev-C++ v.5"...
Anyone know of this problem? Is there actually a problem with this code? Heres an example of the book's code
#include <iostream.h>
void myFunction();
int x = 5, y = 7;
int main()
{
cout << "x from main: " << x << "/n";
cout << "y from main: " << y << "/n/n";
myFunction();
cout << "Back from myFunction!/n/n";
cout << "x from main: " << x << "/n";
cout << "y from main: " << y << "/n";
return 0;
}
void myFunction()
{
int y = 10;
cout << "x from myFunction: " << x << "/n";
cout << "y from myFunction: " << y << "/n/n";
}
So, obviously it's just a simple little program, not really doing much, but it won't work!
Someone know how to fix my problem?
Also, one of the errors at the bottom of the page is "32:2 C:\Dev-Cpp\include\c++\3.4.2\backward\backward_warning.h . "
heh, anyone know this one? | https://www.daniweb.com/programming/software-development/threads/75643/hi-i-m-new-to-c-and-i-need-some-confirmation | CC-MAIN-2016-50 | refinedweb | 212 | 80.92 |
IOT Switch
For a while now we have seen lamps that can be turned on or off via your smartphone, or using something like Amazon Alexa or Google Home. I decided to give it a shot at building a device that can plug in into existing bulb sockets and allow for any type of bulb to be integrated into IOT.
Hardware
For this project the list of parts is as follows.
- Nodemcu
- 5V relay
- 120/220V to 5V smartphone charger
- Socket for light bulb
The image below shows a diagram of how the parts for this project should be conected together.
The first prototype I designed had a plug socket, but the funciontioning is the same as if it had a bulb socket. Below you can see a picture of the design I used for testing.
Stripped 5V phone charger
Software
The software side was developed using arduino, and consists on a sketch that connects to a MQTT broker and subscribes to a pre-defined topic. Within this topic we receive the on or off signal which in turn activates or deactivates the 5V relay which turns the bulb or on off. The MQTT broker I used was Mosquitto running on a Raspberry Pi, but you can very well use something like cloudmqtt or adafruit.io
Below is the arduino code used.
#include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "xxxxx"; // Your WIFI SSID const char* password = "xxxxxx"; // Your WIFI Password const char* mqttServer = "192.168.0.31"; // Your Broker IP Address const int mqttPort = 1883; long lastReconnectAttempt = 0; WiFiClient espClient; PubSubClient client(espClient); void callback(char* topic, byte* payload, unsigned int length) { if (strcmp(topic,"bedroom1")==0){ if( (byte)payload[0] == '1'){ digitalWrite(16, HIGH); // Turn the LED off by making the voltage HIGH } if( (byte)payload[0] == '0'){ digitalWrite(16, LOW); // Turn the LED on by making the voltage LOW } } } boolean reconnect() { if (client.connect("Nodemcu 3.0")) { // Once connected, publish an announcement... client.publish("bedroom1","bedroom connected"); // ... and resubscribe client.subscribe("bedlroom1"); } return client.connected(); } void setup() { pinMode(16, OUTPUT); pinMode(5, OUTPUT); pinMode(4, OUTPUT); pinMode(0, OUTPUT); Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } Serial.println("Connected to the WiFi network"); client.setServer(mqttServer, mqttPort); client.setCallback(callback); lastReconnectAttempt = 0; } void loop() { if (!client.connected()) { long now = millis(); if (now - lastReconnectAttempt > 5000) { lastReconnectAttempt = now; // Attempt to reconnect if (reconnect()) { lastReconnectAttempt = 0; } } } else { // Client connected client.loop(); } client.publish("bedroom1", "stillalive"); }
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Your email address will not be published. Required fields are marked * | https://www.alejandrowurts.com/projects/iot-switch/ | CC-MAIN-2020-16 | refinedweb | 438 | 56.96 |
This post contains affiliate links. For more information, see my disclosures here.
In 2019, a regulation came into force in Europe by which companies are required to have a daily record of the hours of their employees.
There are many online tools to keep track of this. At Desygner we use Calamari.io.
We use Slack as a communication tool and we have commands for clocking in / out from Calamari.
The problem is that sometimes I forget to write the command in Slack to start or end my working day 🤦🏽♂️
Thinking about solutions to make it easier, and since I like to tinker with electronics, I thought about building a small device with a couple of buttons with which I could start and end my shift and register the lunch break. All I needed was for Calamari to offer an API to communicate with, and they have one! 👏🏽
Now, it was time to choose where to start building this system. Previously, I had used Arduino for electronics projects but now I was going to need WiFi connection and the cheapest option of this brand is the Arduino Nano 33 IoT at around $25 on Amazon. Several people had recommended me to use the ESP32 board that also includes WiFi and Bluetooth and you can find it on Amazon for $10.
This was my first time working with the ESP32 board, so after the first steps to get it working with my computer and Arduino IDE, the next thing I wanted to do was connect it to the WiFi network.
My first idea was to have an app or web with which to connect via Bluetooth to the board, and once there, through an interface, be able to select the network to connect it to and write the password. It sounded great! However, after searching a lot about how to connect the ESP32 board via WiFi I did not find anything similar already done. So I opted for a simpler option: hardcode the name and password of the WiFi network in the code. The downside of this is that every time I want to shift networks I need to change the code and compile it back to the board.
#include "WiFi.h" //ESP32 WiFi library WiFi.mode(WIFI_STA); WiFi.begin("Wifi_SSID", "WiFiPassword"); uint8_t i = 0; while (WiFi.status() != WL_CONNECTED) { delay(500); if ((++i % 16) == 0) { Serial.println(F(" still trying to connect")); } } Serial.print(F("Connected. My IP address is: ")); Serial.println(WiFi.localIP());
This guide was helpful
Once connected to the network, the next important step was to find out how to communicate over the Internet, needed to be able to make calls to Calamari's API.
This, similar to the WiFi connection, is not a complex task since there are libraries that we can use to help us. In this case, I used the library
<HTTPClient.h>.
For this first test of how to make HTTP calls I didn't want to mess with Calamari's API just yet, hence I used a service that offers a mock REST API for testing: JSONPlaceholder.
#include "HTTPClient.h" HTTPClient http; http.begin(""); int httpCode = http.GET(); if (httpCode > 0) { String response = http.getString(); Serial.println(httpCode); Serial.println(response); } else { Serial.println("Error on HTTP request: "); Serial.println(httpCode); } http.end();
I followed this guide
With everything set up, I was ready to make requests to the Calamari.io API.
I created a class to have everything tidier and make the operation easier within the code. I helped myself with this guide to do it. You can see how I built it in the link at the end of the article with the repository on Github.
To use the class you just need to create an instance and pass four arguments, the base URL of the Calamari.io API, the username and password (information that Calamari provides when you activate the API) and the employee's email (in this case my corporate email).
The class has six methods available to use. I think the names are understandable enough:
- Shift:
shiftIsOn(),
startShift(),
stopShift()
- Break:
breakIsOn(),
startLunchBreak(),
stopLunchBreak()
After a bit of trial and error, I got everything working. I was only missing the hardware part: a button to start/end the shift 👨🏽💻 and another button to start/finish the lunch break 🍕
The two buttons have one of the pins connected to ground through a resistor, here you can read a good explanation of why it is necessary to use these resistors (pull-up or pull-down). The pins on the same side but at the bottom are connected to the GPIO inputs on the board:
26 for the first button (the one that starts/ends the shift) and
27 for the second button (the one that starts/ends the break). And the right pins are connected to the 3.3V output.
Finally, I only needed to take care of the code of when the buttons are pressed, so it can perform the necessary action depending on the button pressed.
int pushShiftButton = digitalRead(26); int pushBreakButton = digitalRead(27); if(pushShiftButton) { if(calamari.shiftIsOn()) { Serial.println("Stop shift"); calamari.stopShift(); } else { Serial.println("Start shift"); calamari.startShift(); } delay(1000); } if(pushBreakButton) { if(calamari.breakIsOn()) { Serial.println("Stop lunch break"); calamari.stopLunchBreak(); } else { Serial.println("Start lunch break"); calamari.startLunchBreak(); } delay(1000); }
When one of the buttons is pressed, for example the lunch break button, it is checked whether the break is currently taking place. If it is, then the method to stop it is called, and if not, the method to start it is called. Then there is a delay of 1 second in the code. This is done because otherwise, the code could be executed multiple times, even if we only pressed the button once since this piece of code is inside a loop that runs faster than it takes to press and remove your finger from the button.
And this is it, here you can see how it actually works 😁:
And this is the complete code on my Github:
jvlobo
/
esp32-calamari.io-api
Clocking in and out in Calamari.io with the ESP32 development board
Stay tuned for the second part of this project, where I am going to create in 3D and print a box to make this system more compact and portable. I will also install a battery so I don't need to be powering it through the ESP32 USB port.
Update: Second part is published now! ⬇️
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/jvlobo/how-to-make-clock-in-at-work-easier-with-the-esp32-board-part-1-3eo0 | CC-MAIN-2021-10 | refinedweb | 1,081 | 71.24 |
Create slideshow in qt creator
I want to Devlope application where using left and right aerrow key i change image. I created list using stringlist for all image links. But I not able to implement keypressevent function.i don't have any idea how I go to next or previous image based on respective key
Hi and welcome to devnet,
What technology are you using ? Widgets or QtQuick ?
@RAJ-Dalsaniya hi see qml Keys type
You wrote that you are using QtQuick but now you want to use C++.
Did you change technology ?
- RAJ Dalsaniya last edited by RAJ Dalsaniya
@SGaist Yes I try same using widget but problem is when i press key my application crashed. it will give sigabrt signal .. I implement keyevent using keypressevent
If it crashed then there's likely an error in your code. Did you try to debug it ?
@RAJ-Dalsaniya
Hi
please show the c++ code then. :)
f1_image.cpp
#include "f1_image.h" #include "ui_f1_image.h" #include<QGraphicsView> #include<QStringList> #include<QList> #include<QDir> #include<iostream> #include<QWidget> #include <QKeyEvent> #include <QStringList> class f1_image_private { public: f1_image_private(); int CurrentSlide; }; F1_Image::F1_Image(QDialog *parent) : QDialog(parent), ui(new Ui::F1_Image) { ui->setupUi(this); filenames.append(":/f1/F1_IMG/city.jpg"); filenames.append(":/f1/F1_IMG/cycle.jpg"); filenames.append(":/f1/F1_IMG/design.jpg"); filenames.append(":/f1/F1_IMG/nature.jpg"); filenames.append(":/f1/F1_IMG/tree.jpg"); } F1_Image::~F1_Image() { delete ui; } void F1_Image::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing, false); if (filenames.size() > 0) { ui->image->setPixmap(filenames.at(i)); } } void F1_Image::keyPressEvent(QKeyEvent* event) { if(event->key()==Qt::Key_Left) { i++ ; } else if(event->key()==Qt::Key_Right) { i--; } }
f1_image.h
#ifndef F1_IMAGE_H #define F1_IMAGE_H #include <QDialog> #include <QStringList> #include <QGraphicsScene> namespace Ui { class F1_Image; } class F1_image_private; class F1_Image : public QDialog { Q_OBJECT public: explicit F1_Image(QDialog *parent = nullptr); ~F1_Image(); void addImage(QStringList filenames); QStringList filenames; int i=0; private: Ui::F1_Image *ui; Ui::F1_Image *d; QPixmap image; QImage *imageObject; QGraphicsScene *scene; signals: void inputReceived(); protected: void keyPressEvent(QKeyEvent *event); void paintEvent(QPaintEvent *event); // void showEvent(QShowEvent *event ); };
@SGaist @mrjj this is my code. i am not sure where excatly i am doing wrong. can you please help me??
- mrjj Lifetime Qt Champion last edited by mrjj
Hi
It does not look very wrong.
At least not something app should crash from.
(not unless you press right from start and i becomes -1)
You don't need the
void F1_Image::paintEvent(QPaintEvent *event)
as the QLabel can paint itself and since you are
not painting anything else it seems wasted.
However, in sample, i used to print i on same form.
You can call setPixmap in keypressEvent
void F1_Image::keyPressEvent(QKeyEvent* event) { if(event->key()==Qt::Key_Left) { i++ ; } else if(event->key()==Qt::Key_Right) { i--; } int maxSize = filenames.size() - 1; // checks to make it round trip / avoid crashing if (i > maxSize) { i = 0; } if (i < 0 ) { i = maxSize; } if (i <= maxSize && i >= 0) { ui->label->setPixmap(filenames.at(i)); } }
also in .h
Ui::F1_Image *d;
That looks a little odd but just a pointer so should not do anything.
Make sure that you check i against being negative also.
If user press right as first key, the i will be -1 and also crash the list.
here is a working sample based on your code.
Well your code works fine in the sample
so i cannot guess why it does not for you.
Use the debugger and check what happens when you press a key
and check the the value of i.
Also , set an image to the QLabel in CTOR so it has something to show from start.
Make sure you check that i is valid.
The sample does the above if you have doubts.
@mrjj I set one other label to check I value and it changed according to keypress but label where I show picture it has some issue..
- mrjj Lifetime Qt Champion last edited by mrjj
What types of issues ?
It is extremely hard to help when you do not describe
what happens,
what is wrong,
What do you see on screen after key pressed.
make sure you have valid index (i)
int maxSize = filenames.size() - 1; // checks to make it round trip / avoid crashing if (i > maxSize) { i = 0; } if (i < 0 ) { i = maxSize; } if (i <= maxSize && i >= 0) { ui->label->setPixmap(filenames.at(i)); }
- RAJ Dalsaniya last edited by RAJ Dalsaniya
@mrjj When I press key it change I value but it doesn't show picture that available in resource file. Problem is lable don't show picture from list. Can you just check what I write to add all links in filenames is right or not?
Hi, find the image file in the project tree to the left side
then right-click it and see the correct path there. then check
what you add to list.
@RAJ-Dalsaniya
Super to hear \o/
Please mark as solved using the Topic Tool button at first post :) | https://forum.qt.io/topic/107183/create-slideshow-in-qt-creator/20 | CC-MAIN-2019-47 | refinedweb | 823 | 65.12 |
This chapter provides you with a strong theoretical concept of Android. It is obvious that the term is not alien even for any novice technology user. Because of the popularity of this great operating system, many developers started to shift from web development and other platforms. This huge migration has brought a significant change in the market of Android apps and has opened new, unlimited doors for new mobile application developers. Android is a strong opponent of iOS which is an operating system by Apple Inc. However, as statistics suggest, Android is catching up with the iOS market in terms of revenue as Google Play is the fastest growing app market in terms of total number of downloads.
This chapter includes the following topics:
Introducing Android
Understanding the whys and whens of Android
Official Google IDE for Android Developers â the Android Studio
Structure of an Android application
Presenting the Android Activity lifecycle
Android is a Linux-based operating system which makes it an open source software. Google distributed its license under the Apache License Agreement. The availability of Android code makes it an easily-modifiable operating system, which can be customized by the vendor as well. Due to a highly flexible design, some critics call it unsecure, which was right at a certain period of time, but now, Android is a mature operating system with a high-level secure architecture. It is said that the newest version of Android (that is, Jelly Bean) is the most secure operating system that Google has ever produced. Let's move forward with an overview of the different versions of the Android OS.
Since the beginning, Android has been transforming itself with the release of different versions. Not just UI but many features were added, modified, and enhanced in each upcoming version. The first version to officially use the name of a dessert was Android Cupcake 1.5, which was based on Linux 2.6.27. Every new Android version comes with a new set of API levels, which basically revises the previous API with some modification, obsoleteness, and addition of new controls.
Releasing new versions of Android brings some obsoleteness in the previous methods/functions from a developer's point of view. However, this will bring warnings but not errors; you can still use previous method calls in new API Levels as well.
The following table shows the different Android versions with their API Levels and major highlights:
Note
It is an interesting fact that the versions of Android are in alphabetical order. Starting off from Apple Pie 1.0 and then Banana Bread 1.1, it made its way towards Jelly Bean with a complete coherence of alphabetical sequence, and by maintaining the legacy; the next version expected will be Key Lime Pie.
As it is mentioned earlier that Android is open for modifications by the vendor due to its open-sourced nature, many famous mobile manufacturers put their own customized versions of Android in their phones. For example, Samsung made a custom touch interface over Android and calls it TouchWiz (Samsung Galaxy S4 comes with TouchWiz Nature UX 2.0). Similarly, HTC and Sony Xperia came up with their own custom user interface and called it HTC Sense and TimeScape respectively.
Just like any other famous mobile operating systems, Android has its app store known as Google Play. Previously, the app store was called Android Market, which, at the start of the year 2012, became Google Play with a new-and-improved user experience. The update unified the whole entertainment world under the umbrella of Google Play. Music, apps, books, and movies, all became easily accessible to the users just like Apple's famous App Store (iTunes). You can find detailed information about the Android store at.
Note
Google Movies & TV, Google Music, Google Books, and Google Magazines are only available in limited countries.
Google Play provides a wide range of applications, movies, e-books, and music. Recently, they also introduced the Google Play TV facility under the same app store. Talking about the application side, Google Play provides different categories in which a user can select applications. It ranges from games to comics and social apps. Users can enjoy many paid applications and can unlock many features by in-app billing services provided by Google Play.
There are different vendor specific app stores as well, such as Kindle's Amazon App Store, Nook Store, and many others that provide many applications under their own terms and conditions.
Android is a Linux-based open source operating system, primarily targeted for touch screen mobiles and tablets. Andy Rubin, Rich Miner, Nick Sears, and Chris White founded the operating system in October 2003. The basic intention behind the idea of Android was to develop an operating system for digital content. This was because, at that time, mobiles were using Symbian and Windows Mobile as their operating systems.
Note
iPhone was released in June 2007 by Apple Inc. Android was released in November 2007 by Google Inc.
However, when they realized that there is not much of a market for devices such as cameras, they diverted their attention to mobile phones against Symbian and Windows Mobile. iPhone was not on the market then. Android Inc., a top brand for smart phone operating systems covering 75 percent of market share as of today in smartphones, was running secretly at that time. They revealed nothing to the market except that they were working on software for mobile phones. That same year, Rubin, the co-founder of Android, ran out of money, and his close friend, Steve Perlman, brought him $10,000 cash in an envelope.
In August 2005, Google Inc. acquired Android Inc., making it a subsidiary of Google Inc. The primary employees of Android stayed in Android Inc. after acquisition. Andy Rubin developed a mobile device platform powered by Linux Kernel. Handset makers and carriers were being promised a flexible and upgradeable operating system by Google. As Google was not releasing any news about Android in the media, rumors started to spread around. Speculations spreading around included Google is developing Google branded handsets and Google is defining cell phone prototypes and technical specifications. These speculations and rumors continued until December 2006.
Later, in November 2007, Open Handset Alliance revealed that their goal was to develop an open standard for mobile devices. Android was released as its first product; a mobile device platform built on Linux Kernel Version 2.6. Open Handset Alliance is a consortium of 65 companies involved in mobile space advocating open source standards for the mobile industry.
In October 2008, the very first commercially available phone deploying Android operating system was released by HTC, called HTC Dream. The following image shows HTC Dream. Since then Android is being upgraded. Google launched its nexus series in 2010.
HTC Dream, the First Android phone using Android Activity back stack
After the first appearance of Android OS in HTC Dream, it gained rapid popularity among consumers. Android is continuously being upgraded by Google. Each major release includes bug fixes from the last release and new features.
Android released its first version in September 2008 in the device HTC Hero. Android 1.1 was an update tweaking bugs and issues, with no major release. After Android 1.1, Android 1.5 named Cupcake, was released with features such as video uploading, text prediction, and so on. Android 1.6 Donut and Android 2.0/2.1 Ãclair released at the end of 2009, followed by 2.1 in January 2010, introduced major updates such as Google Maps, enhanced photo video capabilities, Bluetooth, multi-touch support, live wallpapers, and more. In May 2010, Android 2.2 named as Frozen Yogurt, or Froyo, was the major release, adding support for Wi-Fi hotspot connectivity.
This version became very popular among developers, and is used to be the minimum API level for android apps. Android 2.3 Gingerbread, released in May 2010 introduced the Near Field Communication (NFC) capability, which allowed users to perform tasks such as mobile payments and data exchange. This version of Android became the most popular version among developers. Android 3.0/3.1 Honeycomb, was specially optimized for tablet devices, and more UI control for developers was a big plus. Android 4.0 Ice Cream Sandwich was released in October 2011. Since Android 3.0/3.1 was only for tablets, the Ice Cream Sandwich release overhauled the gap, and was supported by both mobile phones and tablets. The latest release of Android, Android 4.2 Jelly Bean further polished the UI, refined the software, among other improvements.
Note
Google started naming Android versions after sugar treats, in alphabetical order, after Android 1.1 version.
The following image shows all the versions in a visual format:
The following screenshot shows the current distribution (March 2013) of Android versions. It is clear from the screenshot that Android 2.3 Gingerbread is the most popular version, followed by Android Ice Cream 4.0:
Current distributions of Android versions
Before Google I/O 2013, Android was officially using Eclipse as an IDE for its development. Official Android Support clearly mentioned about the use of this IDE along with the Android Development Tools (ADT) and Android Software Development Kit (SDK) with its documentation.
In Google I/O 2013, Google came up with a new IDE that is specially designed for the development of Android Apps. The IDE is called Android Studio, which is an IntelliJ-based software that provides promising features to the developers.
Android Studio gives various features on top of an IntelliJ-based IDE. The list of features that are introduced in Android Studio is as follows:
Android Studio comes with built-in Android Development Tools
Android Studio gives Gradle-based support for the build
Flexible controls for building an Android UI and simultaneous views on different screen sizes
Android refactoring, quick fixes, and tips and tricks
Advance UI maker for Android apps with drag-and-drop functionality
The following screenshot shows the Android Studio multi-screen viewer with UI maker:
Apart from that, there are various other features that are offered by Android Studio. Google mentioned in the launch that the version (v0.1) is unstable and needs various fixes before it can be used with its 100 percent accuracy.
Android Studio is in the early phase, which makes it an immature software with limitations. According to Google, they are working on the updates of the software and soon will rectify the issues. As per Version 0.1.1,the limitations faced by the developers are as follows:
Android Studio can only be compiled with Android 4.2 Jelly Bean
The user interface can only be made with Android 4.2 Jelly Bean UIs and widgets
An Eclipse project cannot be directly imported on Android Studio (refer to)
Bugs in importing library projects
An Android application consists of various building blocks that help developers to keep things organized. It gives flexibility to maintain assets, pictures, animations, movie clips, and implement the localization functionality. Moreover, there are some components that contain the information regarding the minimum and maximum versions of Android that your application supports. Similarly, menus are separately handled in Android application projects.
Various components of an Android application as shown in Android Studio
Just like Eclipse IDE, Android Studio gives various handy functionalities to play with these features. Looking forward to the building blocks of the Android application, we can classify the components into the following parts:
Coding components
Media components
XML components
Referencing components
Library components
Breaking into components brings an easy understanding of the structure of an Android application. Coding components are those that directly relate to the source code of an Android project. In order to write an application, a developer needs to write some lines of code that will respond in the way the user wants.
In coding components, the main folder that holds all of the developer's code is
src. The folder consists of one or more Java packages in which developers classify their code in accordance with the type of work done. The default way to write a package name is dot separated (for example,
com.app.myapplicationproject), which can easily distinguish it from any other package of any other project.
Inside the packages there are
.java files that are present for the developer to reference from the Android library and proceed to the desirable output. These Java classes may be or may not be inherited from the Android API. We can also use most of the Java functions in writing our code.:
Assets folder
Res folder
An Android project contains a folder named
assets. This folder is responsible for holding all of the media files, including music, images, and so on. The developer can directly access the folder from the code by writing the
getAssets() function within the inherited
Activity class. This function returns the
AssetManager that can easily be used to access the subfolders and files inside the main
assets folder.
The main advantage of the
assets folder is that there is no need to keep references for the files placed, which is very handy in the situation where the developer needs to do a test and make a runtime change. Though it does not have any reference, it may introduce errors due to typing mistakes. Another advantage of using assets is that the developer can arrange folders according to his or her will; similarly, the naming conventions for these folders can easily be chosen according to the ease of the developer.
The
res folder is used to manage an application's resources such as media files, images, user interface layouts, menus, animation, colors, and strings (text) in an Android application; or in other words, you can say that this is the most intelligent way of handling the media files. It consists of many subfolders including
drawable,
drawable-ldpi,
drawable-mdpi,
drawable-hdpi,
drawable-xhdpi,
drawable-xxhdpi,
raw,
layout,
anim,
menu, and
values.
Drawable is directly related to the images that are used in the Android project. It is an intelligent way of keeping images in the project. As we know that there are various types of devices present in the market that support Android OS. In order to differentiate between these devices, the low resolution images are placed in the
ldpi folder for the devices with less resolution. Similarly, the
mdpi folder is for the device with medium screen density,
hdpi for high density,
xhdpi for extra high density, and so on.
Tip
The images placed in these drawable folders should be uniquely named in order to access them with a single reference from the code.
Similarly, for placing music and sound contents, we use the
raw folder in order to access them from the code. Any other file apart from the music and sound can also be placed in the
raw folder (for example, the JSON file). The same goes with
anim,
values,
menus, and
layout folders for placing the animations, values, custom menus, and different types of layouts respectively.
In Android, a developer needs to use XML in order to make the user interface. Layouts, Menus, Sub Menus, and many other things are defined in the form of different Android tags based on XML. Apart from layouts, you can also store strings, color codes, and many other things in the form of XML files. The component supports the maintenance of the hierarchy of the application and makes it easy to understand for all developers.
Let's take a look at some of the most important XML files that are used as the backbone of any Android application.
Inside the
res folder, there is a folder called
layout that contains all the layouts of activities. It is to be noted that there are some extensions of this folder, just like the drawable folders. The
layout-land and
layout-port methods are specifically used for keeping the layout well organized in landscape and portrait mode respectively.
Tip
XML can also be used for making custom drawables that can be used as images in different scenarios. For example, the image of the custom button can be made with XML, which gives a different UI behavior on clicked and non-clicked states.
The preceding screenshot is of Android Studio where you can see an
activity_main.xml file that is used to describe the layout of an activity. There are some Android-defined XML tags for
RelativeLayout and
TextView (read the following information box). Similarly, there are some other tags as well that are available for the developer to include different kinds of widgets in the layout.
Android comes with different kind of menus that can be used in order to give quick access to the prominent functionalities that are used within an activity. The different menus available are as follows:
Due to the limited focus of this chapter, we cannot completely elaborate on the functionality and give examples of the different types of menus. However, all types of menus are based on XML files in which Android-defined tags such as
<item>, and
<group> are used to introduce menus in the application. See the following screenshot for reference:
The Android ICS Options menu is on left and the Custom Pop Up menu is on the right
The
values folder consists of various XML files that can be used by the developer in many scenarios. The most common files for this folder are
styles.xml and
strings.xml. The
style file consists of all the tags that are related to the style of any UI. Similarly, the
strings.xml file consists of all the strings that are used in the source code of any Android project. Apart from that, the
strings.xml file also contains the
<color> tagged hash-coding, which is used to identify many colors inside the source code of an Android application.
Unlike the previously mentioned folders,
AndroidManifest.xml is a file that contains important information about the Android application. The manifest file consists of various tags such as
<application>,
<uses-sdk>,
<activity>,
<intent-filter>,
<service>, and many other tags that are enclosed within the main tag of
<manifest>.
Just like the tags suggest, this XML file contains all the information about activities, services, SDK versions, and everything that is related to the application. There are various errors that may arise if you don't enter the correct information or miss anything in the
AndroidManifest.xml file.
Another major advantage of the
AndroidManifest.xml file is that it is the best way to track the structure of any Android application. The total number of activities, services, and receivers can be seen easily by this file. Apart from that, we can change the styles, fonts, SDK constraints, screen-size restrictions, and many other features just by tweaking the
AndroidManifest.xml file.
At the time of signing the
.apk build, we mention the package name, version name, and version code, which are uniquely identified by the Google Play in order to put the application on the market. The application will then be identified by this package name and further releases are based on changing the version codes and version name described inside the
AndroidManifest.xml file.
Another basic component of an Android application is the referencing component. Put simply this component helps XML-based files to interact with the Java code. In Android Studio, the file
R.java is placed under the source folder, which is the child of the build folder in the project hierarchy. The
R.java file consists of all the references that are used in the XML files for layout, menus, drawables, anim, and so on. This file is then exposed to the activity files to get the references and obtain the objects to perform various functions and parameters.
Mostly, this
R.java file is obtained as a part of the project import and used as
R.layout.main. In this example, it clearly means that we need to obtain a layout that is a part of the
res layout folder and the name of the layout is
main. As a result, it will return a resource ID, which is hidden from the developer and directly referenced to the particular layout inside the
res folder.
Note
The
R.java file is automatically generated while building the project. Hence, it should not be pushed into the repository. Ensure the content of the
R.java file is not modified manually. The
R.java file that exists in the
gen folder of your project is defined by Android at the time of project making or compiling.
Libraries are pre-built Java files/projects that can be used by anyone to perform certain tasks inside this application. There are various third-party paid/unpaid libraries available that give various functionalities to the developer. Library components are not libraries themselves; rather, they are the project folders in which the libraries are kept.
In an Android project, a folder named
libs is present inside the main application folder (Android Studio), which is used as a library component. Any
.jar library file can be put under this folder in order to reference it from the code. While using those libraries inside the Java code, you need to import the corresponding package name that is present inside the
.jar file in order to use the functions of that particular class.
Similarly, you can use any other Android project as a library by making it a module and importing it inside your project. This functionality was previously called as Library Project in Eclipse, imported by Project Properties | Android | Library Reference.
The Android Studio module importing window
An Android application consists of one or more activities. These activities are visual representations of an application in transitioning flow while performing the task, taking user inputs, and showing results to the user. Each activity presents the user with a visual representation on the screen for user interaction. Android keeps all the activities in a back stack following the last in, first out rule. Whenever a new activity is started, the current activity is pushed in the back stack. Thus, Android gives focus focuses on the new activity. The activity can take up the whole screen of the device, or it can also take part of the screen, or it can be dragged as well. Whether it is an activity taking the whole area of a screen or a small part of screen, only one activity is focused at a time in Android. When, any existing activity is stopped, it is pushed into the back stack, which in turn results the next top activity being focused.
Note
Android 4.x versions introduced fragments. Fragments can be referred to as sub-activities, which are embedded in an activity to perform different tasks in a single activity at the same time, unlike activities.
Usually,.
Android Activity back stack
The previous figure shows a simple representation of how back stack works. The area highlighting top activities in a stack represents foreground activity, sometimes called focused activity or running activity. When a new activity is created, it is pushed in the stack, and when any existing activity is destroyed, it is pulled out of the stack. This process of being pushed in the stack and pulled out of the stack is managed by the activity lifecycle in Android. This lifecycle is called Activity lifecycle. The lifecycle manages the activities in the stack and notifies about the changes in the state in the activities through the callback methods of the cycle. An activity receives different types of states such as activity created, activity destroyed, and so on, due to change in the state. A developer overrides these callback methods to perform the necessary steps for respective change of state. For example, when an activity is started, the necessary resources should be loaded, or when an activity is destroyed, those resources should be unloaded for better performance of the app. All these callback methods play a crucial role in managing the Activity lifecycle. It is the developer's choice to override none, some, or all methods.
Basically, an activity remains in three states:
Resumed,
Paused, and
Stopped. When an activity is resumed, it is shown on the screen and gets the focus of the user. This activity remains in the foreground section of the back stack. When another activity is started and it becomes visible on the screen, then this activity is paused. This activity still remains on the foreground task, and it is still alive, but it has not gotten any user focus. It is also possible that the new activity partially covers the screen. In that case, the part of the paused activity will be visible on the screen. The activity comes in the Stopped state when it becomes completely invisible from the screen, and is replaced by another activity in the foreground. In this stopped state, the activity is still alive, but it is in the background section of the back stack. The difference between the paused and stopped states is that, in the paused state, the activity is attached to the window manager, but in the stopped state, it is not attached to the window manager.
Note
In an extremely low memory situation, an Android system can kill any paused or stopped activity by asking to finish it, or without asking by killing the process. To avoid this problem, the developer should store all the necessary data in a pause and stop callback, and should retrieve this data in the resume callback.
There are various callback methods that are called when the state of any activity is changed. Developers perform the necessary tasks and actions in these methods for better performance of the app. To show the Activity lifecycle in action, we are creating a small Android application in this section. Here is the step-by-step approach:
Start Android Studio.
Create an empty project with the details as shown in the following screenshot:
New Project Dialog in Android Studio
Add the following code in the
MainActivity.javafile of the project:
package com.learningandroidintents.callbacksdemo; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); Toast.makeText( this, "Activity Created!", Toast.LENGTH_SHORT ).show(); } @Override protected void onStart () { super.onStart(); Toast.makeText(this, "Activity Started!", Toast.LENGTH_SHORT ).show(); } @Override protected void onResume() { super.onResume(); Toast.makeText(this, "Activity Resumed!", Toast.LENGTH_SHORT ).show(); } @Override protected void onPause() { super.onPause(); Toast.makeText(this, "Activity Paused!", Toast.LENGTH_SHORT ).show(); } @Override protected void onStop() { super.onStop(); Toast.makeText(this, "Activity Stopped!", Toast.LENGTH_SHORT ).show(); } @Override protected void onDestroy() { super.onDestroy(); Toast.makeText(this, "Activity Destroyed!", Toast.LENGTH_SHORT ).show(); } }
Run the project in the emulator, and you will see toasts being printed on screen in the following order:
Activity Created
Activity Started
Activity Resumed
Activity Paused
Activity Stopped
Activity Destroyed
Let us see the working of the previously mentioned code.
When you run the project, the emulator will display all the toasts in the previously given order on the screen. At the start of project, an activity is created, and then the activity is started. After starting the activity, it is displayed on the screen and emulator prints Resumed. Now, we go back by pressing the back key, and the Android system prepares to finish the activity. So, the activity is first paused, then it is stopped, and finally it is destroyed. All these callbacks together are called the Activity lifecycle. Activity lifecycle starts from the
onCreate() method and it stops at the
onStop() method. The activity is visible from the
onStart() method to the
onStop() method, and the activity remains in foreground from the
onResume() method to the
onPause() method. The following figure shows this cycle distribution:
Until now, we have discussed the lifecycle callback methods used, their states, and their purpose. Now, we will look into the callback method's flow. In Android, when one activity is started, the already opened activity is stopped, and this change of activity happens in a flow. The following figure shows the visual flowchart of the Activity lifecycle:
Callback methods are shown with rectangles. The very first step in the Activity lifecycle is to create an activity. Android creates an activity, if no instance of that activity is running in the same task. The
noHistory tag does not allow multiple activities; rather it will determine whether an activity will have historical trace or not (refer to), where you can determine multiple instances by the
android:launchmode flag tag. Making this tag's value
true means only one instance of the activity will be created in the stack, and whenever an activity intent is called, the same instance is pushed on top of the stack to show the activity on screen.
After the
onCreate() method, the
onStart() method is called. This method is responsible for the initial settings, but it is best practice configure these in the
onResume() method, which is called after the
onStart() method. Remember, the foreground phase is started from the
onResume() method. Say a user gets a call on his or her phone, then this activity will be paused through the
onPause() method. So, all the steps involved in storing the necessary data when the activity is paused should be done here. This method can be very beneficial in critical memory situations because in these situations, Android can stop the paused activities, which in turn can show unexpected behavior in the app. If the activity is killed due to a critical memory situation, the
onCreate() method is called instead of the
onResume() method, resulting in the creation of a new instance of the activity.
But, if everything goes right, then the activity returns to its same state through the
onResume() method. In this method, the user can do all the work of reloading the stored data in the
onPause() method, and can get the activity back to life. On turning off the activity after
onResume() is launched the
onStop() method is called. This triggers either the
onRestart() method, or the
onDestroy() method depending on user action. In a nutshell, the developer can control the Activity lifecycle using callback methods. It is a good practice to use the
onPause() and
onResume() methods for data management, whether the activity remains foreground or not, and
onCreate() and
onDestroy() should be used for only initial data management and cleaning up the resources respectively.
Note
All callback methods except the
onCreate() method take no parameter or argument. In case of a critical memory situation, if an activity is destroyed, then that instance state is passed in the
onCreate() method at the time of creation of that activity.
It is not necessary to override all the methods. The user can override any number of methods as there is no such restriction on it. The user should set a view in the
onCreate() method. If you don't set any view for the content, a blank screen will show up. In each callback, first of all, the same callback method of the superclass should be called before doing anything. This super callback method operates the Activity lifecycle through standard flow developed by Android systems.
In this chapter, we explored the key concepts of Android. We discussed about Android, its versions that are named after sugar treats, covered a brief history of Android, and how its founders released Android with Google. We also discussed Google Play, an official store for Android apps; Android Studio, an official IDE from Google, and its features and limitations. Then we moved our discussion to a development perspective, and we discussed the building blocks for any Android application. We also discussed the Activity lifecycle, which plays a very important role in any Android application, its flow, its callback methods, and and looked at an example of it.
In the next chapter, we will discuss the intents, role played by the intents in Android, a technical overview, structure, and its uses in Android. | https://www.packtpub.com/product/learning-android-intents/9781783289639 | CC-MAIN-2020-40 | refinedweb | 5,338 | 54.02 |
HOUSTON (ICIS)--Here is Tuesday’s end of day ?xml:namespace>
CRUDE: Sep WTI: $100.97/bbl, down 70 cents/bbl; Sep Brent: $107.72/bbl, up 15 cents/bbl
NYMEX WTI crude futures lost ground for the second consecutive session in response to a refinery outage due to a fire in the US Midwest, which should back out crude due to reduced consumption. Reports that the Commerce Department had put on hold requests from various companies for permission to export ultra-light oil (condensate) from shale were being factored in by the market. A stronger dollar also pressured prices, overshadowing a jump in consumer confidence.
RBOB: Aug $2.8709/gal, up 2.17 cents/gal
Reformulated blendstock for oxygen blending (RBOB) gasoline futures were stronger after a refinery fire in Kansas raised supply fears in the region. However, analysts expect overall gasoline inventories to be much stronger.
NATURAL GAS: Aug $3.808/MMBtu, up 6.1 cents/MMBtu
Natural gas futures on the NYMEX recovered from a slight downturn in trading earlier in the day, driven by cooler temperatures that are expected to bring down demand for air conditioning. However, the impending expiry of the August front month brought on late-session support.
ETHANE: higher at 23.25 cents/gal
Ethane spot prices followed natural gas futures slightly higher in thin trade on Tuesday.
AROMATICS: toluene flat at $4.00-4.20, mixed xylenes flat at $3.80-4.00/gal
Activity was thin for US toluene and mixed xylenes (MX) spot prices during the day, sources said. As a result, prices were stable from the previous session.
OLEFINS: ethylene lower at 65 cents/lb; PGP higher at 70 cents/lb
US July ethylene traded on Tuesday at 65.0 cents/lb, lower than the previous reported trade at 66.5 cents/lb on 25 July. US July polymer-grade propylene (PGP) traded on Tuesday at 70.00 cents/lb, up compared to a trade at 69.25 cents/lb a week ago.
For more pricing intelligence please visit | http://www.icis.com/resources/news/2014/07/29/9806131/evening-snapshot-americas-markets-summary/ | CC-MAIN-2016-26 | refinedweb | 340 | 68.67 |
Introduction
Here I will explain how to create online poll system with percentage graphs using asp.net.
Description:
In many websites we will see online polls like which browser is best browser? We can submit our votes to these polls and they will display result with graphs after seen all these polls I tried to implement simple application for online polls with percentage graphs using as.net.
Here I am using XML to store all the poll options and retrieving all the options and displaying result based on polls options. Here I need to say one thing before implement this application I don’t know the exact purpose of XML whenever I implement this application I got idea regarding XML. XML is used to store the data and we can use it in any application and it will support for all the languages. Here I explained clearly how to insert and retrieve data from XML and how to bind that data to repeater
Here in my application I used only simple table concepts to display graphs I didn’t used any graph tools let see how I implemented
Design your aspx page like this
After that add XML file to your application and give name as "Votes.xml" intially xml file like this root element is compulsory for XML files that’s why I added CommentInformation in XML file that root element in XML file.
After that add this namespace in codebehind
After that write the following code in code behind
Demo
Download sample code attached
13 comments :
nice post but i need to show graph without using XML and record will be bind from the database and to show graph on the percentage of vote.
this code not working
error in web.config i m using vs2010
hi i did this example in vs 2008 if you open this application with vs 2010 it will ask you to convert higher version so at that time version problem will arise to avoid that problem you should create new website in vs2010 and copy and paste the aspx page and code behind code in your website and use your own website web.config file and follow my instructions it will work for you
it is not working in online sir did u give suggestion?
hi madhan for me it's working fine r u getting any error after deploy the application
Hi Suresh,
I keep getting the "Sorry, unable to process request. Please try again." error and it's not inserting my vote into the xml file. Is there something I can do to get it to work?
Thanks - Jude
Thanks for Sharing .. Nice Post.... May i know how to prevent a particular User voting again and again?
eg -:only prevent using Cookies.(Without Login )
add more namespace
using System.Data;
using System.Web.UI.HtmlControls;
then it is work perfectly.
thanks
Great Post man keep rocks.....
greatt Post....
but if i need to store data in sql server then how to do this can you give example
This blog is definitely awesome as well as informative. I have found a bunch of useful things out of it. Thanks a lot!
thnks
Not working Server but local system working fine..
error says 'Sorry, unable to process request. Please try again' pls help me | http://www.aspdotnet-suresh.com/2011/01/how-to-create-online-poll-system-with.html?showComment=1354512363944 | CC-MAIN-2014-15 | refinedweb | 552 | 69.62 |
With the announcement of Apple Watch, there has been a buzz for development of apps for it. In this tutorial we will make a Watch App using Swift and add some nice cool features in it. So lets get started!
You can start either by making a fresh new project or adding a new extension to an earlier developed iOS project. In both cases the watch app will work just perfect.
You need to have Xcode 6.2 beta or above to develop Apple watch apps.
Your Apple watch app is not the substitute of your iOS app but it is complimentary. You need your iOS device to be near the watch as it uses the Bluetooth LE to communicate with each other. If your iOS device is locked and you launch your third party watch kit apps it will show a message “Unlock to activate”.
Let us first understand how the watch app works :
When the app is launched on the watch, the companion iOS extension is automatically launched. They both work in synergy, with the watch app showing content to the watch and responding to interactions, while iOS extension is doing everything else. Actually, no application code is executed on the watch : all processing is delegated to the iOS extension.
In case you are starting with an existing project skip the step 1.
Step 1. In Xcode : Choose File -> New -> Project -> Single View Application. Name the project and choose Swift as the language. Fill out the other details and click “Next” and save it. You would now see that xcode has provided with the initial classes.To make an apple watch app we need to add “Watch Kit extension” to the project.
Step 2. In project Navigator click on your project name , click on (+) button on bottom side to add a new extension to the project. Choose Apple watch -> WatchKit App. Click next and you will see other settings which the xcode asks you.
- Choose language as Swift.
- You will see ‘Include Notification Scene’ and ‘Include Glance Scene’ are provided with checkboxes against them.
Just to brief up what Notification and Glance scenes are in Watch App are:
- Notification Scene – Notifications on Apple Watch facilitate quick, lightweight interaction in two parts: the Short Look and the Long Look. A Short Look appears when a local or remote notification needs to be presented to the user. A Short Look provides a discrete, minimal amount of information. If the wearer lowers his or her wrist, the Short Look disappears. A Long Look appears when the wearer’s wrist remains raised or the user taps the short look interface. It provides more detailed information and more functionality and it must be actively dismissed by the wearer.
- Glance Scene –.
So we will select both the checkboxes to include glances and notification scene in our app.
Click on “Finish” and you will see 2 targets have been added in your project – Watch Kit Extension and Watch kit App. Watch Kit Extension runs over your iphone and provides all the computations while the Watch Kit App just displays the data manipulated by the extension.
Going in the Watch Kit App Folder in Xcode, this bundle is static, meaning that adding or changing any of the resources, views, images etc. is not possible at runtime.While the Watch Kit Extension Folder contains the classes one each for the Glance, Notification and the Root view controller of the app.
Lets have a look at watch app looks in simulator: But before that choose your simulator and go to Hardware -> External Displays. You will see 2 options : Apple Watch 38 mm and Apple Watch 42 mm. Choose any. Now select Watch Kit App from the scheme and run. You must be wondering as to what will be seen on the simulator but it turns out that it just shows the time as we haven’t added code in it.
So lets dive in making the watch App work.
Step 3. If you started with an existing project then you want to display some information on the watch app which interests the user. As the watch app is all about extending the ios app functionality on your wrist. Here we will make a basic functionality in which we will display the table and the selected rows value will be updated on the watch.
We start with the iOS App and add UITableView in the storyboard and connect it using the Assistant Editor to the class. Connect the delegate and datasource to the view controller.
As we started with a fresh project and after set up, the viewcontroller should look like the code given below. It contains just the basic functions to populate the table and get row selection in it. We will have to add the code with which we tell the watch App the text of the row selected.
Use the following code to make UITableView work in ViewController class.
import UIKit class ViewController: UIViewController , UITableViewDataSource, UITableViewDelegate{ @IBOutlet weak var table: UITableView! let dataArray = [&quot;Obejct 1&quot;, &quot;Object 2&quot;, &quot;Object 3&quot;,&quot;Object 4&quot;]; let cellIdentifier = &quot;cellIdentifier&quot; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return dataArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = dataArray[indexPath.row]; return cell; } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.updateAppGroupContainer(dataArray[indexPath.row]) } }
There are various ways of communication between the iOS and watch App:
- Writing data in shared container by enabling the App groups in project.This further can be of two types depending on requirement. NSUserDefaults, Files or Coredata can be shared between the app and its extension.
- Watch App can initiate communication by using openParentApplication(userInfo:reply:) of WKInterfaceController which will call application(_:handleWatchKitExtensionRequest:reply:) in iOS app delegate.
Below code describes the use of NSUserDefaults for sharing data.To enable App Groups in project, go to targets section and choose the Watch Kit Extension/ Capabilities/App Groups. Switch on the app groups and click on the add button and add the name of a Container. As you see in code, i have named my container “group.com.WatchDemoTutorial”. The Group Identifier should start with “group.” otherwise Xcode generates an error. Similarly follow the same steps for the project in Target section. You will see that the Group Identifier will already be there, just check mark it to include in the project.
Use the following code to create / update the NSUserDefaults in the Shared Container.
func updateAppGroupContainer(data : NSString) { let defaults = NSUserDefaults(suiteName: "group.com.WatchDemoTutorial") let dict = ["rowSelected":data] defaults?.setObject(dict, forKey: "currentSelection") defaults?.synchronize() }
Step 4. We will now start working on the watchkit app and retrieve the data saved in the container. For this we now jump to the Watchkit App folder in project and select the storyboard so that we can design our UI.
Drag Drop a Label to the Interface Controller Scene and write a static text : “Row Selected”.Drag another label in which we will update the value stored in container and connect it through an outlet.
Next we go to “InterfaceController.swift”. You will see the default methods provided by Xcode. We need to retrieve the value stored in container. “UpdateWatchKitApp” function looks for the changes in the container and updates the label.
Use the following code in InterfaceController of the Watch Kit Extension to update the watch app of the shared container.
import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet weak var updateLabel: WKInterfaceLabel! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateWatchKitApp"), userInfo: nil, repeats: true) self.updateWatchKitApp() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } func updateWatchKitApp() { let userDefaults = NSUserDefaults(suiteName:"group.com.WatchDemoTutorial") userDefaults!.synchronize() if var updatedDictionary : NSDictionary = userDefaults!.objectForKey("currentSelection") as? NSDictionary { var text : NSString = (updatedDictionary.objectForKey("rowSelected") as? NSString)! self.updateLabel.setText(text as String) } } }
Finally we have some code up there to see the results. First run the Project, select some row in you are creating a fresh project or perform those steps which lead to saving of data in container. Stop the app after that.
Next run the Watch Kit Extension, you will see the value stored in container is displayed as text on label. If you are using any other structure of dictionary while storing, use the same while retrieving. Now while the extension is running on the watch simulator, launch the app on iOS simulator by tapping on it. Now, if you will select some other row, the corresponding value will be updated on watch simulator.Upto this point we learnt how to communicate with the iOS app and display the data on watch app. The watch App’s storyboard can be customised more to include more WKInterfaceControllers.
In the starting, we included a glance scene and an notification scene but we didn’t code anything in it. So, now we will have a look at our glance scene.
Step 5. GLANCE SCENE- Glances are used to show the important information which you want to show to the customer. User can have a look at the glances from each app when he slides his finger from bottom to top in the same way as we open Control center in iPhone.
Lets create a glance which displays the information which is saved on the container. When a user taps on the Glance, he is directed in the watch app.
Open the StoryBoard of the WatchKit App and go to the GlanceInterfaceController. You will see that there are 2 groups in it. We can use the upper group to display the App name and lower one to display information. So lets drag drop one label in each group. Add static text to upper label and connect outlet to the second one.
Referring to the code above, the function “updateWatchKitApp()” is used to retrieve the contents in the container. With the same technique we can get the value stored and display it in it the label. After making these changes and running the Glance scheme you will the the App name and the value stored on the glance and tapping on it will take you to the app.
Step 6. NOTIFICATION GLANCE – Notifications where local or remote are displayed using notification scene. It has a short and long look. Long look notification scene is customizable unlike the short look. In your project, you will find “PushNotificationPayload.apns” file. This file is a sample of how the notification will look. The code for this will be written in NotificationController.swift. Depending on the requirement of the project, local or remote or both notifications can be responded to.
Open storyboard of Watch App and click on Static Notification interface controller – i refers to the short look notification while Notification Controller scene depicts the Long Look notification. The short look scene can be changed through the “PushNotificationPayload.apns” file. The array corresponding to the key “WatchKit Simulator Actions” defines the number of buttons and the actions related to them.On clicking of any button the control is delegated to the InterfaceController where the delegate method corresponding to the local or remote notification can be used to steer the flow of the app. Similarly the alert title and alert body can be configured from this file.
Opening NotificationController.swift we can use))
Using the following functions in InterfaceController.swift:
handleActionWithIdentifier(identifier: forRemoteNotification remoteNotification:) for handling remote notifications
handleActionWithIdentifier(identifier: forLocalNotification localNotification:) for handling local notifications
So if you don’t change your “PushNotificationPayload.apns” file and select the notification scheme and run, you will see the short look of the notification first appear which is configured as the payload file. Clicking on any button performs the action assigned to it and takes the user to the app. Use the notification identifier to identify the source of the action. Using this identifier the flow of the app can be altered i.e. some different WKInterfaceController can be displayed.
One should note that in Watchkit App you cannot add WKIntefaceObjects at runtime. They have to be configured in your storyboard. You can show or hide them at runtime. Hiding an element frees the space occupied by it and shifts the rest of the objects to cover its space.
So, with this we finish the setup of basic watch app with Notification and Glance scene. Also we looked on how to set up communication between the iOS and watch app. | http://paxcel.net/blog/apple-watch-app-how-to-go-about-it/ | CC-MAIN-2020-10 | refinedweb | 2,169 | 56.66 |
Bubble Sort in Python
The basic idea behind bubble sort is to compare the first element in list to second element .
Compare the second element to the third element if greater swap the elements.
Compare the third element to the fourth element if greater swap the elements.
Do until the list is sorted.
The Python code for bubble sort.
import numpy as np
a=[10,5,-1,6,7,15,20,16,15,18]
for i in np.arange(10):
for j in np.arange(10-i-1):
if a[j] > a[j+1]:
s=a[j]
a[j]=a[j+1]
a[j+1]=s
print(a)
Output of the program would be
[-1, 5, 6, 7, 10, 15, 15, 16, 18, 20]
Explanation of Program
The statement “import numpy as np” imports numpy module and rename as np.
The statement a=[10,5,-1,6,7,15,20,16,15,18] initialize a list a.
The statement “for i in np.arange(10):” is for passes in bubble sort.
The statement “for j in np.arange(10-i-1):” is for number of comparisons.
The statement “if a[j] > a[j+1]:” compares the adjacent elements in list.
The statements “s=a[j] a[j]=a[j+1] a[j+1]=s” swaps the value of a[j] to a[j+1] if the above statement is true.
The statement “print(a)” prints the sorted list.
Time Complexity of the Bubble Sort Algorithm
If there are n elements in a list then.
The first pass will require (n-1) comparisons.
The the second pass will require (n-2) comparisons.
The third pass will require (n-3) comparisons.
. . . . . . .
. . . . . . .
. . . . . . .
The last pass will require only one pass.
Then the total number of comparisons
=(n-1)+(n-2)+(n-3)+ (n-4)+…………..+1= n(n-1)/2= O(n2)
Then the complexity of bubble sort is O(n2).
Conclusion
Before making bubble sort in Python program you must have made in C/C++ or in Java. However, it is easy way to learn a programming language, to make the same programs what you have built in other languages. | https://www.postnetwork.co/bubble-sort-in-python/ | CC-MAIN-2020-24 | refinedweb | 357 | 77.03 |
A Tutorial Series for Software Developers, Data Scientists, and Data Center Managers
This is the 22nd article in the Hands-On AI Developer Journey Tutorial Series and it focuses on the first steps in creating a deep learning model for music generation, choosing an appropriate model, and preprocessing the data.
This project uses the BachBot* model1 to harmonize a melody that has been through the emotion-modulation algorithm.
Music Generation—Thinking About the Problem
The first step in solving many problems using artificial intelligence is reducing it to a fundamental problem that is solvable by artificial intelligence. One such problem is sequence prediction, which is used in translation and natural language processing applications. Our task of music generation can be reduced to a sequence prediction problem, where we are predicting a sequence of musical notes.
Choosing a Model
There are a number of types of neural networks to consider for a model: feedforward neural network, recurrent neural network, and the long short-term memory network.
Neurons are the basic abstractions that are combined to form neural networks. Essentially, a neuron is a function that takes in an input and returns an output.
Figure 1: A neuron1.
Layers of neurons that take in the same input and have their outputs concatenated can be combined to make a feedforward neural network. A feedforward achieves strong performance due to the composition of nonlinear activation functions throughout many layers (described as deep).
Figure 2: A feedforward neural network1.
A feedforward neural network works well in a wide variety of applications. However, a drawback that prevents it from being useful in the music composition (sequence prediction) task is that it requires a fixed input dimension (music can vary in length). Furthermore, feedforward neural networks do not account for previous inputs, which makes it not very useful for the sequence prediction task! A model that is better suited for this task is the recurrent neural network (RNN).
RNNs solve both of these issues by introducing connections between the hidden nodes so that the nodes in the next time step can receive information from the previous time step.
Figure 3: An unrolled view on an RNN1.
As can be seen in the figure, each neuron now takes in both an input from the previous layer, and the previous time point.
A technical problem faced by RNNs with larger input sequences is the vanishing gradient problem,meaning that influence from earlier time steps are quickly lost. This is a problem in music composition as there important long-term dependencies that need to be addressed.
A modification to the RNN called long short-term memory (LSTM) can be used to solve the vanishing gradient problem. It does this by introducing memory cells that are carefully controlled by three types of gates. Click here for details on Understanding LSTM Networks3.
Thus, BachBot proceeded by using an LSTM model.
Preprocessing
Music is a very complex art form and includes dimensions of pitch, rhythm, tempo, dynamics, articulation, and others. To simplify music for the purpose of this project, only pitch and duration were considered. Furthermore, each chorale was transposed to the key of C major or A minor, and note lengths were time quantized (rounded) to the nearest semiquaver (16th note). These steps were taken to reduce the complexity and improve performance while preserving the essence of the music. Key and time normalizations were done using the music21* library4.
def standardize_key(score):
"""Converts into the key of C major or A minor.
Adapted from
"""
# conversion tables: e.g. Ab -> C is up 4 semitones, D -> A is down 5 semitones
majors = dict([("A-", 4),("A", 3),("B-", 2),("B", 1),("C", 0),("C#",-1), ("D-", -1),("D", -2),("E-", -3),("E", -4),("F", -5),("F#",6), ("G-", 6), ("G", 5)])
minors = dict([("A-", 1),("A", 0),("B-", -1),("B", -2),("C", -3),("C#",-4), ("D-", -4),("D", -5),("E-", 6),("E", 5),("F", 4),("F#",3), ("G-",3),("G", 2)])
# transpose score
key = score.analyze('key')
if key.mode == "major":
halfSteps = majors[key.tonic.name]
elif key.mode == "minor":
halfSteps = minors[key.tonic.name]
tScore = score.transpose(halfSteps)
# transpose key signature
for ks in tScore.flat.getKeySignatures():
ks.transpose(halfSteps, inPlace=True)
return tScore
Figure 4: Code to standardize key signatures of the corpus into either C major or A minor 2.
Quantizing to the nearest semiquaver was done using the music21’s function, Stream.quantize(). Below is a comparison of the statistics about the dataset before and after preprocessing:
Figure 5: Use of each pitch class before (left) and after preprocessing (right). Pitch class refers to pitch without regard for octave 1.
Figure 6: Note occurrence positions before (left) and after preprocessing (right)1.
As can be seen in Figure 5, transposition of key into C major and A minor had a large impact on the pitch class used in the corpus. In particular there are increased counts for the pitches in C major and A minor (C, D, E, F, G, A, B). There are smaller peaks at F# and G# due to their presence in the ascending version of A melodic minor (A, B, C, D, E, F#, and G#). On the other hand, time quantization had a considerably smaller effect. This is due to the high resolution of quantization (analogous to rounding to many significant figures).
Encoding
Once the data has been preprocessed, the chorales needed to be encoded into a format that can be easily processed by an RNN. The format that is required is a sequence of tokens. The BachBot project opted for encoding at note level (each token represents a note) instead of the chord level (each token represents a chord). This decision reduced the vocabulary size from 1284 potential chords to 128 potential notes, which improves performance.
An original encoding scheme was created for the BachBot project 1. A chorale is broken down into semiquaver time steps, which are called frames. Each frame contains a sequence of tuples representing the musical instrument digital interface (MIDI) pitch value of the note, and whether it is tied to a previous note at the same pitch (note, tie). Notes within a frame are ordered by descending pitch (soprano → alto → tenor → bass). Each frame may also have a fermata that signals the end of a phrase, represented by (.). START and END symbols are appended to the beginning and end of each chorale. These symbols cause the model to initialize itself and allow the user to determine when a composition is finished.
START
(59, True)
(56, True)
(52, True)
(47, True)
|||
(59, True)
(56, True)
(52, True)
(47, True)
|||
(.)
(57, False)
(52, False)
(48, False)
(45, False)
|||
(.)
(57, True)
(52, True)
(48, True)
(45, True)
|||
END
Figure 7: Example encoding of two chords. Each chord is a quaver in duration, and the second one has a fermata. ‘|||’ represents the end of a frame1.
def encode_score(score, keep_fermatas=True, parts_to_mask=[]):
"""
Encodes a music21 score into a List of chords, where each chord is represented with
a (Fermata :: Bool, List[(Note :: Integer, Tie :: Bool)]).
If `keep_fermatas` is True, all `has_fermata`s will be False.
All tokens from parts in `parts_to_mask` will have output tokens `BLANK_MASK_TXT`.
Time is discretized such that each crotchet occupies `FRAMES_PER_CROTCHET` frames.
"""
encoded_score = []
for chord in (score
.quantize((FRAMES_PER_CROTCHET,))
.chordify(addPartIdAsGroup=bool(parts_to_mask))
.flat
.notesAndRests): # aggregate parts, remove markup
# expand chord/rest s.t. constant timestep between frames
if chord.isRest:
encoded_score.extend((int(chord.quarterLength * FRAMES_PER_CROTCHET)) * [[]])
else:
has_fermata = (keep_fermatas) and any(map(lambda e: e.isClassOrSubclass(('Fermata',)), chord.expressions))
encoded_chord = []
# TODO: sorts Soprano, Bass, Alto, Tenor without breaking ties
# c = chord.sortAscending()
# sorted_notes = [c[-1], c[0]] + c[1:-1]
# for note in sorted_notes:
for note in chord:
if parts_to_mask and note.pitch.groups[0] in parts_to_mask:
encoded_chord.append(BLANK_MASK_TXT)
else:
has_tie = note.tie is not None and note.tie.type != 'start'
encoded_chord.append((note.pitch.midi, has_tie))
encoded_score.append((has_fermata, encoded_chord))
# repeat pitches to expand chord into multiple frames
# all repeated frames when expanding a chord should be tied
encoded_score.extend((int(chord.quarterLength * FRAMES_PER_CROTCHET) - 1) * [
(has_fermata,
map(lambda note: BLANK_MASK_TXT if note == BLANK_MASK_TXT else (note[0], True), encoded_chord))
])
return encoded_score
Figure 8: Code used to encode a music21* score using the specified encoding scheme2.
Conclusion
This article discussed some of the early steps in implementing a deep learning model using BachBot as an example. In particular, it discussed the advantages of RNN/LSTM for music composition (which is fundamentally a problem in sequence prediction), and the critical steps of data preprocessing and encoding. Because the steps taken for preprocessing and encoding are different in each project, we hope that the considerations described in this article will be helpful.
Check out the next article for information about training/testing the LSTM model for music generation and how this model is altered to create a model that completes and harmonizes a melody.
For more such intel IoT resources and tools from Intel, please visit the Intel® Developer Zone
Source: | https://www.digit.in/apps/hands-on-ai-part-22-deep-learning-for-music-generation-1choosing-a-model-and-data-preprocessing-38468.html | CC-MAIN-2018-51 | refinedweb | 1,492 | 55.13 |
BASIC CHINESE: A GRAMMAR AND WORKBOOK
Praise for the first edition: ‘Very well structured and clearly explained’ Dr Qian Kan, Cambridge University Basic Chinese introduces the essentials of Chinese syntax. Each of the 25 units deals with a particular grammatical point and provides associated exercises. Features include: • • • • •
clear, accessible format many useful language examples jargon-free explanations of grammar ample drills and exercises. Yip Po-Ching was formerly Lecturer in Chinese Studies at the University of Leeds and Don Rimmington is Emeritus Professor of East Asian Studies and former head of the East Asian Studies Department at the University of Leeds. They are the authors of Chinese: An Essential Grammar (1996; 2nd edition, 2006), Intermediate Chinese: A Grammar and Workbook (1998; 2nd edition forthcoming), and Chinese: A Comprehensive Grammar (2004).
Titles of related interest published by Routledge: Intermediate Chinese: A Grammar and Workbook by Yip Po-Ching and Don Rimmington Chinese: An Essential Grammar by Yip Po-Ching and Don Rimmington Chinese: A Comprehensive Grammar by Yip Po-Ching and Don Rimmington Colloquial Chinese: A Complete Language Course by Kan Qian Colloquial Chinese CD-ROM by Kan Qian Colloquial Chinese (Reprint of the ďŹ rst edition) by Ping-Cheng T’ung and David E. Pollard The Chinese Lexicon by Yip Po-Ching Basic Cantonese: A Grammar and Workbook by Virginia Yip and Stephen Matthews Intermediate Other titles available in the Grammar Workbooks series are: Basic Cantonese Intermediate Cantonese
Basic Polish Intermediate Polish
Basic Dutch Intermediate Dutch
Basic Russian Intermediate Russian
Basic German Intermediate German
Basic Spanish Intermediate Spanish
Basic Irish Intermediate Irish
Basic Welsh Intermediate Welsh
Basic Italian Basic Korean Intermediate Korean (forthcoming)
BASIC CHINESE: A GRAMMAR AND WORKBOOK 2nd edition Yip Po-Ching and Don Rimmington with Zhang Xiaoming, Rachel Henson and Yip Li Quzhen
First published 1998 by Routledge 2 Park Square, Milton Park, Abingdon, Oxon OX14 4RN Simultaneously published in the USA and Canada by Routledge 270 Madison Ave, New York, NY 10016 Second edition published 2009 1998, 2009 Yip Po-Ching and Don Rimmington Yip, Po-ching, 1935– Basic Chinese : a grammar and workbook / Yip Po-Ching and Don Rimmington. p. cm. Includes index. 1. Chinese language—Grammar. 2. Chinese language—Syntax. 3. Chinese language—Textbooks for foreign speakers—English. I. Rimmington, Don. II. Title. PL1111.Y56 2009 495.1′82421—dc22 2008031535 ISBN 0-203-88340-3 Master e-book ISBN
ISBN10: 0 – 415 – 47216 – 4 (hbk) ISBN10: 0–415–47215–6 (pbk) ISBN10: 0 –203 – 88340 –3 (ebk) ISBN13: 978 – 0 – 415 – 47216–6 (hbk) ISBN13: 978 –0 – 415 – 47215 –9 (pbk) ISBN13: 978 – 0 –203 – 88340 –2 (ebk)
CONTENTS
Introduction
vii
1
Nouns: singular and plural
1
2
Definite and indefinite reference and demonstratives
8
3
Personal pronouns
17
4
Interrogative pronouns
28
5
Numbers
38
6
Measure words
49
7
Indefinite plurals
63
8
Times and dates
73
9
More interrogative expressions
84
Adjectives: attributive and predicative
93
10 11
shì and
yiu
103
12
Comparisons
113
13
Verbs and location expressions
127
14
Verbs and time expressions
139
15
Verbs and aspect markers
154
16
Modal verbs
165
v
Contents
vi
17
Negators:
bĂš and
( ) mĂŠi(yiu)
174
18
Types of question (1)
185
19
Types of question (2)
196
20
Imperatives and exclamations
206
21
Complements of direction and location (or destination)
214
22
Complements of result and manner
225
23
Potential complements
234
24
Coverbal phrases
242
25
Disyllabic prepositions
255
Key to exercises
264
Vocabulary list: Chinese to English
320
Vocabulary list: English to Chinese
340
Glossary of grammatical terms
359
Index
364
INTRODUCTION
This book is designed to assist learners of Mandarin or Modern Standard Chinese, which is the language spoken by close on 70 per cent of the people of China. It presents the essential features of Chinese syntax in an easily accessible reference-and-practice format. We hope that it will be helpful to students of the language at all levels, though some initial knowledge will be an advantage, and we envisage that it will be suitable for classroom use, as well as for individual study and reference. The book sets forth most of the basic elements of Chinese syntax, dealing with simple sentences and the main grammatical categories. The material is laid out over 25 units, and is introduced on a graded basis with more elementary items in the early units and more complex patterns in the later sections. Each unit deals with an individual language category or structure. In the early stages, of necessity, grammatical items beyond those introduced in a unit are used in the illustrative sentences, but explanatory notes are added for them with cross-referencing to the later units, in which they themselves appear. Each unit also provides follow-up exercises, which are designed for immediate reinforcement and readers are encouraged to make full use of them. A key to the exercises is given at the end of the book. Readers may wish to consult the units separately or work progressively through the book, but we suggest that, when going through a particular unit, they attempt all the exercises in it, before consulting the key. In this second edition extra drills have been provided for each unit, which draw on the additional illustrative material mentioned above and which give an opportunity for the reader to extend and explore his or her learning experience of the language. They of course in many cases anticipate material that is to appear later in the book, but the intention is to encourage from the start practice in the rhythms of the basic structures of the language. It is an advantage when learning any language, and particularly Chinese, if you can develop good speech habits
vii
Introduction
as soon as possible as well as learning grammatical rules. If the exercises are there to help you with the grammatical rules, the drills will help you develop good speech habits. Keys to these drills are provided with the exercise keys at the end of the book. Practical, functional vocabulary is used in the grammatical explanations and in the exercises and drills, and it is introduced as far as possible on a cumulative basis. A complete vocabulary list is appended to facilitate easy reference. The use of grammatical terms is kept to a minimum and explanations of them are given as they occur. In addition a glossary of these terms is included as an appendix. An index is also provided to help locate particular grammatical structures or explanations. All illustrative examples throughout the book are given in Chinese script and pinyin romanization, with colloquial English translations and where necessary with additional literal translations (marked lit.). Students interested in pursuing their practical study of the Chinese language to a higher level should consult the companion volume to this book, Intermediate Chinese: A Grammar and Workbook, where more syntactic patterns peculiar to the Chinese language are explained and the important grammatical items covered in Basic Chinese are summarized. Furthermore, exercises and drills in Intermediate Chinese not only cover specific grammar points but also compare them with English language usage. The preparation of this second edition is based on the first edition of the book, which received financial assistance from the University of Leeds Academic Development Fund. Two Research Assistants, Ms Zhang Xiaoming and Ms Rachel Henson carried out much of the important work of assembling the illustrative material. The present revision, however, could not have been completed without help and contribution from Mrs Yip Li Quzhen, who closely monitored the vocabulary progression, partially revamped the exercises and compiled the vocabulary list. Any errors or omissions are, of course, the fault of the authors. Note: We have used ‘a’ rather than ‘ɑ’, which is the standard form in pinyin romanization.
viii
UNIT ONE Nouns: singular and plural
A In Chinese, as in other languages, nouns may be differentiated into a number of categories. The largest category is the common noun, which covers tangible, discrete entities, e.g. dàren adult, shù tree, etc. The common noun is the main focus of this unit, but other noun categories are: (i) proper noun (for one individual entity): e.g. zhdngguó China, lh míng Li Ming (name of a person) (ii) material noun (for non-discrete entities): e.g. zhh paper, chá tea (iii) abstract noun (for non-tangible entities): e.g. wénhuà culture, jcngjì economy B Chinese common nouns, unlike English ones, make no distinction in form between singular and plural: pínggui háizi yc gè pínggui lifng gè pínggui yc gè háizi lifng gè háizi
apple/apples child/children an/one apple two apples a/one child two children
C Another important feature of the common noun in Chinese is that when it is used with a numeral, the numeral has to have a measure word between it and the noun (see also Unit 6). gè (usually unstressed as ge in actual speech) is by far the most common measure word and it can occur with a wide range of nouns: yc gè rén lifng gè xuésheng san gè miànbao sì gè chéngzi
a/one person two students three bread rolls/three buns four oranges
1
1 Nouns: singular and plural
wj gè jcdàn liù gè chéngshì qc gè guójia ba gè shangdiàn jij gè nán háizi shí gè ns háizi jh gè péngyou
five eggs six cities seven countries eight shops nine boys ten girls a few friends
A considerable number of nouns or sets of nouns are linked with particular measure words: yc yc yc yc
bgn she zhc bh bf yáshua kb shù
a/one a/one a/one a/one
book pen toothbrush tree
Some Chinese measure words that indicate portion or partition, for example, are similar to English measures: lifng piàn miànbao yc kuài dàngao yc bbi kafbi yc bbi píjij
two slices of bread a piece of cake a cup of coffee a glass of beer
Measure words are also used with abstract and material nouns: yc yc yc yc yc
gè jiànyì gè jièkiu gè lhxifng zhang zhh kuài bù
a suggestion an excuse an ambition/ideal a piece of paper a piece of cloth
(abstract) (abstract) (abstract) (material) (material)
Note 1: Notice that with yc you distinguish between ‘a/an’ and ‘one’ in speech by the degree of emphasis given to it. The phrase yc gè bbizi, for example, may mean ‘one mug’ if yc is stressed and ‘a mug’ if yc is not stressed. In the latter meaning yc can be omitted altogether if it comes directly after a monosyllabic verb. ( ) wi xifng qù shangdiàn mfi (yc) gè bbizi ( yc is unstressed and optional) I’m going to the shop to buy a mug. 2
wi zhh yào mfi yc gè bbizi ( I only want to buy one mug.
yc is stressed)
Note 2: In Chinese as ‘mug’.
bbizi may mean ‘cup’ or even ‘glass’ as well
1 Nouns: singular and plural
Note 3: xifng and yào are both modal verbs, i.e. verbs which precede main verbs to indicate the mood or attitude of the subject (see Unit 17). While xifng emphasizes ‘plan’ or ‘inclination’, yào indicates ‘wish’ or ‘will’. They may generally be used interchangeably. D It is possible to pluralize human nouns by adding the suffix men but only when the people concerned are seen or addressed as a group. A collectivized noun like this undergoes two changes: (i) A noun with men suffix becomes definite in reference. Being of definite reference, this form may be used to address a particular audience: . . . xianshengmen, Ladies and gentlemen nsshìmen . . . ... péngyoumen Friends . . . ...
...
(ii) A collectivized noun with men suffix is incompatible with a ‘numeral + measure word’ phrase: One cannot say: * *
san gè gdngchéngshcmen (lit. three engineers) jij gè dàrenmen (lit. nine adults)
However, it is not possible to collectivize non-human nouns with the suffix men: * *
giumen bbizimen
(lit. dogs) (lit. cups/glasses/mugs)
E Nouns or noun phrases (e.g. ‘numeral + measure word + noun’) may be linked together by the conjunction hé ‘and’: bh hé zhh pens and paper nán háizi hé ns háizi boys and girls
3
1 Nouns: singular and plural
san gè dàngao hé sì gè miànbao three cakes and four bread rolls zhdngguó jcngjì hé wénhuà China’s economy and culture ta yiu lifng bgn she hé yc zhc bh He has two books and one pen. wi yào chc lifng piàn miànbao | yc gè jcdàn hé yc kuài dàngao I want to eat two slices of bread, an egg and a piece of cake.
Note: Observe that a Chinese full-stop is a hollow dot, not a solid one as in English; and the ‘ ’ dun-comma, seen in this last example, is peculiar to Chinese punctuation and is used for listing items in a series:
ta xifng mfi sì gè pínggui | san gè chéngzi | lifng gè miànbao hé yc dá jcdàn She would like to buy four apples, three oranges, two loaves of bread and a dozen eggs.
Exercise 1.1 Translate the following phrases into Chinese:
4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
a child one child two children three oranges a dozen eggs four bread rolls five slices of bread a city two suggestions six countries eight shops nine students seven engineers a friend a person
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
one mug two pens ten cups two cups of tea three books four adults six pieces of paper a cake a piece of cake an excuse five boys six girls two pieces of cloth a few trees two Chinese
Exercise 1.2 Decide on the emphasis given to yc in the sentences below by putting brackets round the where it may be omitted:
1 Nouns: singular and plural
1 wi xifng jiao (yc) gè zhdngguó péngyou I would like to have a Chinese friend. ( jiao ‘to make friends with’) 2 wi xifng mfi yc dá jcdàn I want to buy a dozen eggs. 3 ta zhh shì yc gè xuésheng He is only a student. 4 wi xifng chc yc gè chéngzi I want to eat an orange. 5 wimen yiu yc gè jiànyì We have a suggestion. 6 wi zhh xifng qù yc gè guójia I only want to go to one country. 7 wi yào qù mfi yc bf yáshua I want to go and buy a toothbrush. 8 ta zhh yiu yc gè háizi She only has one child.
Exercise 1.3 Decide which of the following sentences are incorrect and make the necessary corrections: 1
wi pèngjiàn lifng gè péngyoumen ( pèngjiàn ‘to bump into’) I bumped into two friends.
2
ta xifng zhfo yc jièkiu ( He wanted to find an excuse.
zhfo ‘to find’) 5
1 Nouns: singular and plural
3
háizimen yào chc píngguimen The children wanted to eat apples.
4
tamen xifng qù san guójia They would like to visit three countries.
5
wi xifng hb bbi chá ( I would like to have a cup of tea.
6
ta yiu zhdngguó péngyoumen She has Chinese friends.
7
nh yào chc jh miànbao How many slices of bread would you like to eat?
8
shuí/shéi yào mfi jcdàn Who wants to buy eggs?
hb ‘to drink’)
Exercise 1.4 Translate the sentences below into English: 1 2 3 4 5 6 7 8 9 10
wi yào mfi jh gè miànbao ta xifng chc lifng kuài dàngad wi pèngjiàn san gè zhdngguó rén wi yào hb bbi kafbi wi xifng qù wj gè guójia ta shì yc gè gdngchéngshc wi yiu lifng gè háizi wi zhh xifng qù yc gè chéngshì shuí/shéi xifng mfi she wi yiu gè jiànyì
Exercise 1.5 Translate the following phrases and sentences into Chinese. Don’t forget to use the dun-comma where necessary.
6
1 2 3 4 5 6 7
apples and oranges adults and children three slices of bread, a cup of coffee and a piece of cake four books and six pens I would like to visit three countries. I would like to have a cup of tea. She only wants to go to two shops.
8 9 10 11 12
She wants to buy a bread roll, two cakes, five apples and a dozen eggs. The child has only one ambition. I bumped into four Chinese friends. I want a few pieces of paper. I want to know something about China’s economy and culture. ( lifojig ‘to know or understand’)
1 Nouns: singular and plural
Pattern and vocabulary drill 1.1 Complete the following sentences using the examples indicated: 1
. . . wi yào mfi . . . I would like to buy . . . a. some eggs b. a few bread-rolls d. some oranges
2
. . . wi xifng hb . . . I would like to drink . . . a. a cup of tea b. a cup of coffee d. a glass of coke ( kglè)
3
c. a book and a pen
c. a glass of beer
. . . wi xifng chc . . . I would like to eat . . . a. an apple b. an orange c. a piece of cake d. a sandwich ( sanmíngzhì)
4
. . . wi yào qù . . . I would like to go to . . . a. China b. Britain ( ycngguó) c. Beijing ( d. London ( lúnden)
5
blijcng)
. . . wi xifng jiao . . . I would like to make friends with . . . a. a few Chinese friends
b. some English friends
Pattern and vocabulary drill 1.2 Change all the statements you have completed in Drill 1.1 into questions, using shéi ‘who’ as the subject instead of wi ‘I’: wi yào mfi jh gè pínggui I would like to buy a few apples. shéi yào mfi jh gè pínggui Who would like to buy a few apples?
7
UNIT TWO Definite and indefinite reference and demonstratives
A Reference is an important aspect of common nouns. As there are no definite or indefinite articles ‘the/a(n)’ in Chinese, definite or indefinite reference is indicated by the positioning of the noun in the sentence. Generally speaking, a noun placed before the verb will be of definite reference, while a noun placed after the verb will be of indefinite reference. Definite reference:
(
bh zài nfr Where is the pen?/Where are the pens? bh ‘pen’ is positioned before the verb zài ‘be in/at’.)
Indefinite reference: nfr yiu bh Where is there a pen?/Where are there some pens? ( bh ‘pen’ is positioned after the verb yiu ‘exist’.) In fact, any noun used on its own is subject to this general principle. The English translations of the following examples provide the referential clues: bìngrén zài nfr nfr yiu ycshbng wi xhhuan chc xiangjiao nh zhfo máoyc ma
8
Where is the patient? Where is there a doctor? I like (eating) bananas. Are you looking for your sweater/jumper?
Note: ma is a sentence particle which is used at the end of a statement to convert it into a general question asking for either confirmation or denial (see Unit 18).
Even a noun apparently made indefinite by its ‘numeral (other than yc ‘one’) + measure’ phrase, may still be regarded as of definite reference when placed before the verb, particularly when ddu or yg is present to refer back to the noun in question: san gè háizi ddu shàngxué All the three children go to school. (lit. three children all go to school)
2 Definite and indefinite reference and demonstratives
lifng jiàn máoyc yg zài guìzi li Both of the jumpers are also in the wardrobe. Note: guìzi is a general term in Chinese which may mean ‘wardrobe’, ‘cabinet’, ‘cupboard’, etc. depending on the context.
B However, this general rule may be nullified if the speaker is making a general comment rather than narrating an event or incident. The comment in a topic-comment sentence, as we shall see, usually consists of an adjective, the verb shì ‘to be’, a modal verb or a verb that indicates a habitual action: xiangjiao hgn hfochc chéngzi bù shì shecài mao huì zhua lfoshj mf chc cfo
Bananas are delicious. Oranges are not vegetables. Cats can catch mice. Horses eat grass.
(adjective) (verb shì ‘to be’) (modal verb) (verb that indicates a habitual action)
In the above examples, xiangjiao ‘bananas’, chéngzi ‘oranges’, mao ‘cats’ and mf ‘horses’, as topics to be commented on, are of indefinite reference, in spite of the fact they are placed before the verb. Note: The distinction between subject-predicate and topiccomment sentences is discussed in detail in Intermediate Chinese, Unit 7.
C On the other hand, a noun before the verb may be made to take on indefinite reference if it is preceded by yiu ‘have/exist’:
9
2 Definite and indefinite reference and demonstratives
yiu rén zhfo nh There is someone looking for you. yiu máoyc zài guìzi li There is a sweater/there are (some) sweaters in the wardrobe. In these sentences with yiu a numeral (including yc ‘a(n); one’) or an expression such as ( ) (yc)xib ‘some’ or jh + measure ‘a few’ may be used with the noun: ( ) yiu (yc) gè ycshbng qhng bìngjià A doctor was on sick leave. (lit. There was a doctor [who] asked for sick leave.) ( ) yiu (yc) gè ns ycshbng zài bìngfáng li A lady doctor is in the ward. (lit. There is a female doctor [who] is in the ward.) yiu lifng gè jcdàn zài wfn li There are two eggs in the bowl. ( ) yiu (yc)xib huar zài huapíng li There are some flowers in the vase. yiu jh bgn she zài shejià shang There are a few/several books on the (book)shelf. As can be seen from the examples above, these yiu sentences can express the presence of a person or thing in a place, with or without a clear indication of the location. Where the location is indicated, a more common way of phrasing such sentences is to begin with the location phrase (e.g. huapíng li ‘in the vase’, shejià shang ‘on the bookshelf’), since it is likely to be of definite reference and a pre-verbal position is therefore more natural (see Units 11 and 13): ( ) huapíng li yiu (yc)xib huar There are some flowers in the vase. (lit. In the vase there are some flowers.) shejià shang yiu jh bgn she There are a few books on the (book)shelf. (lit. On the bookshelf there are a few books.) wfn li yiu lifng gè jcdàn There are two eggs in the bowl. (lit. In the bowl there are two eggs.)
10
2 Definite and indefinite reference and demonstratives
wezi li yiu yc zhang zhudzi hé sì bf yhzi There are a table and four chairs in the room. (lit. In the room there are a table and four chairs.) ( ) zhudzi shang yiu (yc) gè huapíng There is a vase on the table. (lit. On the table there is a vase.) guìzi li yiu maóyc There is a sweater/are sweaters in the wardrobe. (lit. In the wardrobe there is a sweater/are sweaters.) bìngfáng li yiu sì gè bìngrén There are four patients in the ward. nàr yiu bh | zhèr yiu zhh There is a pen/are pens over there and (there is) some paper here. (lit. There there is a pen/are pens, here there is some paper.) D Demonstratives are by definition context-based. They naturally zhè and ‘that’ is nà: indicate definite reference. In Chinese ‘this’ is zhè shì kafbi | nà shì chá This is coffee and that is tea. In Chinese, when demonstratives are followed by a noun, as with numbers, a measure is required between the demonstrative and the noun. When used in this way, zhè may also be pronounced ‘zhèi’ and nà, ‘nèi’. The probable explanation for this is that ‘zhèi’ and ‘nèi’ are fusions of ‘zhè + yc’ and ‘nà + yc’: zhèi gè rén nèi zhang zhudzi zhèi zhc giu nèi zhc mao
this person that table this dog that cat
wi péngyou xhhuan zhèi zhang zhàopiàn My friend likes this photograph. wi bù xhhuan nèi fú huàr I don’t like that painting. In the plural, these demonstratives are followed by measure word phrase to mean ‘these’ or ‘those’:
xib or a
jh + 11
2 Definite and indefinite reference and demonstratives
ta yào zhèi xib maóyc She wants these sweaters. ta yào zhè jh jiàn máoyc She wants these (few) sweaters. wi mfi nèi xib wfn I’ll buy those bowls. wi mfi nà jh zhc wfn I’ll buy those (few) bowls. When zhè and nà are used in conjunction with a numeral, the word order is demonstrative + number + measure: nh xhhuan zhè lifng zhang zhàopiàn ma Do you like these two photo(graph)s? nh zhfo nà san bf yàoshi ma Are you looking for those three keys? When the context is clear, the noun, of course, may be omitted: wi yào zhèi gè I want this one. ta xhhuan nèi lifng jiàn He likes those two. (e.g. sweater, shirt, etc.) wi xhhuan zhèi zhang | bù xhhuan nèi zhang I like this one, but I don’t like that one. (e.g. photographs, paintings, etc.) E Finally, as we have seen context is always an important factor in Chinese. If an object or a matter has already been mentioned in a particular context, then this will give it a consequential definite reference. For example, in the sentence: nh qù mfi she ma
12
the unmarked noun she ‘book’ would normally be of indefinite reference because it comes after a verb (where it would mean: ‘Are you going to buy a book/some books?’). However, it would take on definite reference if the communicators were already aware from their previous exchange that she here refers to a book or books they have been talking about. This would make it mean: ‘Are you going to buy the book(s)?’
The indefinite reference of an unmarked noun after the verb can, of course, always be countered by the presence of a demonstrative: nh qù mfi nèi bgn she ma Are you going to buy that book?
Exercise 2.1
2 Definite and indefinite reference and demonstratives
Complete the translations below by filling in the blanks: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
this pen bh these pens bh that orange chéngzi those oranges chéngzi those (few) children háizi these (few) tables zhudzi that cup/glass/mug bbizi this book she those schoolbags shebao those (few) bookshelves shejià this vase huapíng these (few) vases huapíng that kitchen chúfáng these flowers huar those trees shù that piece of cake dàngad that school xuéxiào this toothbrush yáshua that slice of bread miànbao these keys yàoshi those umbrellas yjsfn that shop shangdiàn those (few) chairs yhzi these (few) paintings huàr these two doctors ______ ______ ______ ycshbng those few patients ______ ______ ______ bìngrén
Exercise 2.2 Indicate which of the two English translations below is the correct version of the Chinese in each case: 1
ta xhhuan giu She likes the dogs./She likes dogs.
13
2 Definite and indefinite reference and demonstratives
2
wi mfi zhèi dhng màozi ( dhng measure word for hats/caps) I’ll buy this hat./I’ll buy that hat.
3
nh dài yjsfn ma ( dài ‘to bring along; to take with’) Are you bringing an umbrella with you?/Are you bringing the umbrella with you?
4
yàoshi zài nfr Where are the keys?/Where can I find some keys?
5
nh dài máoyc ma Are you bringing along a jumper/sweater?/Are you bringing along the jumper?
6
ta yiu háizi ma Has she got any children?/Has she got the children?
7
zhudzi shang yiu zhc wfn There is a bowl on the table./The bowl is on the table.
8
yiu jiàn máoyc zài guìzi li The jumper is in the wardrobe./There is a jumper in the wardrobe.
9
kuàizi zài zhudzi shang The chopsticks are on the table./There are chopsticks on the table.
10
wi huì zhua kuàizi ( huì ‘know how to’) I know how to use chopsticks. (lit. I know how to grasp chopsticks.)/ I know how to use the chopsticks.
Exercise 2.3 Translate the following sentences into English paying attention to whether the nouns involved are of definite or indefinite reference. In some cases the noun could be either definite or indefinite depending on the possible contexts.
14
1 2 3 4 5 6 7 8 9 10
nfr yiu she she zài nfr chúfáng li yiu yc gè dàngao mao zài wezi li nh zhfo yàoshi ma nh mfi yjsfn ma nh chc xiangjiao ma wimen xifng mfi huar háizimen zài xuéxiào li wi xhhuan chc pínggui
11 sì jiàn máoyc hé san dhng màozi ddu zài guìzi li 12 shí gè xuésheng ddu xifng qù zhdngguó 13 nh yiu kuàizi ma 14 pínggui | chéngzi | dàngao hé miànbao ddu zài chúfáng li
2 Definite and indefinite reference and demonstratives
Exercise 2.4 Translate the following sentences into Chinese: 1 2 3 4 5
6 7 8 9 10 11 12 13 14 15
Where are there any shops? Oranges are good to eat. There are a few mugs on the table. There are some books on the bookshelf. Do you have a pen on you? (Hint: you can formulate this sentence using the verb dài ‘to bring along with’ or you can use the location phrase shbnshang lit. ‘on body’.) The bowls are in the cupboard. Where is the key? There are some flowers in the vase. Where are the boys? Do you have a jumper? Do you like these photo(graph)s? Are you looking for the books? These two books are very interesting. ( yiu yìsi ‘interesting’) I like those three pictures. Where are those five students?
Pattern and vocabulary drill 2.1 Following the patterns below, in each case formulate the question or statement separately as appropriate for (a) and (b): 1
. . . nfr yiu . . . Where is there a . . . ? (when you need to locate (a) a pen and (b) a chair)
. . . zài nfr Where is the . . . ? 2 ... (when you want to know where (a) the toilet ( (b) where the station ( chbzhàn) is) 3
cèsui) is and
yiu . . . zài bìngfáng li There is/are . . . in the ward ... (when you are explaining that there are (a) a male doctor and a lady doctor (b) nine patients in the ward)
15
2 Definite and indefinite reference and demonstratives
4 ... . . . zài chúfáng li The . . . is/are in the kitchen (when you are pointing out that (a) the bowls and chopsticks and (b) the knives and forks are in the kitchen) 5
... guìzi li yiu . . . . There is/are . . . in the cupboard (when you are saying that there are (a) tea and coffee and (b) some mugs in the cupboard)
Pattern and vocabulary drill 2.2 Change the following statements into general questions using Model: Answer:
1 2 3 4 5 6 7 8 9 10
ma:
wi xhhuan chc xiangjiao I like eating bananas. nh xhhuan chc xiangjiao ma Do you like eating bananas? wi xhhuan chc dàngao wi xhhuan hb píjij wi xhhuan chc shecài wi xhhuan jiao péngyou wi xifng hb bbi kafbi wi xifng mfi zhc bh wi yào mfi jh bgn she wi xifng mfi xib huar wi de mao huì zhua lfoshj ( huà ‘draw; paint’) wi huì huà huàr
Note: If xifng and yào indicate wills and wishes on individual occasions, xhhuan indicates habitual preferences.
16
UNIT THREE Personal pronouns
A Chinese personal pronouns
1st person
2nd person
3rd person
Singular wi I/me
nh you nín you (polite form) ta he/him ta she/her ta it
Plural wimen we/us zánmen we/us (including the listener) nhmen you
tamen they/them (masculine) tamen they/them (feminine) tamen they/them (neuter)
As can be seen the personal pronouns have no case distinctions: wi shì zhdngguó rén ta lái kàn wi nh hfo nhmen zhù zài nfr wimen bù rènshi tamen tamen bù xhhuan ta zhù nh shbngrì kuàilè
I am Chinese. She came to see me. Hello!/How are you? Where do you (plural) live? We don’t know them. They don’t like her. Happy birthday! (lit. Wish you birthday happy.)
Note: As and are both pronounced ta, gender differentiation in speech (rather than in writing) is only possible through context.
17
3 Personal pronouns
B zánmen ‘we, us’ is employed only when the speaker wants consciously to include the listener(s): zánmen ziu ba Let’s go. zàijiàn | wimen Goodbye. We’re off now. ziu le Note 1: In ordinary conversation the distinction between zánmen ‘we (inclusive)’ and wimen ‘we (exclusive)’ is not strictly followed, particularly in the south of the country, where zánmen may often be replaced by wimen, though not the other way round when the speaker wants to exclude the listener(s): e.g. wimen zìjh lái ‘We’ll help ourselves/manage by ourselves.’ ba is a sentence particle for a tentative request (see Unit Note 2: 20), and le is a sentence particle used to signal the beginning of a new situation of some kind as is made clear in the statement above (see Intermediate Chinese Unit 8). C
ta/
tamen is mostly used to refer to animals:
nh zhfo dào le nèi zhc mao méiyiu Have you found that cat? zhfo dào le | ta zài huayuán li I have found it. It’s in the garden. shuhchí li yiu hgn dud jcnyú | tamen ddu hgn hfokàn There are a lot of goldfish in the pool. They are all very beautiful. ta/ tamen is rarely used to refer to inaniIn spoken Chinese, mate objects since the reference is usually clear without it: zìxíngchb nh xie hai le méiyiu Have you repaired your bicycle? xie hfo le Yes, I have (repaired it). (lit. repair good)
18
nh kàn le nèi gè diànyhng méiyiu Did you see that film? kàn le | kgshì bù xhhuan Yes, but I didn’t like it.
One does not usually say: * *
3 Personal pronouns
xie hfo ta le kàn le ta | kgshì bù xhhuan ta
It occurs only occasionally in expressions where without it ambiguity might arise: bié dòng ta
Don’t touch it!
bié dòng
Don’t you move!
bié gufn ta ba
Don’t bother about it.
nh bié gufn
None of your business.
vs
vs
D nín is the polite form of nh. It is a fusion of nh and men and therefore has no plural form. (One cannot say * nínmen.) To express a plural for nín, one uses an appositional phrase: nín san wèi shì zhdngguó rén ma Are the three of you Chinese? nín jh wèi shì nf guó rén Where are you (people) from?
Note: normal
wèi is a more polite measure word for ‘people’ than the gè.
E Possession, whether as an adjective or a pronoun, is indicated by the addition of the particle de to the personal pronoun: wi de wimen de nh de nhmen de ta de tamen de ta de tamen de ta de tamen de
my/mine our/ours your/yours your/yours his their/theirs her/hers their/theirs its their/theirs
(masculine) (feminine) (neuter)
19
3 Personal pronouns
nh de jiàoshì zài nfr Where is your classroom? zhè shì tamen de chb This is their car. nèi bf yjsfn shì wi de That umbrella is mine. de may be omitted before nouns where the possessor has a close relationship with the person or object: wi mama xifng gbn nh mama tántan My mother would like to talk to your mother. wi gbge xifng rènshi nh dìdi My older brother would like to meet/get to know your younger brother. nh fùmj hfo ma How are your parents? nh jia zài nfr Where is your home?
Note 1:
de may also be used after nouns to indicate possession:
wi mèimei xhhuan qí wi jigjie de zìxíngchb My younger sister likes to ride my elder sister’s bicycle. wi dìdi xhhuan línje de nèi zhc xifo mao My younger brother likes that kitten of our neighbours. wi jigjie xhhuan kai bàba de chb My elder sister likes driving father’s car.
Note 2: The possessive phrase always comes before the demonstrative:
20
línje de nèi zhc xifo mao wi de nèi jìan máoyc nh de zhèi xib she ta de zhè jh fú huàr
that kitten of our neighbours that jumper of mine these books of yours these few paintings of his
zìjh ‘oneself’:
F
(i) It is used immediately after the subject in apposition to it:
( )
wimen zìjh méi yiu diànshì(jc) ta zìjh ziu le wi zìjh lái
3 Personal pronouns
We don’t have a television (set) ourselves. He left by himself. I’ll do it (by) myself./ I’ll help myself. (e.g. at a meal)
Note: lái which basically means ‘to come’ is used here in an idiomatic sense to indicate personal involvement.
(ii) It may also be used as a reflexive object: bié mà zìjh Don’t blame yourself. (iii) With the addition of the particle de, it means ‘one’s own’: zhè shì wi zìjh de shìr This is my (own) business. G There are a few less conventional pronouns like dàjia ‘everybody’, rénjia ‘others’, etc. rén ‘person’ when used on its own as the object of a verb means ‘anybody’: dàjia hfo Good morning/afternoon/evening, everybody! (lit. everybody good) nh huì | rénjia bù huì You know how to do it; but other people (me included) don’t. nèi bgn she bù shì wi zìjh de | shì rénjia de That book is not my own; it is somebody else’s. lái rén na yòu rén ma
Note:
Help! (lit. come anybody) Anybody there/in? (lit. have anybody)
na is an exclamatory sentence particle. (See Unit 20 J) 21
3 Personal pronouns
Exercise 3.1 Complete the Chinese translations of the English sentences below by adding the correct personal pronouns where necessary. (Bear in mind that it may not be necessary to fill in the blanks in all cases.) 1 I like him, and he likes me, too. ( yg ‘also’) xhhuan | yg xhhuan 2 We want to see them, but they don’t want to see us. ( xifng qù jiàn
dànshì ‘but’) | dànshì
bù xifng jiàn
3 You don’t know her, but she knows you. bù rènshi | dànshì rènshi 4 Dad, Mum, would you like some coffee? bàba | mama | yào hb kafbi ma 5 Where is she? I want to talk to her. zài nfr | xifng gbn tántán 6 We have two dogs. They live in his room. ( tiáo measure word for dogs) yiu lifng tiáo giu | ddu zhù zài fángjian li 7 I don’t like those flowers. Do you like them? bù xhhuan nà/nèi xib huar | xhhuan 8 Do you want to see that film? Let’s go and see it. nh xifng kàn nà/nèi gè diànyhng ma | zánmen qù kàn
ma
ba
Exercise 3.2 Complete the Chinese translations of the following by filling in the blanks: 1 I like my work.
22
wi xhhuan 2 Is Li Ming a good friend of yours? ( ) lh míng shì ( ) háo péngyou ma
gdngzuò
3 My family live in the country. jia zhù zài xiangcen ( 4 This book is my older brother’s.
xiangcen ‘the countryside’)
3 Personal pronouns
zhèi bgn she shì 5 That hat is hers. nèi dhng màozi shì 6 Those three children are all our neighbours’. nà san gè háizi ddu shì 7 Their parents don’t live in London. ( ) ( ) fùmj bù zhù zài lúnden ( fùmj ‘parents’) 8 This is her daughter and that is my son. ( ) ( ) zhè shì ( ) ns’ér | nà shì ( ) érzi 9 The kitten is sleeping on Father’s chair. xifo mao shuì zài 10 This is our classroom.
yhzi shang
zhè shì jiàoshì ( 11 He often repairs his car himself.
jiàoshì ‘classroom’)
ta chángcháng xie qìchb 12 That child doesn’t have a bicycle of his own. nèi gè háizi méi yiu
zìxíngchb
Exercise 3. Yours is in the wardrobe. zhèi jiàn máoyc shì 5 Have you ever met my parents?
|
zài guìzi li
nh jiàn guo fùmj ma 6 Do you know his father? nh rènshi bàba ma 7 Your apples taste nice; mine are awful. pínggui hgn hfochc | bù hfochc 8 These three pictures are yours; those two are hers. zhè san fú huàr shì
| nà/nèi lifng fú shì
9 My elder sister likes driving Father’s car, but doesn’t like riding her own bicycle. ( ) wi jigjie xhhuan kai chb | dànshì bù xhhuan qí ( ) zìxíngchb 10 The garden at your home is very pretty. huayuán hgn hfokàn 11 I like those goldfish of our neighbours.
wi xhhuan jcnyú 12 My younger brother does not like wearing that jumper of his. ( ) wi dìdi bù xhhuan chuan ( máoyc
)
Exercise 3.4 Replace nh and polite forms: 24
nhmen in the following sentences with their
1
nh xifng hb bbi chá ma Would you like some tea? 2 nhmen shì nf guó rén Which country are you all from? 3 nhmen qhng zuò ( qhng ‘please’; zuò ‘to sit’) Please take a seat. (addressing a few visitors) 4 nh shì ycngguó rén ma Are you from Britain? 5 nhmen yào chc difnr dàngao ma ( difnr ‘a bit (of)’) Would you like some cake? 6 wi gòu le | xièxie nh ( gòu ‘enough’) I’m fine/I’ve had enough, thanks.
3 Personal pronouns
Exercise 3.5 Decide whether wimen or in the following situations:
zánmen should strictly be used
1 We must be off now. Goodbye. ziu le | zàijiàn 2 Let’s be friends. jiao gè péngyou ba 3 We would like some beer. Thank you. xhang hb difnr píjij | xièxie nín ( píjij ‘beer’) 4 I am Li. What’s your name? Do let us introduce ourselves. wi xìng lh | nín guìxìng | 5 Let’s go together.
rènshi ycxià ba (
ycqh ziu ba ( 6 We live in London. Where do you live?
ycxià ‘briefly’) ycqh ‘together’)
zhù zài lúnden | nhmen zhù zài nfr
Pattern and vocabulary drill 3.1 Translate the following sentences into English, making intelligent guesses at the meaning with the help of the words given in brackets: 25
3 Personal pronouns
1 2 3 4 5 6
/ zhù nh/nín shbngrì kuàilè / zhù nh/nín xcnnián kuàilè ( xcnnián ‘new year’) / zhù nh/nín shèngdàn kuàilè ( shèngdàn ‘Christmas’ ) / zhù nh/nín shbnth jiànkang ( shbnth ‘body’; jiànkang ‘healthy’) / zhù nh/nín yclù píng’an ( yclù ‘all the way’; píng’an ‘safe and sound’) / zhù nh/nín chénggdng ( chénggdng ‘succeed’)
Pattern and vocabulary drill 3.2 Translate the following sentences into Chinese, following the model of the examples. Pay particular attention to how adjectives are coined with yiu ‘to have’ and hfo ‘good’. Don’t forget to include the degree adverb hgn in each instance: My work is interesting. wi de gdngzuò hgn yiuqù This piece of cake is delicious. zhèi kuài dàngao hgn hfochc
26
1 Those books of yours are interesting. ( yiuqù ‘interesting’) 2 His parents are famous. ( yiumíng ‘famous (lit. to have name)’) 3 Those three Chinese (persons) are very rich. ( yiuqián ‘rich (lit. to have money)’) 4 Your father’s book is really useful. ( yiuyòng ‘useful (lit. to have use)’) 5 This method is truly effective. ( fangff ‘method’; yiuxiào ‘effective (lit. to have effect)’) 6 That cake of yours is really tasty. This cup of coffee is really nice. ( hfochc/ hfohb ‘tasty, nice (lit. good to eat/good to drink)’) 7 That jumper of my younger sister is beautiful. ( hfokàn ‘pleasant to the eye’) 8 That song is pleasant to the ear. ( gb ‘song’; shiu measure word for songs; hfotcng ‘pleasant to the ear’) 9 That suggestion of his was ridiculous. ( hfoxiào ‘laughable/ ridiculous’) hfowánr 10 That kitten of our neighbours is really playful. ( ‘amusing (lit. good to play with)’)
Pattern and vocabulary drill 3.3 As we have seen, when a noun is placed at the beginning of a sentence, it is to some extent emphasized, as it registers what is foremost in the speaker’s mind. Following the model below, construct ten questions using the noun and verb given and translate the questions into English. The assumption is that the noun object has already been alluded to and is therefore of definite reference.
3 Personal pronouns
bh dài Have you brought the pen(s) with you? bh nh dài le méiyiu 1 2 3 4 5 6 7 8 9 10
yàoshi dài yjsfn dài máoyc dài zhàopiàn dài she kàn wfn kuàizi mfi chá hb dàngao chc mao zhfo dào diànyhng kàn
27
UNIT FOUR Interrogative pronouns
A The main interrogative pronouns in Chinese are: shéi (shuí – less colloquial) shéi de shénme nf/ngi + measure word nfr/ shénme dìfang
who/whom whose what which where/what place
B The most important feature about Chinese interrogative pronouns is that, unlike English practice which shifts all interrogative pronouns to the beginning of the question, Chinese keeps them in the position in the sentence where the answers would be expected: ta shì shéi ta shì wI de lFoshC
Who is he?r Li has left. Who did you go to see? I went to see Mr/Mrs Zhang, the manager. Whose is this satchel?
4 Interrogative pronouns
This is my coursemate’s satchel. What would you like to drink? I would like to have some beer. What are you looking for? I’m looking for my watch. Where is my coat? Your coat is here.
C In addition to shéi/shuí, nf/ngi wèi (lit. ‘which person’) may be used to express a more respectful personal enquiry: ngi wèi shì nh bàba nín yào jiàn ngi wèi
Which person is your father? Who do you want to see?
Note: shénme rén (lit. ‘what. nh xhhuan shéi de huàr (adjective) Whose picture do you like? wi xhhuan nèi gè huàjiA de huàr I like pictures by that artist. E shénme ‘what’ likewise may be used as an adjective or a pronoun: zhèi xib shì shénme shecài (adjective) What kind of vegetables are these? zhèi xib shì báicài These are Chinese cabbages. zhèi xib shì shénme (pronoun) What are these? zhèi xib shì lí These are pears. ( ) nh xifng chc (yc)difnr shénme (pronoun) What would you like (to eat)? ( ) wi xifng chc (yc)difnr dàngAo I’d like (to eat) some cake. ( ) nh mfi le (yc)xib shénme ddngxi (adjective) What things did you buy? wi mfi le yC píng kAfBi | yC bAo cháyè hé yC shù xiAnhuA I bought a bottle of coffee, a packet of tea and a bunch of flowers. nh míngtian xifng zuò shénme (pronoun) What do you want to do tomorrow? wi míngtian xifng qù yóuyIng I want to go swimming tomorrow.
30
F nf/ngi meaning ‘which’ (not to be confused with nfr ‘where’) can only be used in conjunction with a measure word or ‘numeral + measure word’ phrase:
nGi zhang
4 Interrogative pronouns
zhèi zhang
Which one? (e.g. newspaper, sheet of paper, table, etc.) This one.
nh yào nF san gè wi yào nà san gè
Which three do you want? I want those three.
nGi xib piányi difnr zhèi xib piányi difnr
Which ones are cheaper? These ones are cheaper.
nh mfi nF lifng bgn she wi mfi nà lifng bgn she
Which two books are you going to buy? I’m buying those two books.
nGi bf sfn shì nh de zhèi bf sfn shì wi de
Which umbrella is yours?
G nfr ‘where’ and ally ask about location.
This umbrella is mine.
shénme dìfang ‘what place’ natur-
(i) They may occur at the object position, particularly after go (to)’ and zài ‘to be at/in/on’:
qù ‘to
/ nh qù nFr/shénme dìfang Where are you going?. Where is there something to eat?). Here are some more examples: nFr yiu hfo diànyhng kàn Where can we go to see a good film? (lit. Where is there a good film (to) see?) nèi jiA diànyHngyuàn yiu hfo diànyhng kàn There is a good film on show in that cinema. (lit. At that cinema there is a good film (to) see.) nFr yiu bcngjilíng mài Where can (we) buy ice-cream? (lit. Where is there ice-cream to be sold/for sale?) mFlù duìmiàn yiu | nàr yiu yc liàng bcngjilíng chb Across the road. There’s an ice-cream van there. (lit. Across the road there is (some). There there is an ice-cream van.) nFr yiu chb ze Where are there cars for/to hire? duìbuqh | zhèr méi yiu chb ze I’m sorry, there aren’t any cars for hire here. (lit. Here there are not cars (to) hire.) (iii)
nfr and shénme dìfang are also commonly used after a coverb (see Unit 24) such as zài ‘in, at, on’, dào ‘to’, etc., to create a coverbal phrase. These coverbal phrases come before the verb: nh háizi zài nFr xuéxí Where is/are your child(ren) studying? wi háizi zài dàxué xuéxí My child(ren) is/are studying at the university.
32
nh bàba zài shénme dìfang gdngzuò Where does your father work?
wi bàba zài yC jiA yínháng gdngzuò My father works at a bank. / ta dào nFr/shénme dìfang qù Where is he going? ta dào bàngDngshì qù He’s going to his office.
4 Interrogative pronouns
Note:
jia, as you may have noticed, is the measure word for diànyhngyuàn ‘cinema’, yínháng ‘bank’, shangdiàn ‘shop’, etc. The noun jia also means ‘home; house; family’.
Exercise 4.1 Formulate questions based on the sentences below focusing on the words in bold italics. Use interrogative pronouns and switch the first-person and second-person pronouns as necessary. wi qù shangdiàn mfi ddngxi I’m going to the shops to buy something. (a) wI qù shangdiàn mfi ddngxi shéi qù shangdiàn mfi ddngxi (b) wi qù shAngdiàn mfi ddngxi nh qù nFr mfi ddngxi (c) wi qù shangdiàn mfi dDngxi nh qù shangdiàn mfi shénme (d) wi qù shangdiàn mFi dDngxi nh qù shangdiàn zuò shénme 1
mama qù shìchfng mfi jcdàn Mother is going to the market to buy eggs. (a) mAma qù shìchfng mfi jcdàn (b) mama qù shìchFng mfi jcdàn (c) mama qù shìchfng mfi jCdàn (d) mama qù shìchfng mFi jCdàn
2
bàba zài bàngdngshì xig tucjiànxìn Father is writing a reference/a letter of recommendation in the office.
33
(a) (b) (c) (d)
4 Interrogative pronouns
bàba zài bàngDngshì xig tucjiànxìn bàba zài bàngdngshì xiG tuCjiànxìn bàba zài bàngdngshì xig tuCjiànxìn bàba zài bàngdngshì xig tucjiànxìn
3
jigjie zài chúfáng li wèi mao (My) elder sister is feeding the cat in the kitchen. (a) jigjie zài chúfáng li wèi mao (b) jigjie zài chúfáng li wèi mAo (c) jiGjie zài chúfáng li wèi mao
4
gbge zài wàimian xie chb (My) elder brother is repairing the car outside. (a) gbge zài wàimian xiE chB (b) gbge zài wàimian xie chB (c) gbge zài wàimian xie chb (d) gBge zài wàimian xie chb
5
dìdi qù yóuyingchí xué yóuying (My) younger brother is going to the swimming-pool to learn to swim. (a) dìdi qù yóuyingchí xué yóuyIng (b) dìdi qù yóuyingchí xué yóuying (c) dìdi qù yóuyIngchí xué yóuying
6
dìdi xifng qhng jigjie bang ta de máng (My) younger brother would like to ask his elder sister to lend him a hand. (i.e. give him some help) (a) dìdi xifng qhng jiGjie bang ta de máng (b) dìdi xifng qhng jigjie bAng tA de máng (c) dìdi xifng qhng jigjie bangmáng
7
línje de háizi zài jib shang qí zìxíngchb (Our) neighbour’s child is riding a bicycle in the street. (a) línjE de háizi zài jib shang qí zìxíngchb (b) línjE de háizi zài jib shang qí zìxíngchb (c) línje de háizi zài jib shang qí zìxíngchB (d) línje de háizi zài jib shang qí zìxíngchB (e) línje de háizi zài jiB shang qí zìxíngchb
8
34
mèimei míngnián xifng gbn yéye qù zhdngguó lsxíng (My) younger sister wants to go travelling in China with Grandpa next year. (a) mèimei míngnián xifng gbn yéye qù zhdngguó lsxíng (b) mèimei míngnián xifng gBn yéye qù zhDngguó lSxíng (c) mèimei míngnián xifng gbn yéye qù zhdngguó lsxíng
(d) mèimei míngnián xifng gbn yéye qù zhDngguó lsxíng (e) mèimei míngnián xifng gbn yéye qù zhdngguó lSxíng
4 Interrogative pronouns
Exercise 4.2 Translate the following sentences into Chinese using the pattern: ‘
+
+ noun + verb’
Where can we buy pears? (Where are there pears to be sold/for sale?) nfr yiu lí mài 1 2 3 4 5 6 7 8 9 10
Where Where Where Where Where Where Where Where Where Where
can we hire bicycles? can we have coffee? can we buy flowers? is there any beer to drink? can I find something to eat? can I see a film? can you buy a newspaper? ( bàozhh ‘newspaper’) can you borrow books? ( jiè ‘borrow’) can you buy fresh vegetables? ( xcnxian ‘fresh’) can we hire a good car?
Exercise 4.3 Translate these sentences into Chinese: 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Who would like some tea? Who would like some cake? Whose is this mug? What would you like to eat? Which picture do you prefer? Who can speak Chinese? ( huì ‘can; be skilful with’) Which child is yours? Whose teacher is Mr Zhang? Which oranges are you going to buy? What kind of vegetables do you like? Who can repair cars? Who can help me? ( néng ‘can; be able to’) Who do you want to see? Which two books have you brought with you?
35
4 Interrogative pronouns
15 16 17 18 19 20
What place did you go to? Which countries are you going to? Where is my purse/wallet? Where do you go for coffee? Who are you going to China with? Where did you get acquainted with her?
Note: huì ‘can’ indicates permanent skills whereas néng ‘can’ indicates whether someone is able or in a position to do something on a particular occasion, e.g. wi huì yóuying | dànshì jiantian bìng le | bù néng yóu ‘I know how to swim, but as I am unwell today, I can’t.’
Pattern and vocabulary drill 4.1 Provide the answers to the following questions using the pattern of the example: nh xifng hb difnr shénme What would you like to drink? Answer (a) some tea (b) some coffee (a) wi xifng hb difnr chá (b) wi xifng hb difnr kafbi
36
1
nh xifng chc difnr shénme What would you like to eat? Answer (a) some cake (b) some ice cream
2
nh xifng mfi difnr shénme What would you like to buy? Answer (a) Chinese cabbage ( báicài) (b) fish (
yú)
3
nh zhèi gè lhbàitian xifng zuò shénme What would you like to do this coming Sunday? Answer (a) go to see a film (b) go swimming
4
nh zhfo shénme What are you looking for? Answer (a) my key (b) my umbrella
5
nh zhfo shéi Who are you looking for? Answer (a) Mr Li (b) my father
6
nh dào/shàng nfr qù ( Where are you off to? Answer (a) the bank (b) the university
shàng ‘go to’)
4 Interrogative pronouns
Pattern and vocabulary drill 4.2 First translate the following sentences into English and then replace the particle ma by ba so as to turn a general question into a surmise question as if you were saying, instead of ‘Do you like drinking coffee?’, ‘You like drinking coffee, don’t you?’ 1 2 3 4 5 6 7 8 9 10 11 12
nh xhhuan yfng mao ma ( yfng ‘to keep; to rear’) nh xhhuan yfng giu ma nh xhhuan yfng jcnyú ma nh xhhuan qí zìxíngchb ma nh xhhuan qí mf ma nh xhhuan zhù zài lúnden ma nh xhhuan zhù zài balí ma ( balí ‘Paris’) nh xhhuan mfi piányi de ddngxi ma nh xhhuan zhèi xib xianhua ma nh xhhuan nh de línje ma nh xhhuan nh de gdngzuò ma nh xhhuan zhèi jiàn máoyc ma
37
UNIT FIVE Numbers
A Numbers in Chinese follow a system based on tens, hundreds, etc.: yc èr san sì wj liù qc ba jij shí líng
one two three four five six seven eight nine ten zero
shí yc shí èr shí san shí qc shí jij èr shí san shí yc wj shí sì ba shí liù jij shí jij
eleven twelve thirteen seventeen nineteen twenty thirty-one fifty-four eighty-six ninety-nine
Note 1: 7 yao is sometimes used instead of yc in speech (e.g. on the telephone) to avoid the confusion between yc ‘one’ and qc ‘seven’.
Note 2: The numeral 2 before a measure word is èr: lifng gè lí lifng gè xcngqc/lhbài
/
lifng and not
two pears two weeks
B While in English you count up to a thousand and then repeat up to a million, Chinese counts up to ten thousand ( wàn) and then repeats up to a hundred million ( yì). The higher numbers are:
38
yc yc yc yc
bfi qian wàn yì
100 1,000 10,000 100,000,000
one hundred one thousand ten thousand one hundred million
Figures are expressed from higher to lower units:
5 Numbers
yc bfi èr shí wj 125 one hundred and twenty-five yc qian èr bfi san shí wj 1,235 one thousand two hundred and thirty-five yc wàn èr qian san bfi sì shí wj 12,345 twelve thousand three hundred and forty-five shí èr wàn san qian sì bfi wj shí liù 123,456 one hundred and twenty-three thousand four hundred and fifty-six yc bfi èr shí san wàn sì qian wj bfi liù shí qc 1,234,567 one million two hundred and thirty-four thousand five hundred and sixty-seven yc qian èr bfi san shí sì wàn wj qian liù bfi qc shí ba 12,345,678 twelve million three hundred and forty-five thousand six hundred and seventy-eight yc yì èr qian san bfi sì shí wj wàn liù qian qc bfi ba shí jij 123,456,789 one hundred and twenty-three million four hundred and fifty-six thousand seven hundred and eighty-nine It is useful to remember that a million in Chinese is (= 100 × 10,000).
yc bfi wàn
Note: líng ‘zero’ is used as a filler for any missing unit or units within a figure: yc bfi líng wj 105 yc qian líng sì 1004 yc qian yc bfi 1102 líng èr
one one one and
hundred and five thousand and four thousand one hundred two
C A fraction is expressed by the pattern: ‘denominator fbn zhc numerator’. ( fbn means ‘part; component’ and zhc means ‘of’):
39
5 Numbers
san fbn zhc yc sì fbn zhc yc sì fbn zhc san ba fbn zhc qc
1/3 1/4 3/4 7/8
one third one quarter three quarters seven eighths
D bàn ‘half’ followed by a noun functions like a numeral and requires a measure word: bàn bbi jij
( )
bàn bàn / bàn bàn bàn
gè xcgua nián (gè) xifoshí / gè zhdngtóu gè yuè
half a glass of wine (or any alcoholic drink) half a watermelon six months (lit. half a year) half an hour two weeks (lit. half a month)
bàn is used after a ‘number + measure word’ phrase to mean ‘and a half’: yc bbi bàn jij lifng gè bàn xcgua san nián bàn wj gè bàn xifoshí yc gè bàn yuè E
a glass and a half of wine (or any alcoholic drink) two and a half watermelons three and a half years five and a half hours a month and a half
Percentages take the form of fractions of 100: bfi fbn zhc sì shí 40% bfi fbn zhc yc bfi líng qc 107%
F The decimal point is expressed as
difn:
san difn liù jij 3.69 san shí san difn san san 33.33 liù difn yc qc 6.17 Note: When líng ‘nought; zero’ occurs after the decimal point, it is not a ‘filler’ but functions as a separate unit and is therefore repeated as necessary. See for instance the following:
40
1,002.002
yc qian líng èr difn líng líng èr one thousand and two point zero zero two
G Ordinal numbers in Chinese are formed by placing the numeral: dì yc dì shí
dì before
5 Numbers
(the) first (the) tenth
Ordinal numbers, like cardinals, require a measure with a noun: dì yc gè xuésheng dì shí cì huìyì dì san bgn she
the first student the tenth meeting the third book
They also regularly occur with frequency, time and unit measures: dì yc cì dì èr zhdu dì wj kè Note 1: The numeral 2 in an ordinal is before a measure word:
the first time the second week Lesson Five èr and not
lifng even
dì èr chfng zúqiú bhsài the second soccer match One cannot say: *
dì lifng chfng the second match
Note 2: In some cases Chinese does not use ordinal numbers where the equivalent phrase in English would: yc niánjí the first year/the first form (in school, etc.) èr lóu the first floor (‘ground floor’ in English is counted as yc lóu or dì xià and ‘first floor’ therefore becomes èr lóu.) H When referring to an item or items adjacent or next to the one in question, one does not usually make use of dì. One uses shàng ‘previous, last’ or xià ‘next’ followed by a numeral, a measure and the noun. The noun is often omitted, particularly when its meaning can be readily derived from the context or from the measure word itself, e.g.:
41
5 Numbers
( ) ( )
shàng lifng chfng (bhsài) the last two matches xià san kè (she) the next three lessons
Where the numeral is the measure and noun: ( ) ( ) ( )
yc ‘one’, it is regularly omitted, leaving just
shàng (yc) gè shìjì xià (yc) gè yuè shàng (yc) gè xcngqc/ lhbài shàng (yc) gè jiémù
/
( )
the previous century next month last week the previous programme
However, when the noun is understood and omitted, be used: xià yc gè shàng yc jí
yc ‘one’ must
the next one (e.g. ‘the next person in the queue’) the previous volume, etc. in a series
Therefore notice the following: ( ) ( ) xià (yc) gè zhàn (xià chb) (I’m getting off at) the next stop, please As zhàn itself may be used as a measure word, one may often hear this expressed as ( ) xià yc zhàn (xià chb/xia). I Approximate numbers in Chinese can be expressed by placing zuiyòu or shàngxià ‘approximately’ after the ‘numeral + measure word’ phrase or dàyub ‘about’ or chàbudud ‘almost’ before it:
/
42
san gdngjcn zuiyòu wj mh shàngxià dàyub lifng difn zhdng dàyub lifng gè xifoshí/zhdngtóu chàbudud san shí ycnglh
about three kilograms about five metres about two o’clock about two hours almost thirty miles
Note: Observe the difference between lifng difn zhdng ‘two o’clock’ and / lifng gè zhdngtóu/xifoshí ‘two hours’ (see Unit 8).
Approximation with the number 10 and its multiples, up to and including 100, may also be expressed using lái or dud: / / ( )
/
5 Numbers
shí lái/dud nián around ten years sì shí lái/dud suì about forty years old (yc) bfi lái/dud gè a little over a hundred
Note: jh may also be used to indicate approximation with round numbers above 10 and below 100, e.g.: èr shí jh nián qc shí jh suì
twenty odd years over seventy years of age
yc bfi jh rén
over a hundred people
But not: *
However, with qian ‘thousand’ and dud is used for a similar purpose: lifng qian dud nián san wàn dud rén Note: Observe the difference between and suì ‘year (of age)’.
wàn ‘ten thousand’, only
over two thousand years over thirty thousand people nián ‘year’ (period of time)
Any two consecutive numbers from one to nine may also be used to express approximation: yc | lifng nián lifng | san tian shí qc | ba gè rén
( )
èr | san shí gè lfoshc yc | èr bfi gè xuésheng lifng | san qian (gè) rén
one or two years two or three days seventeen or eighteen people twenty to thirty teachers a hundred to two hundred students two to three thousand people
43
5 Numbers
Note: In relation to ‘two’, to say simply ‘one or two’ or ‘two or three’, yc | lifng or lifng | san are generally used. For ‘eleven or twelve’ and ‘twelve to thirteen’ you must say shí yc | èr or shí èr | san. ‘Ten or twenty’, ‘twenty or thirty’ must also be yc | èr shí or èr | san shí. For higher numbers in these sequences lifng is usually preferred (e.g. lifng | san bfi ‘two or three hundred’, yc | lifng qian ‘one or two thousand’) but èr is also possible. J To ask ‘how many’, dudshao ‘how many; how much’ (lit. many few) or jh ‘how many’ with a measure are used. jh implies that the number involved is below ten whereas dudshao is unlimited. jh always requires a measure, whereas dudshao normally does not:
nh yiu jh gè háizi How many children do you have? ( ) nh ns’ér jcnnián jh suì (le) How old is your daughter (this year)? nh hb le jh bbi píjij How many glasses of beer did you drink? nh shbn shang dài le dudshao qián How much money do you have on you? zhdngguó yiu dudshao rén How many people are there in China? nh qù guo dudshao guójia How many countries have you been to? Note 1:
jh may be used with
shí,
bfi,
qian, etc.:
zhdngguó yiu jh qian nián de lìshh How many thousand years of history does China have? nèi tian wfnhuì | nh qhng le jh shí gè tóngxué How many (lit. tens of) classmates did you invite to the party that evening?
44
Note 2:
guo is an aspect marker indicating experience (see Unit 15).
5 Numbers
Exercise 5.1 Express the following Chinese numbers in figures: 1 2 3 4 5 6 7 8 9 10 11 12
ba shí jij shí liù yc wàn liù yì qc bfi wàn yc wàn san qian wj bfi èr shí liù shí ba wàn liù qian jij bfi san shí sì san qian liù bfi wj shí èr qc yì ba qian wàn líng sì bfi liù shí jij liù wàn sì qian wj bfi líng sì sì qian líng sì difn líng líng wj
Exercise 5.2 Translate the figures below into Chinese: 1 2 3 4 5 6
80,205 6,329,814 600,000,000 1,080 7/36 1/4
7 8 9 10 11 12
3% 97% 4.1316 586.23 7,005 601.007
Exercise 5.3 Translate the following phrases into Chinese: 1 2 3 4 5 6 7
half a day two weeks three and a half years six months the first floor half an orange half a bottle of wine
8 9 10 11 12 13 14
five and a half pears the fifth week the fourth child the twelfth match the third year (at school) the second day seven and a half hours 45
5 Numbers
Exercise 5.4 Fill in the blanks below with either translation of the English: 1 2 3 4 5
shí
èr or
lifng to complete the
cì wàn rén
twice twenty thousand people half twelve metres twenty-five goldfish
fbn zhc yc mh shí wj tiáo
jcnyú tiáo qúnzi dì kè | san dá jcdàn shí | san bf yáshua yc | bf yjsfn
6 7 8 9 10
Exercise 5.5 Translate the following phrases into Chinese: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 46
one or two weeks two hundred years about sixty years old thirty to forty bicycles ten days and more some two hundred shops ten per cent twenty or so fifteen metres or so a month or so over ten thousand students two or three children about fifty friends and neighbours about seventy miles over eight kilograms ten cities or more
two skirts Lesson Two two or three dozen eggs twelve to thirteen toothbrushes one or two umbrellas
5 Numbers
Exercise 5. 5 Li Ming has invited ( qhng le) thirty to forty friends and fellow students. 6 My boyfriend ( nán péngyou) has brought ( dài lái le) a bunch of flowers and a few bottles of beer. 7 I have written ( xig le) around five references. ( fbng is the measure word for letters, etc.) 8 My girlfriend ( ns péngyou) has been to ten countries or more. 9 I bumped into ( pèngjiàn le) over twenty fellow students. 10 My son saw ( kàn le) about a dozen films this year. ( jcnnián ‘this year’) 11 How much is that sweater? 12 How many younger sisters does he have? 13 How many people are there in Beijing? 14 How many Chinese people does your father know? 15 How many kilos of Chinese cabbage do you want to buy?
Pattern and vocabulary drill 5.1 Try to work out the English translation of the following. You can use the vocabulary at the end of the book if it helps. 1 2 3 4 5
xià yc wèi | qhng jìn lái xià (yc) ban chb jh difn kai shàng bàn chfng hgn jcngcai wimen xià xcngqc sì ziu ta shàng gè xuénián hgn njlì ( working; industrious’) 6 nh xià gè zhàn xià chb ma 7 shàng yc qc mài wán le 8 xià (yc) cì zàijiàn ( ) ( )
njlì ‘hard-
47
5 Numbers
Pattern and vocabulary drill 5.2 Translate the following questions into Chinese, using the alternative méiyiu format and the experience aspect marker guo: Have you ever ridden a bike? nh qí guo zìxíngchb méiyiu 1 Have you met these few engineers before? ( jiàn guo ‘to have met/seen’) 2 Have you ever been to Britain? ( qù guo ‘to have been’) 3 Have you ever kept a dog? ( yfng guo ‘to have had the experience of rearing’) 4 Have you ever ridden a camel? ( luòtuo ‘camel’) 5 Have you used chopsticks before? ( yòng guo ‘to use’) 6 Have you ever had any Chinese friends? ( jiao guo ‘to have made (friends with)’) 7 Have you ever tried English beer? 8 Have you had Chinese tea before? 9 Have you seen a Chinese film before? 10 Have you ever driven a car? ( kai guo ‘to have driven’) 11 Have you ever hired a car? ( ze guo ‘to have hired’) 12 Have you ever been to your friend’s place? 13 Have you met her parents before? 14 Have you ever helped your friends? ( bang guo ‘to have helped’) 15 Have you ever learned how to swim? ( xué guo ‘to have learned’)
48
UNIT SIX Measure words
Measure words are a particular feature of Chinese syntax, but they do not present an insuperable problem for the learner. With a certain amount of practice, they can soon be generally mastered. This unit compartmentalizes some of the most common and important measure words to provide a structure for understanding their usage and an easy reference. A A measure word is always necessary when a noun is modified by a numeral or a demonstrative: yc bgn cídifn yc zhc máobh lifng zhc nifo san tiáo máojcn zhèi bbi niúnfi nèi píng píjij ngi gè rén
a/one dictionary a/one writing brush two birds three towels this glass of milk that bottle of beer which person
One would not normally say: * * * *
yc bh lifng she zhè nifo nf chb
(lit. (lit. (lit. (lit.
a/one pen) two books) this bird) which car)
Some nouns may be associated with more than one measure word: / / / / / / /
yc zuò/sui/zhuàng/ dòng fángzi zhèi zhc/tiáo/sdu chuán san liàng/bù chb nf fú/zhang huàr
a/one house this boat/ship three cars which picture or painting
49
6 Measure words
B gè, as we have seen (in Unit 1), is by far the most common of the measures and can be used with virtually any noun: yc gè kànff yc gè xifngff yc gè diànyhng yc gè wj lifng gè kèren san gè guójia zhèi gè jchuì ngi gè qcngnián
a view, opinion an idea a film/movie a dance two visitors/guests three countries this opportunity which young man
C Most of the other measures can be placed in general categories, depending on their relationship to the nouns or sets of nouns they accompany: (i) Associated with particular nouns or sets of nouns clothing yc dhng màozi lifng jiàn chènshan yc tiáo qúnzi shops, schools and buildings san | sì jia shangdiàn jh jian xuéxiào yc zuò dà lóu
a/one hat two shirts a skirt three or four shops a few schools a large building
vehicles yc yc yc yc
jià fbijc liàng bashì liàng xifoba liàng dìshì
publications, writing and performance yc bgn she yc pian wénzhang yc fbng xìn yc che xì yc | lifng shiu gb jh jù huà
a/one plane a bus a minibus a taxi a book a composition a letter a play one or two songs a few words
plants
50
yc dui huar a/one flower nèi kb shù that tree zhèi kb cfo this tuft/clump of grass yc kb méiguì hua a rosebush (cf. yc dui méiguì hua a rose)
weather yc yc yc yc yc Note:
zhèn fbng zhèn léi cháng yj cháng dà xug dui yún
a a a a a
gust of wind peal of thunder shower of rain heavy fall of snow cloud
6 Measure words
dui is also the measure word for ‘flowers’.
games yc chfng qiú yc jú qí
a football/basketball/tennis match a game of chess
Note 1: jh means ‘a few’ when used in a statement but ‘how many’ in a question (see Unit 5): wi mfi le jh jiàn chènshan I bought a few shirts. nh mfi le jh jiàn chènshan How many shirts have you bought (or did you buy)?
Note 2: cháng for weather and chfng for games are homographs, but note their different tones. (ii) Portion of whole san dc shuh wj piàn miànbao zhèi kuài ròu liù kuài dàngao
three drops of water five slices of bread this piece of meat six pieces of cake
Note: Observe the difference between yc gè dàngao ‘a (whole) cake’ and yc kuài dàngao ‘a piece of cake’ (i.e. a portion of a whole cake). (iii) Container lifng bbi chá san wfn fàn sì píng jij yc guàn niúnfi yc ting shuh yc zhudzi cài
two cups of tea three bowls of (cooked) rice four bottles of wine a bottle of milk a pail/bucket of water a table laden with food
51
6 Measure words
Note: Most containers occur as nouns themselves and then take on other measure words: lifng gè bbizi san zhc wfn sì gè píngzi
two cups/glasses/mugs three bowls four bottles
But yc gè guàntou does not mean ‘a can/tin’ in general, but specifically ‘a can/tin of food’. Portion and container measure words are often further qualified by dà ‘big’ or xifo ‘small’ to indicate their relative size: yc dà kuài ròu a large piece of meat yc xifo piàn miànbao a small slice of bread yc dà wfn fàn a large bowl of (cooked) rice/a bowl of (cooked) rice filled to the top yc xifo wfn fàn a small bowl of (cooked) rice/a bowl of (cooked) rice partially filled lifng xifo guàn wjcanròu two small cans of luncheon meat, etc. (iv) Shape (a)
(b)
(c) 52
tiáo long and narrow; a strip yc tiáo miànbao yc tiáo lù yc tiáo shéngzi yc tiáo yú yc tiáo hé zhèi tiáo qúnzi nèi tiáo bèizi
a loaf of bread a road (street) a rope/piece of string a fish a river this skirt that quilt
gbn stick-like yc gbn huichái yc gbn cfo yc gbn xiàn
a match a blade of grass a piece of thread
( ) zhc like a branch or a twig yc zhc qianbh lifng zhc yan
a pencil two cigarettes
yc zhc bùduì yc zhc qiang (d)
zhang a flat surface yc zhang zhh ngi zhang zhudzi yc zhang bàozhh yc zhang chuáng yc zhang dìtú
(e)
an army a rifle/pistol
6 Measure words
a piece of paper which table a newspaper a bed a map
lì granular yc lì sha yc lì mh
(f)
a grain of sand a grain of rice
kb small and round (not to be confused with its homophone kb ‘measure word for plants’) yc kb zhezi a pearl yc kb huángdòu a soya bean
(v) Relating to noun groups (a)
bf is used with nouns which indicate something held by the hand: yc bf dao a knife zhèi bf yhzi this chair ( ) yc bf (yj)sfn an umbrella yc bf yáshua a toothbrush
(b)
zuò is used with nouns which indicate something large and imposing: yc zuò shan a hill/mountain yc zuò qiáo a bridge nèi zuò fángzi that house/building
(c) •
zhc is used with the following noun groups: animals, birds and insects yc zhc nifo a bird yc zhc mao a cat yc zhc lfoshj a mouse yc zhc yáng a sheep yc zhc cangying a fly Note: The following animals take individual measure words: yc tóu niú yc ph mf zhèi tiáo giu
a cow a horse this dog
53
•
6 Measure words
•
utensils yc zhc wfn yc zhc gud
a bowl a wok
yc zhc shiutào nèi zhc xié yc zhc wàzi yc zhc yfnjing yc zhc grduo
a glove that shoe a sock an eye an ear
one of a pair
(vi) Referring to weight, volume, length, etc. lifng gdngjcn mflíngshj two kilos of potatoes yc bàng niúròu a pound of beef ba shbng qìyóu eight litres of petrol wj ycnglh lù five miles (distance) D
Objects in pairs. In Chinese ‘a pair of’ is usually yc duì: yc yc yc yc yc yc
shuang xiézi shuang kuàizi shuang shiu shuang shiutào duì wàzi duì grhuán
a a a a a a
pair pair pair pair pair pair
yc shuang or
of of of of of of
shoes chopsticks hands gloves socks earrings
Note 1: yc shuang and yc duì are generally interchangeable, although yc duì is more often used for people or animals forming partnerships: yc duì fefù yc duì gbzi yc duì yuanyang
husband and wife a pair of pigeons a pair of mandarin ducks/an affectionate couple
Note 2: In English one may use ‘a pair of’ with objects which are, in fact, a single entity. In Chinese these objects take specific measure words:
54
yc bf jifndao yc tiáo kùzi ngi fù yfnjìng
a pair of scissors a pair of trousers which pair of glasses?
E Objects in clusters or held together in one way or another adopt different measure words: yc yc yc yc yc yc
chuàn xiangjiao chuàn pútao shù hua bf mh cuò yán bh qián
a a a a a a
6 Measure words
bunch of bananas bunch of grapes bouquet (of flowers) handful of rice pinch of salt sum of money
F Some nouns, particularly those referring to time, can be measure words in themselves and do not require a measure word: yc tian lifng nián
a/one day two years
In some cases the measure word is optional: yc gè xcngqc or san gè xifoshí or
yc xcngqc san xifoshí
a/one week three hours
Note: lhbài, an alternative for ‘week’ and zhdngtóu, an alternative for ‘hour’, and yuè ‘month’ always take the measure word ge: lifng gè lhbài not * san gè zhdngtóu not * liù gè yuè not *
However,
yuè is used without ycyuè èryuè liùyuè shíèryuè
lifng lhbài two weeks san zhdngtóu three hours liùyuè six months
gè for the calendar months, e.g. January February June December
G A few Chinese measure words have a variety of translations in English according to context and to the noun they are linked with: yc bbi chá yc bbi kafbi yc bbi shuh
a cup of tea a mug of coffee a glass of water
yc qún láng yc qún yáng yc qún rén
a pack of wolves a flock of sheep a crowd of people
55
6 Measure words
Conversely some measure words in English have a range of translations in Chinese: yc yc yc yc yc yc
tiáo xcnwén kuài féizào zhang zhh gè xìnxc zhc yuèqj zhc fgnbh
a a a a a a
piece piece piece piece piece piece
of of of of of of
news soap paper information music chalk
H As we have seen from the examples in the unit, demonstratives zhè and nà and interrogative adjective nf are used with measure words in the same way as numerals: zhèi bbi jij nèi píng niúnfi ngi shuang xié?
this glass of wine (or any alcoholic drink) that bottle of milk which pair of shoes?
When zhè or nà or nf occurs together with a numeral, the former always precedes the latter: zhè lifng bbi jij nà san píng niúnfi nf sì shuang xié?
these two glasses of wine, etc. those three bottles of milk which four pairs of shoes?
zhè, nà and nf are also used regularly with ( ) ‘some’ to identify an indefinite plural number or amount: ( ) ( ) ( )
zhèi (yc)xib she nèi (yc)xib wàzi ngi (yc)xib qián?
(yc)xib
these books those socks/stockings which (amount of) money?
Note: (yc)xib ‘some’ is a set expression. with other numerals.
xib cannot be used
One cannot say: *
56
lifng xib she
I There are a number of collective nouns which consist of a measure word suffixed to a noun. These collective nouns are only used in more formal contexts:
chbliàng vehicles chuánzhc shipping shebgn books zhhzhang paper
xìnjiàn huadui mfph rénqún
correspondence flowers horses crowd (of people)
6 Measure words
These collective nouns cannot be modified by a ‘numeral + measure word’ phrase: * *
lifng dui huadui san zhc chuánzhc
(lit. two flowers) (lit. three boats)
J In more descriptive writing, plurality may also be formed by using the numeral yc ‘one’ followed by a reduplicated measure word with or without the attributive marker de: ( ) ( )
yc duidui (de) huar yc zhènzhèn (de) fbng
many a flower gusts of wind/gust after gust of wind
In poetic writing or proverbial sayings, an alternative version can be ‘reduplicated measure + noun’: duidui huar xiàng yáng kai Many a flower opens towards the sun. tiáotiáo dà lù tdng luómf All roads lead to Rome. rénrén wèi wi | wi wèi rénrén All for one and one for all.
Exercise 6.1 Match each noun below with the correct measure word and translate the resulting phrase into English: 1 2 3 4 5 6 7 8
yc ph lifng jià san gè sì | wj bf jh zhang liù jia qc sui ba zuò
shangdiàn dàngao yhzi shan mf guójia zhudzi she
57
6 Measure words
9 10
jij bgn shí kuài
fbijc xuéxiào
Exercise 6.2 See if you can find a measure word out of the eight below to replace the measure words in the following phrases: bù
fù
duì
1 2 3 4 5 6 7 8
yc yc yc yc yc yc yc yc
zuò
sui
fèn bàozhh tiáo bèizi jian xuéxiào duì grhuán liàng qìchb bù diànyhng zhuàng fángzi shuang kuàizi
gè a a a a a a a a
zhang
chuáng
newspaper quilt school pair of earrings car film house pair of chopsticks
Exercise 6.3 Translate the phrases below into Chinese: 1 2 3 4 5 6 7 8 9 10
a day a bowl of (cooked) rice a year this pair of spectacles a pair of shoes a week an earring a sock a piece of bread that pair of scissors
11 12 13 14 15 16 17 18 19 20
a piece of soap a pair of trousers a month two pounds of apples three miles seven litres of petrol which writing brush? a boat two songs a map
Exercise 6.4 Translate the following phrases into Chinese (note that some nouns may share the same measure word):
58
1 a flock of sheep 2 a glass of beer
3 a crowd of people 4 an umbrella
5 6 7 8 9 10 11 12
a knife that bird those two bunches of flowers a piece of music this newspaper which three pencils? an opportunity a drop of water
13 14 15 16 17 18 19 20
a cup of tea which flower? a (piece of) string a bed a pair of trousers a pair of scissors this dog these three cigarettes
6 Measure words
Exercise 6.5 Complete the Chinese translations of the English sentences below, choosing appropriate measures from the following list (note that some measure words may be used more than once): tiáo bbi jian
bgn bf gè
liàng dhng
wfn zhc
xib jia
zhang zhc
1 There are only four tables and five chairs in this classroom.
jiàoshì li zhh yiu yhzi 2 Our neighbour has two dogs and three cats.
zhudzi hé
wimen línje yiu giu hé 3 We’ve got four cars in the family. ( ) wi jia yiu 4 My younger brother bought a new hat. dìdi mfi le màozi 5 I had four cups of coffee today. wi jcntian hb le kafbi 6 That person made a few suggestions. rén tí le 7 My uncle brought some fruit.
mao (qì)chb xcn
jiànyì
sheshu dài lái le shuhgui 8 Li Ming walked into a restaurant and ordered a bowl of fried noodles.
59
6 Measure words
lh míng ziu jìn fàngufn | jiào le chfomiàn 9 My uncle wants to go to France by car. He’s borrowed a map of France. wi jiùjiu xifng kai chb qù ffguó | ta jiè le ffguó dìtú 10 My younger sister likes birds. She keeps those two parrots. mèimei xhhuan nifo | ta yfng le
ycngwj
Note: There is a difference in Chinese between sheshu ‘uncle (on father’s side)’ and jiùjiu ‘uncle (on mother’s side)’.
Exercise 6.6 Translate into Chinese: 1 2 3 4 5 6 7 8
I have two children. How many do you have? You had three glasses of beer. I had only one. I like this dog. I don’t like that one. My mother has a dozen pairs of shoes. My sister has over twenty. We have one car. You have two, don’t you? She had one bowl of rice. He had three or four. Whose is this one? Which one is hers? Note: In sentence 4 ‘a dozen pairs’ which brings together two measures is unacceptable in Chinese. You therefore have to say ‘twelve pairs’.
Pattern and vocabulary drill 6.1 Complete the following Chinese sentences with the help of the English translations: 1
60
_____ _____ _____ _____ shejià shang yiu . . . There are more than ten books on the bookshelf. 2 _____ _____ _____ _____ _____ huapíng li yiu . . . There is a bouquet of flowers in the vase.
3
4
5
6
7
8 9 10
11
12
13 14 15 16 17 18 19
_____ _____ _____ _____ _____ _____ _____ zhudzi shang yiu . . . hé . . . There are two bowls and two pairs of chopsticks on the table. _____ _____ _____ _____ _____ _____ _____ _____ ycguì li yiu . . . hé . . . There are two shirts, two skirts and two pairs of trousers in the wardrobe. _____ _____ _____ _____ _____ _____ wi fùmj jia yiu . . . hé . . . There are two cats and a dog in my parents’ home. _____ _____ _____ _____ _____ _____ _____ bcngxiang li yiu . . . hé . . . There is a piece of meat and some vegetables in the fridge. _____ _____ _____ _____ (zuòwèi ‘seat’) diànyhng yuàn yiu . . . zuòwèi There are over three hundred seats in the cinema. _____ _____ _____ _____ shangdià li yiu . . . There is a large crowd of people in the shop. _____ _____ _____ _____ ta yíngháng li yiu . . . He has a small sum of money in the bank. _____ _____ _____ _____ _____ _____ ______ (mài ‘to sell’) shìchfng shang yiu . . . hé . . . mài There are apples, oranges, pears and bananas on sale at the marketplace. _____ _____ _____ _____ _____ _____ _____ _____ chúfáng li yiu . . . hé . . . There is a big table and six chairs in the kitchen. _____ _____ (xíngrén ‘pedestrians’) jib shang yiu láilái wfngwfng de . . . hé xíngrén In the street there are cars and pedestrians going to and fro. _____ _____ _____ _____ bàngdngshì li yiu . . . There are four bookshelves in the office. _____ ta shbn shang méi yiu . . . She has no money on her. _____ _____ _____ _____ chí li yiu . . . There are eleven fish in the pond. _____ _____ _____ wfn li yiu . . . There is some (cooked) rice in the bowl. _____ _____ _____ _____ chuáng shang yiu . . . There are two quilts on the bed. _____ _____ _____ _____ wfnguì li yiu . . . There are over ten bowls in the cupboard. _____ _____ _____ shù shang yiu . . . There are a few birds in the tree.
6 Measure words
61
6 Measure words
20
_____ _____ _____ shan shang yiu . . . There is a pack of wolves on the mountain. 21 _____ _____ _____ _____ (chéngkè ‘passenger’) chb shang yiu . . . There are over twenty passengers on the train/coach/bus. 22 _____ _____ _____ _____ _____ _____ _____ _____ chuán shang yiu . . . There are three hundred and fifty-six passengers on board the ship.
Pattern and vocabulary drill 6.2 Pluralize the following phrases, using a more descriptive tone: yc fú huàr a picture/painting ( ) yc fúfú (de) huàr many a picture/painting after painting 1 2 3 4 5 6 7 8 9 10
62
yc zhang zhudzi yc chuàn xiangjiao yc zuò dà shan yc qún yáng yc shuang xiézi yc shuang wàzi yc dui yún yc jià fbijc yc fbng xìn yc zhc xifo nifo
UNIT SEVEN Indefinite plurals
A A large (but unspecified) number or amount may be expressed in Chinese by using the adjectival phrases: hgn dud ‘many; a lot of’ and bù shfo (lit. not few) ‘many; quite a few’. They may modify all types of nouns: hgn dud qián bù shfo she hgn dud péngyou bù shfo jiànyì hgn dud yìjiàn
a lot of money many books many friends quite a few suggestions a lot of opinions
(material) (common) (common) (abstract) (abstract)
Another adjective xjdud ‘many; much; a great deal’ may be used interchangeably with hgndud: e.g. xjdud wèntí ‘many problems’, xjdud rén ‘a lot of people’, etc. As xjdud is more descriptive in tone, it can be used in a reduplicated form often followed by the attributive marker de: e.g. xjxududdud de shangdiàn ‘a great many shops’, xjxududdud de rén ‘a great many people’, etc. Note: When possessive adjectives are present, they precede these indefinite plurals: e.g. ( ) ( )
wi (de) hgn dud péngyou many of my friends ta (de) bùshfo yìjiàn quite a few of his opinions
B To express an unspecified number or quantity, few’, is used, again with all types of nouns:
( )
ycxib zhh ycxib pútao ycxib shuh yiu (yc)xib xcwàng
ycxib ‘some; a
some paper a few grapes some water there is some hope
(material) (common) (material) (abstract)
63
7 Indefinite plurals
A smaller number or amount can be expressed respectively by ‘ jh + measure word’ ‘some; a few’ and ( ) ycdifn(r) ‘some; a little; a bit’. The former is generally used with common nouns and the latter, mostly with material nouns (e.g. ‘iron, water, cloth’, etc.) or abstract notions (e.g. ideas, feelings, etc.):
( )
jh gè rén jh fú huàr jh liàng zìxíngchb
a few people a few pictures a few bicycles
(common) (common) (common)
ycdifn(r) yán ycdifnr dàoli
a bit of salt some sense
(material) (abstract)
( ) ( ) yiu (yc)difn(r) jhnzhang (to be) (lit. have/having a bit of nervousness)
a bit nervous (abstract)
( ) méi yiu ycdifn(r) xcwàng (to be) without any hope
(abstract)
Note: ( ) yiu (yc)xib/ ( ) ( ) yiu (yc)difn(r) + nouns/ verbs or noun/verb phrases may often constitute adjectival predicates: ( ) ta yiu (yc)xib shcwàng ‘He was somewhat e.g. disappointed’; ( ) ( ) wi yiu (yc)difn(r) bù shefu ‘I felt somewhat uncomfortable’, etc.
C Though a ‘ jh + measure word’ phrase is usually used with common nouns, it may also be used with material nouns if the measure word is a container or a standard measurement (e.g. bottle, kilo, etc.): jh píng jij a few bottles of wine (container) jh wfn fàn a few bowls of rice (container) jh shbng qìyóu several litres of petrol (standard measure) jh gdngjcn mflíngshj several kilos of potatoes (standard measure)
64
Note: Compare the different uses of questions:
jh in statements and
wi mfi le jh ping jij I have bought a few bottles of wine. nh mfi le jh ping jij How many bottles of wine have you bought?
7 Indefinite plurals
D These noun phrases, being indefinite plurals, naturally occur after the verb in the object position:
nèi tian | wi jiàn dào le bùshfo péngyou I met quite a few friends that day. nèi tian | wi pèng dào le xjdud wèntí I came across many problems that day. These indefinite plurals can be moved to a pre-verbal position by using yiu before them to retain their indefinite reference: the verb nèi tian yiu xjdud péngyou lái kàn wi Many friends came to see me that day. E Only ( ) ycdifn(r) and ‘ jh + measure word’ phrases can be used in negative sentences (unlike yc xib which cannot): ( ) zhèr méi yiu ycdifn(r) shuh There isn’t any water here. ( ) wi méi yiu ycdifn(r) qián I don’t have any money. ( ) wi méi(yiu) pèngjiàn jh gè péngyou I didn’t bump into many friends. One does not say, for example: *
wi méi yiu yc xib qián I don’t have any money
The negative emphasis is intensified if ( ) ycdifn(r) and its noun is moved to a position before the verb with yg or ddu coming right after it: ( ) zhèr ycdifn(r) shuh yg méi yiu (more emphatic) There isn’t any water here at all.
65
7 Indefinite plurals
( ) wi ycdifn(r) qián yg méi yiu (more emphatic) I don’t have any money at all. ( ) zhèi gè rén ycdifn(r) dàoli ddu bù jifng This person was totally unreasonable. (lit. This person was not concerned with reason in any way.)
Note:
( ) ycdifn(r) may, of course, occur without a noun:
( ) ta ycdifn(r) yg bù chc She didn’t eat anything at all. This emphatic construction is also regularly used with ‘ (+ noun)’ phrases:
yc + measure
zhèr yc gè rén yg méi yiu There isn’t anyone here at all. wi shbn shang yc fbn qián yg méi yiu I don’t have a cent/penny on me. ta yc kiu fàn yg bù xifng chc She doesn’t want to eat a single mouthful. The emphasis can be increased still further by placing lián ‘even’ before ( ) ycdifn(r) or ‘ yc + measure word (+ noun)’ phrases: zhèr lián yc gè rén yg méi yiu There isn’t even one person here. wi shbn shang lián yc fbn qián yg méi yiu I’ve got absolutely no money at all on me. F Interrogative pronouns discussed in Unit 4 (e.g. shéi/shuí, shénme, nfr, etc.) may also be used as indefinite plurals in preverb positions in conjunction with ddu/ yg: shéi/shuí ddu lái le Everybody has turned up. 66
( ) shéi/shuí yg méi(yiu) lái Nobody has turned up.
( ) ta shénme yg méi(yiu) mfi He did not buy anything. ta nfr ddu qù guo She’s been everywhere./There’s no place she’s not been to.
7 Indefinite plurals
Note: The difference between yg and ddu is that the former tends to be used more often in a negative context.
These interrogative pronouns may be used as objects in negative sentences in a similar way: ( ) wi méi(yiu) pèngjiàn shéi/shuí I did not bump into anybody. ta bù xifng chc shénme He did not want to eat anything. nh qù guo nfr ma Didn’t you go anywhere? G Human nouns which take the suffix men are of definite reference and cannot therefore be modified by measure word phrases (see Unit 1 D) or adjectives like hgn dud, bù shfo, ycxib or ( ) ycdifn(r), etc. which express indefinite plurals. One cannot say: * *
hgn dud xuéshengmen ycxib péngyoumen
(lit. many students) (lit. some friends)
Exercise 7.1 Pick out the Chinese phrases/sentences below that are incorrect and make necessary corrections: 1 2 3 4 5 6 7
bù shfo xuésheng bù shfo gè háizi bù shfo péngyoumen ycxib pútao hgn dud gè miànbao hgn dud yìjian ( )
ycdifn(r) shuh
many students many children many friends some grapes a lot of bread a lot of criticism (lit. opinions) a little water
67
7 Indefinite plurals
8 9 10 11 12 13
( )
14 15
jh gè chéngzi hgn dud rénmen ycxib gdngchéng shcmen ycxib yán ycxib qián yg méi yiu ycdifn(r) xcwàng yg méi yiu méi yiu yc wfn fàn lián jia li yc lì mh yg méi yiu huayuán li yc dui huar yg méi yiu
16
a few oranges quite a lot of people some engineers some salt have no money at all have no hope at all there isn’t a single bowl of (cooked) rice There isn’t a single grain of rice at home. There isn’t a single flower in the garden.
Exercise 7.2 Complete the Chinese sentences below by filling the gaps with one of the following expressions: ycxib
hgn dud
bù shfo
( ) ycdifn(r)
1
68
dìdi mfi le wánjù My younger brother has bought a lot of toys. 2 ( ) nfinai méi hb niúnfi Grandma didn’t drink any milk at all. 3 yéye chc le pútao Grandpa ate quite a lot of grapes. 4 jigjie chéngzi yg méi chc (My) elder sister didn’t eat a single orange. 5 mama jifng le gùshi Mother told many stories. 6 bàba qù guo guójia My father has been to a lot of countries. 7 gbge kfo le miànbao My elder brother baked some bread.
yc gè
8
7 Indefinite plurals
( ) mèimei méi dài qián My younger sister hasn’t got any money with her.
9 wi zài xuéxiào jiao le I made a lot of friends at school.
péngyou
10 bàba xig le xìn Father wrote quite a few letters.
Exercise 7.3 Rephrase the following Chinese sentences to make them more emphatic: wi shbn shang méi yiu yc fbn qián I haven’t got any money on me. 2 wi jia li méi yiu yc bgn cídifn I don’t have a single dictionary in my house. 3 bcngxiang li méi yiu ycdifnr shuhgui ( shuhgui ‘fruit’) There aren’t any fruit in the fridge. 4 ta méi shud shénme She didn’t say anything. 5 ta méi chc shénme ddngxi He didn’t eat anything. 6 mama méi mfi shénme ròu Mother didn’t buy any meat at all. 7 wimen méi qù nfr We didn’t go anywhere. 8 wi zuótian méi pèngjiàn shuí/shéi I didn’t bump into anybody yesterday. 1
Exercise 7.4 Fill in the gaps in the following exchanges with ycdifn(r) as appropriate: 1
ycxib or
( )
nh xifng mfi lifng shuang xcn wàzi ma Do you want to buy two new pairs of socks? bù | wi zhh yào mfi yc shuang | wi zhh yiu qián le No, I only want to buy one pair. I’ve only got a little money.
69
7 Indefinite plurals
2
jcntian nh hb guo píjij ma Have you had any beer today? ( ) méi yiu | jcntian wi píjij yg méi(yiu) hb No, I haven’t had any beer today.
3
nh mama hfo ma How is your mother? ( ) ta bìng le | san tian méi chc ddngxi le She’s ill. She hasn’t touched anything for three days.
4
wi è le ( I am hungry.
è ‘to be hungry’)
wi zhèr hái yiu miànbao | nh xifng chc ma I’ve got some bread here. Would you like it? 5
nh dài le qián ma Have you any money with you? duìbuqh | wi shbn shang qián yg méi dài I’m sorry. I haven’t brought any money with me.
6
zhèi jiàn shìr yiu xcwàng ma ( shìr ‘affair; matter’) Is there any hope with this? duìbuqh | xcwàng yg méi yiu I’m sorry. There’s no hope at all.
7
nh yào zài chá li jia táng ma ( jia ‘to add’; táng ‘sugar’) Would you like some sugar in your tea? xièxie | táng yg bù jia No, thank you. I won’t have any sugar.
8
nh hb le hgn dud píjij ma Have you had a lot of beer? bù | wi zhh hb le I have only had a little (beer).
píjij
Pattern and vocabulary drill 7.1
70
First translate the following phrases into English and then turn them into yes or no questions using the formula ... nh yiu . . . ma ‘Have you got . . . ?’:
1 2 3 4 5 6 7 8 9 10
hgndud she bùshfo háizi ycdifnr qìyóu ycxib mh xjdud cài ( cài ‘dishes’; cf. shecài ‘vegetables’) jh bf yhzi jh kuài qián ( kuài ‘Chinese currency unit for one yuan’) ycxib zhh ycdifnr yán ycdifnr shíjian ( shíjian ‘time’)
7 Indefinite plurals
Note: Observe the difference in meaning between questions with and without ma when using the word jh: nh yiu jh kuài qián How many yuan have you got? nh yiu jh kuài qián ma Have you got a few yuan (on you)?
Pattern and vocabulary drill 7.2 Formulate sentences following the given model: jib shang ‘in the street’ rén ‘person’ jib shang yc gè rén yg méi yiu There isn’t a single person in the street. 1 2 3 4 5 6 7
chb shang chéngkè There isn’t a single passenger on the bus. wi (de) qiánbao li qián There isn’t a single penny in my purse. pcngzi li jij There isn’t a single drop of wine in the bottle. shejià shang she There isn’t a single book on the bookshelf. hé shang chuán There isn’t a single boat on the river. ta de huà dàoli There isn’t a single grain of truth in what he says. ycguì li qúnzi There isn’t a single skirt in the wardrobe.
71
7 Indefinite plurals
72
8
wfnguì li wfn There isn’t a single bowl in the cupboard. 9 nèi gè rén péngyou That person doesn’t have a single friend. 10 zhèi jiàn shì xcwàng There isn’t a single ray of hope in this (matter).
UNIT EIGHT Times and dates
A The hours of the day are expressed by difn ‘hour’ is essentially a measure and lifng difn shí yc difn zhdng B fbn ‘minute’ and difn: ( )
( )
difn or difn zhdng. zhdng means ‘clock’:
two o’clock eleven o’clock
kè ‘quarter of an hour’ are placed after
san difn èr shí (fbn) liù difn yc kè ba difn san kè jij difn wj shí (fbn)
twenty minutes past three a quarter past six a quarter to nine nine fifty
líng ‘zero’ is used as a filler when the minutes after the hour are less than ten: wj difn líng wj fbn sì difn líng èr fbn C
For ‘half past’
five past five two minutes past four
bàn ‘half’ comes immediately after lifng difn bàn shí difn bàn
difn:
half past two half past ten
D Expressions for ‘to’ the hour use chà (lit.) ‘lack, be short of’ which can form a phrase before or after difn: chà shí fbn or sì difn chà yc kè or qc difn
sì difn chà ten to four shí fbn qì difn chà a quarter to yc kè seven 73
8 Times and dates
As we can see from the above examples, when the time expression contains other time units apart from the hour, only difn and not difn zhdng can be used to mean ‘o’clock’. One does not say: * * *
( )
san difn zhdng èr shí (fbn) liù difn zhdng yc kè lifng difn zhdng bàn
E To indicate a.m. and p.m., time expressions for particular periods of the day are used: zfoshang shàngwj xiàwj wfnshang bànyè
morning (early) morning (before noon) afternoon evening (night) midnight
wfnshang shí yc difn bàn half past eleven in the evening (11.30 p.m.) xiàwj san difn three o’clock in the afternoon (3 p.m.) zfoshang qc difn yc kè a quarter past seven in the morning (7.15 a.m.) shàngwj shí difn èr shí fbn twenty past ten in the morning (10.20 a.m.) F With the exception of Sunday, days of the week, starting from Monday, are formed by placing the numbers one to six after xcngqc or lhbài ‘week’ and for Sunday tian ‘heaven’ or rì ‘sun’ come after xcngqc/ lhbài: / / / / / / /
74
/
yc èr san sì wj liù rì/tian
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
G Months are also formed numerically by putting the numbers one to twelve before yuè ‘month (or moon)’:
ycyuè wjyuè bayuè shíèryuè Note 1: January is also
January May August December
8 Times and dates
zhbngyuè.
Note 2: The word fèn ‘portion’ is often added to a particular month (except zhbngyuè, an alternative for ycyuè) to mean the whole of that month or a certain period of time within that month: e.g. nh yc yuè fèn zài nfr ‘Where are you in January?’
H Dates of the month are expressed by / /
hào or, in writing,
èryuè san hào/rì shíycyuè èr shí jij hào/rì
rì:
3rd February 29th November
I Years, unlike English, are pronounced in numerical sequence: yc jij jij liù nián nineteen ninety-six yc jij sì wj nián nineteen forty-five yc jij yc yc nián nineteen eleven
1996 1945 1911
J Other common time expressions indicating the recent past, present or near future are: jcntian míngtcan hòutian dà hòutian zuótian qiántian dà qiántian zhèi gè yuè xià gè yuè xià xià gè yuè shàng gè yuè shàng xcngqc yc xià lhbài wj jcnnián
today tomorrow the day after tomorrow in three days time yesterday the day before yesterday three days ago this month next month the month after next last month last Monday next Friday this year
75
míngnián next year hòunián the year after next qùnián last year qíannián the year before last dà qiánnián three years ago jcnnián chentian this spring qùnián xiàtian last summer míngnián qietian next autumn qiánnián ddngtian winter the year before last
8 Times and dates
K Questions about time, apart from the general enquiry shénme shíhou or jh shí ‘when?’, are linked with the particular time expression and all involve the use of jh ‘how many’: ( ) /
jh difn (zhdng) jcntian xcngqc/ lhbài jh jcntian jh hào xiànzài jh yuè
What time (of the day) is it? What day is it today? What is the date today? What month is it (now)?
Note: nf/ngi ‘which?’ can also be used with time words like tian ‘day’, yuè ‘month’, nián ‘year’. With yuè ‘month’, one can also use nf/ngi gè, which also occurs with / xcngqc/lhbài ‘week’: nh ngi tian ziu Which day are you leaving? ( ) nhmen ngi (gè) yuè huí lái In which month are you (pl.) coming back? ( ) nh nf (gè) xcngqc/lhbài huí jia / Which week are you going home? In questions (as above) or statements about time the link verb ‘to be’ is not normally used: xiànzài jij difn bàn It’s half past nine (now). / Today is 21st August. 76
jcntian bayuè èr shí yc hào/rì
shì
However it is not wrong to say: xiànzài shì liù difn bàn jcntian shì xcngqc san
It’s half past six (now). Today is Wednesday.
8 Times and dates
Further question-and-answer examples: nh jh difn qhchuáng What time do you (usually) get up? wi zfoshang qc difn bàn qhchuáng I (usually) get up at half past seven. ( ) kèrenmen jh difn (zhdng) lái What time are the guests/visitors arriving? ( ) tamen xiàwj san difn (zhdng) lái They are coming at three o’clock in the afternoon. nh jh shí huí ycngguó When are you going back to Britain? wi míngnián jijyuè huí qù I’m going back in September next year. nh jh hào dòngshbn dào duzhdu qù Which day of the month are you setting out for Europe? wi sì hào ziu I’m leaving on the fourth. / nh xcngqc/lhbài jh huí lái On which day of the week are you coming back? / wi xcngqc/lhbài wj huí lái I am coming back on Friday. In dates and complex time expressions larger units always precede smaller ones:
yc jij jij liù nián sanyuè èr shí qc hào xiàwj lifng difn líng wj fbn Five past two on the afternoon of the twenty-seventh of March nineteen ninety-six L Time expressions can also be formed by using verbs or activity nouns followed by qián ‘before’, hòu ‘after’, or zhdng ‘during’ (see also Unit 14): chefa qián fàngxué hòu
before setting out after school
77
8 Times and dates
yfnche zhdng fàn hòu kè hòu
during the performance after a meal after class
M As we can see from all the sentence examples above, the time expressions are always placed next to the subject (often after it and sometimes before it as a sentence opener for emphasis) and before the main verb. They in fact have a similar function to the tense indicators of English verbs. (See Unit 14.) nh lhbài tian zuò shénme What do you do on Sundays?/What are you going to do on Sunday? nh zuótian xiàwj zuò shénme What did you do yesterday afternoon? wimen jcntian wfnshang qù jijbajian We’re going to a pub this evening. wi míngnián sanyuè qù bgijcng I’m going to Beijing next March. nh míngtian lái wi jia ma Are you coming to my place tomorrow? qiántian nh qù le nfr Where were you the day before yesterday? xià ban hòu nh qù nfr Where are you going after work?
Exercise 8.1 Translate the following Chinese phrases into English:
78
1 2 3 4 5 6 7 8 9 10
san difn zhdng shí èr difn zhdng lifng difn èr shí fbn qc difn wj shí wj fbn chà shí fbn ba difn shí yc difn yc kè jij difn bàn shí difn líng yc fbn shí èr difn líng wj fbn liù difn san kè
Exercise 8.2 Provide answers to the Chinese questions below using the information in brackets:
8 Times and dates
( ) xiànzài jh difn (zhdng) What time is it (now)? (7.15 a.m.) / xiànzài shàngwj qc difn yc kè/shí wj fbn It’s 7.15 a.m. 1 2 3 4 5 6 7
8 9
10 11 12
nh jh difn zhdng qù xuéxiào What time are you going to school? (8.30 a.m.) nh shénme shíhou qù yóuying What time are you going swimming? (8.55 a.m.) nh péngyou xiàwj jh difn xiàban What time does your friend finish work in the afternoon? (5.45 p.m.) nhmen jh difn chc wfnfàn What time do you have your supper? (about 9.00 p.m.) nh ngi tian pèngjiàn wi sheshu On which day of the month did you bump into my uncle? (the sixth) nh bàba jh hào qù zhdngguó Which day of the month is your father going to China? (the eleventh) nh mèimei jh difn zhdng shuìjiào What time does your younger sister go to bed? (around 12 midnight) nh xià gè yuè jh hào ggi ta xig xìn On which day of next month are you going to write to him? (the 21st) nh xià xcngqc jh lái zhèr kai zuòtánhuì ( kai ‘to attend (a meeting)’) ( zuòtánhuì ‘discussion; seminar’) On which day next week are you coming for a seminar? (Thursday) nh ngi nián bìyè ( bìyè ‘to graduate’) When will you graduate? (1999) nh jh shí dào duzhdu qù When are you going to Europe? (next September) nh tóngxué míngnián jh yuè huí guó Which month next year are your coursemates going back to their home country? (December)
Exercise 8.3 Form questions in Chinese that would elicit the answers specified in bold italics below, making appropriate adjustments, where necessary, to the personal pronouns involved:
79
8 Times and dates
wi èryuè wJ hào qù wi péngyou jia I am going to my friend’s house on the fifth of February. / nh shénme shíhou/jH hào qù nh péngyou jia When/what date are you going to your friend’s house? 1
ta liù diFn bàn chc wfnfàn She has her dinner at half past six. 2 wi lhbài wj wfnshang qC diFn lái nh jia I’ll come to your house at 7 o’clock on Friday evening. 3 wimen bayuè shí hào qù dùjià ( dùjià ‘to go on holiday’) We’re going on holiday on the tenth of August. 4 wi yC jiJ jiJ wJ nián dì yc cì jiàn dào ta I met her for the first time in 1995. 5 wi mama wJ diFn bàn huí jia Mother comes home at half past five. 6 xcn jcnglh xià xCngqC èr lái zhèr shàngban The new manager will start work here next Tuesday. 7 wimen xià gè yuè qù zhfo nh We’ll go and see you next month. 8 tamen míngnián bìyè They will graduate next year. 9 wi jigjie shàng xCngqC sAn xiàwj zài xué kaichb My elder sister was learning to drive last Wednesday afternoon. 10 wi qùnián shíyCyuè mfi zhèi fú huàr I bought this painting in November last year. 11 zuòtánhuì shàngwj jiJ diFn bàn kaishh The discussion starts at half past nine in the morning. 12 wi míngtian zFoshang zài jia li xiexi I am resting at home tomorrow morning.
Exercise 8.4 Translate the following sentences into Chinese:
80
1 What time are you going to school tomorrow? ( ‘school’) 2 I am coming here to attend the seminar next month. ( zuòtánhuì ‘to attend a seminar’)
xuéxiào kai
3 When are you going on a trip to Europe? ( lsxíng ‘to travel’) 4 What time are you going to work tomorrow? ( shàngban ‘to go to work’) 5 What time in the afternoon are you going to the swimming-pool for a swim? ( yóuyingchí ‘swimming-pool’) 6 Which day are you going there to play football? ( tc zúqiú ‘to play football’) 7 Which month are you going to the seaside for a holiday? ( hfi bian ‘beach; seaside’) 8 What time are you going to the railway station to buy the ticket? ( huichbzhàn ‘railway station’) 9 What time in the morning are you going to the market? ( mfi ddngxi ‘to do some shopping’) 10 When are you going to the library to borrow books? ( jiè she ‘to borrow books’)
8 Times and dates
Pattern and vocabulary drill 8.1 Following the given pattern, formulate questions about what someone may be going to do at a particular time, using the times and activities specified in each of the twelve cases: Model:
Time: Activity:
míngtian xiàwj tomorrow afternoon kàn diànyhng see a film/movie
Answer: nh míngtian xiàwj qù kàn diànyhng ma Are you going to the cinema tomorrow afternoon? Include 1 2 3 4 5 6 7
qù if the activity requires the person to go out.
zhèi gè xcngqc tian this coming Sunday kàn qiúsài see a football match ( ) xià (gè) lhbài next week jiàn nh (de) dfoshc see your supervisor míngtian shàngwj tomorrow morning kàn ycshbng see a doctor xià xcngqc èr next Tuesday xué tàijíquán learn T’ai Chi jcntian xiàwj this afternoon wèi mao feed the cat jcntian wfnshang this evening shàng wfng go on the internet míngtian fàngxué hòu tomorrow after school diàoyú go fishing/angling
81
8 Times and dates
8 9 10 11 12
míngtian xiàban hòu tomorrow after work xué kaichb take driving lessons jcn wfn this evening kàn diànshì watch television míngnián bìyè hòu next year after graduation lsxíng go travelling xià gè yuè next month tàn(wàng) nh fùmj see your parents jcnnián liù yuè fèn this June dù jià go on holiday
Note: kàn ‘to watch; see; visit’ is used in the context of entertainment or visit whereas jiàn ‘to see’ is used for an appointment (except in the case of seeing a doctor).
Pattern and vocabulary drill 8.2 The following sentences are answers you have given to questions about timing. Work out in each case what Chinese question was put to you. The model provides an example. nh zfoshang jh difn zhdng qhchuáng wi zfoshang ba difn zhdng qhchuáng I get up at eight in the morning. 1
2 3 4 5 6 7 82
( ) wi wfnshang shí yc difn bàn (shàngchuáng) shuìjiào I go to bed at half past eleven. wi zfoshang jij difn zhdng shàngban I go to work at nine o’clock in the morning. wi liù hào dòngshbn dào zhdngguó qù I am setting out for China on the 6th. wi dàyub wj diàn bàn xiàban I finish work around half past five. wi xià xcngqc sì ziu I am leaving next Thursday. wi míng wfn lái zhfo nh I’ll come to see you tomorrow evening. wi hòutian qhng nh lái wi jia I’ll invite you to my place the day after tomorrow.
8
wi míngtian xiàwj zài jia I am home tomorrow afternoon. 9 wi qiánnián chentian zhù zài bgijcng I lived in Beijing in the spring of the year before last. 10 wi qùnián zài bgijcng rènshi ta I got to know him last year in Beijing.
8 Times and dates
83
UNIT NINE More interrogative expressions
In the last unit we discussed interrogative time expressions which include jh difn zhdng ‘what time (of the day)’ and jh shí or shénme shíhou ‘when’, etc., and in Unit 4 we dealt with a number of interrogative pronouns including the interrogative location expression nfr ‘where’. In this unit we shall look at some more interrogative idioms and expressions. A dud jij and dud cháng shíjian ‘how long’ are placed immediately after the verb, as are more precise questions such as ( )/ ( ) dudshao tian (nián)/jh tian (nián) ‘how many days (years)’, / ( / ) dudshao gè/jh gè yuè (xcngqc/ lhbài) ‘how many months (weeks)’, etc.: ( ) nh dai le dud cháng shíjian How long did you stay? ta dgng le dud jij How long did he wait? nhmen zài nèi gè guójia zhù le dudshao nián How many years did you live in that country?
Note: These question phrases, like all time duration expressions, are placed after the verb and are essentially complements. For further discussion of duration expressions, see Unit 14.
When there is an object with the verb, if it is a pronoun it precedes the interrogative expression; if it is a noun it follows the interrogative expression with or without de: 84
nh dgng le ta dud jij How long did you wait for him?
( ) nh xué le dud cháng shíjian (de) zhdngwén How long did you learn Chinese for? ( ) nh jigjie dang le dudshao nián (de) hùshi How many years was your elder sister a nurse?
9 More interrogative expressions
Another common way to formulate questions of this type where the verb has an object is to repeat the verb after the object and then place the question expression after this repeated verb (see Unit 14): / nh xué zhdngwén xué le dud jij/dud cháng shíjian How long did you learn Chinese for? nh jigjie dAng hùshi dAng le dudshao nián How many years was your elder sister a nurse? A considerable number of common verbs in Chinese are intrinsically of a ‘verb + object’ construction, e.g. yóuying ‘to swim’, tiàowj ‘to dance’, chànggb ‘to sing’, shuìjiào ‘to sleep’, ziulù ‘to walk’, etc. With these verbs the same rule applies: ( ) nh hé nh péngyou tiào le jh gè zhdngtóu (de) wj or
nh hé nh péngyou tiàowj tiào le jh gè zhdngtóu How many hours did you dance with your friend? One cannot say: * nh hé nh péngyou tiàowj le jh gè zhdngtóu (lit. How many hours did you dance with your friend?) B dud ‘how’ may in fact be used with many adjectives in questions of degree, for example, of size, weight, etc. The pattern of such enquiries is usually ‘ yiu + dud + adjective’: zhdngguó yiu dud dà How big is China? nh de xíngli yiu dud zhòng How heavy is your luggage?
85
nh jigjie yiu dud gao How tall is your elder sister?
9 More interrogative expressions
zhèi gè yóuyingchí yiu dud cháng How long is this swimming-pool? xuéxiào lí zhèr yiu dud yufn How far is the school from here? Note: lí in the last example is a coverb which occurs with other verbs or adjectives to mean ‘distance (away) from (a place)’ (see Unit 24). C dud may also be used in conjunction with an adjective as an adverbial or an attributive: (i) as an adverbial to modify a verb nh dud kuài néng wánchéng zhèi jiàn gdngzuò How fast can you finish this work? (ii) as an attributive with de to modify a noun nh chuan dud dà de xié What size (lit. how big) shoes do you take? D zgn yàng, zgnme and zgnme yàng are used adverbially before verbs to mean ‘how; in what way’: wi zgnme yàng qù lúnden How do I get to London? qù yóuyingchí zgnme ziu How do you get to the swimming-pool? Note: Observe the different meanings of ziu: (i) ‘to walk; to come/go on foot’ in wi ziulù qù ‘I’ll go on foot’; (ii) ‘to leave’ in ta ziu le ‘He’s left’; and (iii) ‘to get to (a place) (often with zgnme or zgn yàng)’ in qù chbzhàn zgn yàng ziu ‘How do you get to the station?’ E zgnme yàng can be used as a predicate to mean ‘what is (something or somebody) like’/‘how is (somebody or something)’: 86
nàr de tianqì zgnme yàng What’s the weather like there?
nh dìdi zgnme yàng How is your younger brother? gdngzuò zgnme yàng How’s work? F zgnme yàng in addition, can occur after a statement and convert that statement into a question ‘what/how about . . .’ (it is often used when making suggestions about future actions or activities):
9 More interrogative expressions
wfnshang wimen qù kàn diànyhng | zgnme yàng How about going to the cinema this evening? zánmen míngtian qù tiàowj | zgnme yàng What about going dancing tomorrow? G
wèi shénme ‘why’ is usually placed before the verb: nh wèi shénme xué zhdngwén Why do you study Chinese? xifo lh zuótian wèi shénme bù lái Why didn’t Xiao Li come yesterday?
Note: xifo is often used before the family name or given name (which must be a monosyllable) of a person who is younger than the speaker. It implies a degree of familiarity with the person addressed. In addressing someone older than onself, lfo is used in a similar way. H
zgnme is also used colloquially to mean ‘how is it? how come?’: nh zgnme bù qù kàn ta Why aren’t you going to see him? ta zgnme huì jifng rìyj How come she can speak Japanese?
Exercise 9.1 Convert the Chinese statements below into questions, focusing on the elements in bold italics. Please also make adjustments to the pronouns as necessary:
87
9 More interrogative expressions
wi zài zhèr zhù le liù nián I lived here for six years. / nh zài zhèr zhù le duD jiJ/duD cháng shíjiAn How long did you live here? 1
wi zài lù shang hua le liFng xiFoshí It took me two hours to get here.
2 wi zài jiàoshì li kàn le yC gè duD xiFoshí de she I read for over an hour in the classroom. 3 zúqiú bhsài kaishh bàn gè zhDngtóu le The soccer match started half an hour ago. 4 wi hé jigjie zài huayuán li zuò le shí lái fBn zhDng My elder sister and I sat in the garden for over ten minutes. 5 mama zài chúfáng li máng le jH gè zhDngtóu Mother was busy cooking in the kitchen for several hours. 6 mèimei bang le wi liFng tian de máng My younger sister helped me for two days. 7 wi kai le yC nián chb | qí le liFng nián zìxíngchb I drove for a year and travelled by bike for two years. 8 zúqiúchfng yiu bA shí mH cháng The football pitch is 80 metres long. 9 wi gbge yiu yC mH qC gAo My elder brother is 1 metre 70 tall. 10 balí lí lúnden yiu èr bFi yCnglH yuFn Paris is two hundred miles from London.
Exercise 9.2 Translate into English the following sentences with zgn yàng or zgnme yàng:
zgnme,
1 2 3
88
4 5
zánmen xià xcngqc yc qù ta jia kàn ta | zgnme yàng / qù qìchbzhàn zgn yàng/zgnme ziu lúnden de jiaotdng zgnme yàng ( jiaotdng ‘transport; traffic’) / qù diànyhngyuàn zgnme/zgn yàng ziu míng wfn zánmen qù jijbajian hb píjij | zgnme yàng
6 bgijcng de tianqì zgnme yàng 7 nèi jia shangdiàn de ddngxi zgnme yàng 8 zánmen xià gè yuè qù dùjià | zgnme yàng
9 More interrogative expressions
Exercise 9.3 Translate the following questions into Chinese: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
How much did you eat? How did you get to London? Why did he leave? How long are you going to stay? How did you make this cake? What’s your new house like? How much money have you got? What was the film like? How about a drink? Why are you learning Chinese? How do I get to know Xiao Li? What do you think of the Chinese teacher? How do you go to work? How long have you been waiting for her? How many hours did she sleep? How many days did you (pl.) drive? How long did you wait for the bus? How far did you walk?
Exercise 9.4 Complete the Chinese translations of the English sentences below with ‘ dud + adjective’ (as appropriate): 1 How far is it to London? qù lúnden yiu 2 How tall is your younger brother? nh dìdi yiu 3 How many people are there in Beijing? bgijcng yiu rén 4 How far is the post office from here? yóujú lí zhèr yiu
89
5 How heavy is this piece of luggage?
9 More interrogative expressions
zhèi jiàn xíngli yiu 6 How heavy is the rain outside? wàimian de yj yiu 7 How much is that pair of trousers? ( ) (mfi) nèi tiáo kùzi yào qián 8 What size is that pair of shoes? nèi shuang xié yiu 9 How many miles did he run? ta páo le ycnglh lù 10 How long has Li Ming been gone? / lh míng ziu le / le 11 Have you been dancing the whole evening? / ( ) nhmen tiào le / (de) wj 12 How much time have we still got? wimen hái yiu shíjian 13 How long have you been here? / nhmen zài zhèr dai le / 14 How much work have you done? nhmen zuò le gdngzuò
Pattern and vocabulary drill 9.1 Formulate suggestions with the 15 verb phrases given below by tagging on the final phrase zgnme yàng ‘How about . . . ?’ Begin each sentence with wimen ‘we’, and add the time expression given in brackets, and qù ‘to go’ where appropriate. 1 2 3 4 5 6 90
7
( ) hb (yc) bbi píjij ‘to have a glass of beer’ (this evening) tiàowj ‘to go dancing’ (tomorrow) dùjià ‘to go on holiday’ (next year) jifng zhdngwén ‘to speak Chinese’ (now) ( ) mfi (yc) xib xiangjiao ‘to buy some bananas’ (in the afternoon) ( ) chá li jia (yc)difnr táng ‘to put some sugar in the tea’ yóuying ‘to go swimming’ (today)
8 9 10 11 12 13 14 15
( ) ( ) kàn (yc) chfng zúqiú (bh)sài ‘to go and see a football match’ (on Saturday) xué tàijíquán ‘to learn T’ai Chi’ (next month) wánchéng zhèi jiàn gdngzuò ‘to complete this task’ (at three o’clock) zhfo jcnglh ‘to see the manager’ (on Tuesday) tànwàng ta ‘to visit him’ ( yhhòu ‘afterwards’) zài jia li xiexi ‘to have a rest at home’ (this afternoon) df qiú ‘to play a game (of basketball, tennis, badminton, ping pong, etc.)’ (next Friday) tc qiú ‘to play a game (of soccer)’ (tomorrow afternoon)
9 More interrogative expressions
Pattern and vocabulary drill 9.2 First, use the phrase below.
dud cháng shíjian to ask the questions
How long did you wait for me there? nh zài nàr dgng le wi dud cháng shíjian 1 2 3 4 5 6 7 8 9 10
How How How How How How How How How How
long long long long long long long long long long
did you stay there? did you live there? did you wait there? did you work there? did you study there? did you stay in the pub? have you been resting at home? have you been driving? have you been travelling in Europe? have you known her?
Second, use the phrase yào dud cháng shíjian ‘how long does it take’ to complete the following questions. How long does it take to go to London by train? zuò huichb qù lúnden yào dud cháng shíjian 1 How long does it take to drive down to London? 2 How long does it take to fly to Beijing? ( zuò fbijc ‘to fly; to go by plane’) 3 How long does it take to get to the railway station by taxi? ( dìshì ‘taxi’)
91
4 How long does it take to get to the university on foot? ( ‘to go on foot’) 5 How long does it take to get to the city centre by bus? 6 How long does it take to cycle to your place? 7 How long does it take to get to the bank on foot? 8 How long does it take to get to the coach station by taxi? 9 How long does it take to cycle to the football pitch? 10 How long does it take to get to the post office on foot?
9 More interrogative expressions
92
ziulù
UNIT TEN Adjectives: attributive and predicative
Attributives are words placed before nouns to qualify or describe them. Adjectives are obvious examples of attributives. A When a monosyllabic adjective is used as an attributive, it is placed directly before the noun it qualifies: hóng hua bái yún cháng qúnzi zang ycfu
red flowers white clouds a long skirt dirty clothes
Disyllabic adjectives, on the other hand, are normally followed by ganjìng de jibdào piàoliang de chb gjlfo de lóufáng
de:
a clean street a beautiful car ancient buildings
Where there is a ‘numeral + measure’ phrase or a ‘demonstrative + measure’ phrase, it always precedes the adjectival attributive: yc sui xcn fángzi lifng bgn jiù she zhèi jia dà shangdiàn nèi ph hbi mf yc chfng jcngcfi de bhsài lifng gè yiuqù de gùshi
a new house two old books this big store that black horse an exciting match two interesting stories
Note: When a disyllabic adjective qualifies a disyllabic noun, de may sometimes be omitted, especially when the combination becomes a set expression: xcnxian shecài fresh vegetables jcngcfi bifoyfn excellent performance
93
10 Adjectives: attributive and predicative
B Adjectives themselves are commonly modified by degree adverbs such as hgn ‘very’, tài ‘too’, shífbn ‘extremely’, fbicháng ‘extremely’ (lit. ‘unusually’): hgn dà tài xifo shífbn ganjìng fbicháng gjlfo
(very) big too small extremely clean incredibly ancient
Note: Adjectives modified by degree adverbs also require the particle de when used as attributives: hgn dà de wezi fbicháng gjlfo de chéngshì
a (very) big room a really ancient city
An exception to this rule are adjectives that indicate indefinite plurals hgn dud, xjdud, and bù shfo ‘many’ (see Unit 7): like tamen yiu hgn dud qián They have a lot of money. mgi nián yiu bù shfo rén lái zhèr kàn fbngjhng Quite a number of people come here for the scenery every year. C When the context is clear, the noun following an adjective can be omitted but a demonstrative and/or numeral is usually present. In all these cases, de is indispensable, whether the adjective is monosyllabic or disyllabic: yc jiàn xcn de
?
a new one (e.g. sweater, shirt, etc.) nèi dui hóng de that red one (e.g. flower, blossom, etc.) zhèi xib bfi de these white ones ngi xib dà de which big ones?
( ) zhèi shuamg kuàizi hgn zang | wi yào (yc) shuang ganjìng de These chopsticks are dirty. I want a clean pair.
94
zhèi tiáo kùzi tài dufn | wi mfi nèi tiáo cháng de These trousers are too short. I’ll have (buy) that longer pair.
Where the adjective occurs with a demonstrative and measure, the adjective may also come first:
zhèi tiáo kùzi tài dufn | wi mfi cháng de nèi tiáo These trousers are too short. I’ll have (buy) that longer pair.
10 Adjectives: attributive and predicative
In addition, an adjective with de may be used on its own and imply a noun which may be singular or plural depending on the context: wi bù yào guì de | wi yào piányi de I don’t want an/the expensive one, I want a/the cheaper one. I don’t want (the) expensive ones, I want (the) cheaper ones D A distinctive feature of Chinese is that when an adjective is used as a predicative, it follows the subject/topic immediately and does not require the link verb shì ‘to be’. In addition, it should always be modified by a degree adverb: nèi tiáo jcedào hgn ganjìng The street is (very) clean. zhèi shuang xiézi tài xifo This pair of shoes is too small. zhèi gè gùshi fbicháng yiuqù This story is extremely interesting. nèi chfng bhsài shífbn jcngcfi That match was extremely exciting. One does not normally say (unless speaking emphatically to reiterate or contradict a statement): jibdào shì ganjìng (lit. The street is clean.) [implying, e.g. who says it isn’t or I did say that it was clean]
Note: The degree adverb hgn, though when stressed it means ‘very’, otherwise carries little meaning. An unmodified adjective, when used as a predicative, always implies some form of contrast and sounds incomplete.
95
10 Adjectives: attributive and predicative
. . . jibdào ganjìng . . . The street is clean [but it is perhaps too narrow] . . . zhèi shuang xiézi xifo . . . This pair of shoes is small [but they are comfortable to wear] In fact, to imply such contrasts, the more usual and colloquial form is to incorporate shì and repeat the adjective with or without bù according to the meaning intended: . . . jibdào ganjìng shì ganjìng | kgshì . . . It is true that the street is clean, but . . . . . . zhèi shuang xiézi xifo shì bù xifo | bùguò . . . It is true that this pair of shoes isn’t small; nevertheless . . . E
An adjectival predicative is negated by
bù ‘not’:
zhèi shuang xiézi bù guì This pair of shoes isn’t expensive. nèi píng niúnfi bù xcnxian That bottle of milk isn’t fresh. jcntian de tianqì bù hfo Today’s weather is bad. The negator bù and a degree adverb may both come before the adjectival predicative. When this happens, the positioning of bù in relation to the degree adverb affects the meaning of the adjective: zhèi sui fángzi bù hgn hfo This house isn’t very good/nice. zhèi sui fángzi hgn bù hfo This house is really bad. (lit. This house is very not good.) zhèi píng niúnfi bù tài xcnxian This bottle of milk isn’t very/too fresh. zhèi píng niúnfi tài bù xcnxian le This bottle of milk isn’t fresh at all.
96
Note: le which comes at the end of the sentence seems indispensable with any predicative that incorporates the degree adverb tài ‘simply too much of a certain quality or quantity’, though this does not apply to bù tài with its understated meaning.
The negator bù is regularly linked with an adjectival predicative:
gòu ‘enough’ to modify
zhèi tiáo qúnzi bù gòu cháng This skirt isn’t long enough. wi zhèi bbi kafbi bù gòu tián This cup of coffee (of mine) isn’t sweet enough. bù is also used in conjunction with / emphasis or to contradict a previous statement:
10 Adjectives: attributive and predicative
ycdifnr yg/ddu for
/ zhèi tiáo kùzi ycdifnr yg/ddu bù dufn This pair of trousers is not short at all. / zhèi bbi chá ycdifnr yg/ddu bù rè This cup of tea isn’t hot at all. F Most monosyllabic adjectives may be reduplicated to intensify their meaning, particularly in descriptive writing. Reduplicated adjectde when qualifying nouns: ives take the particle lánlán de tian a really blue sky (lit. blue blue sky) gaogao de lóufáng really tall buildings (lit. tall tall buildings) ycxib hónghóng de júzi some bright red tangerines (lit. some red red tangerines) A limited number of disyllabic adjectives may also be reduplicated. The pattern for reduplication is: AB > AABB ganjìng ganganjìngjìng zhgngqí zhgngzhengqíqí lfoshí lfolaoshíshí
clean and tidy > spotlessly clean orderly/tidy > very orderly/tidy honest/naïve > very honest/very naïve
yc zhang gangan jìngjìng de zhudzi yc gè zhgngzhengqíqí de fángjian yc gè lfolaoshíshí de rén
a spotlessly clean table an extremely tidy room a very honest person
97
10 Adjectives: attributive and predicative
Reduplicated adjectives, being already emphatic in form, cannot be further modified by a degree adverb or a negator. One cannot say: * *
hgn hónghóng bù ganganjìngjìng
(lit. very red) (lit. not spotlessly clean)
Exercise 10.1 Translate the following phrases into Chinese, paying attention to the inclusion or omission of de: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
a very big swimming-pool new buildings white cats a large bowl a beautiful garden a little child an interesting film an exciting match fresh vegetables a lot of money an old car extremely heavy luggage clean clothes a tidy room very narrow streets ( xiázhfi ‘narrow’) 16 ancient cities 17 an extremely good concert 18 dirty shoes
Exercise 10.2 Indicate which of the Chinese translations given for the English sentences below is correct:
98
1 The weather is nice today. jcntian tianqì hgn hfo jcntian tianqì shì hfo
2 She is rich. ta hgn yiu qián ta shì yiu qián 3 This sofa [armchair] isn’t very comfortable. zhèi gè shafa bù hgn shefu zhèi gè shafa hgn bù shefu
10 Adjectives: attributive and predicative
4 The classroom is really clean. nèi gè jiàoshì fbicháng ganganjìngjìng nèi gè jiàoshì shì fbicháng ganjìng nèi gè jiàoshì fbicháng ganjìng 5 My younger brother isn’t very tall. wi dìdi bù tài gao wi dìdi tài bù gao wi dìdi bù gaogao 6 This match isn’t particularly exciting. zhèi chfng bhsài bù shífbn jcngcfi zhèi chfng bhsài bù jcngjingcficai zhèi chfng bhsài shífbn bù jcngcfi 7 There were toys of all colours on the floor. dì shang ddu shì hónghonglqlq wánjù dì shang ddu shì hónghonglqlq de wánjù dì shang ddu yiu hónghonglqlq de wánjù 8 Mr Wang is a very interesting person. wáng xiansheng shì yc gè fbicháng yiuqù rén wáng xiansheng yc gè fbicháng yiuqù de rén wáng xiansheng shì gè fbicháng yiuqù de rén
Exercise 10.3 Translate the following into Chinese: 1 2 3 4
Beijing is an extremely ancient city. That old book is not too expensive. The library is extremely big. I don’t have any new clothes.
99
10 Adjectives: attributive and predicative
5 6 7 8 9 10
Those fresh flowers are very beautiful. That pair of shoes is too large. The weather here is really nice. That street is not clean enough. I don’t like milk which isn’t fresh. That cup of coffee is too sweet.
Exercise 10.4 Add emphasis to the adjectives in bold italics by means of reduplication: 1 lù páng zuò zhe yc gè gAodà de xifohuizi A tall young man sat by the roadside. 2 xifo wáng zhfng zhe wAn méimao | gAo bhzi | xiFo zuhba hé yc shuang dà yfnjing | liú zhe yc tóu zhGngqí de dufn fà Xiao Wang had curved eyebrows, a straight nose, a small mouth, big eyes and hair cut in a neat bob. 3 zhè shì yc jian gAnjìng de fángjian | bái chuángdan | lán chuanglián | hóng lúhui | ggi nh yc zhing shEshì de gfnjué This is a neat and tidy room. The white sheets, blue curtains and warm fire make it feel very cosy. 4 ta nà pJsù de yczhuó | dàfAng de jjzhh | tiánmGi de shbngycn ggi rén liú xià le shbnkè de yìnxiàng Her plain clothes, dignified bearing and clear, sweet voice made a deep impression on people.
Exercise 10.5 Translate into Chinese, paying particular attention to the pronominal expressions:
100
1 Whose are those? 2 These are mine. 3 The white skirt is yours. The red one is mine.
4 5 6 7 8
We don’t have any new ones. The big ones are expensive. The small ones are not too cheap either. These stories are too long. Those two aren’t. This cup is dirty. I need a clean one. These three students are going to Japan. Which two are going to China? 9 I like these two books. Which two do you like? 10 Which ones are yours?
10 Adjectives: attributive and predicative
Pattern and vocabulary drill 10.1 In the model below two sentences are constructed using a noun phrase and two adjectives. In these sentences the second clause contrasts with the first (a positively and b negatively). Use the ten sets of words given below to form pairs of similar sentences. zhèi liàng chb this car guì expensive hfo kai nice to drive a zhèi liàng chb guì shì guì | bùguò hgn hfo kai It is true that this car is expensive, but it is a very good drive. b zhèi liàng chb guì shì bù guì | kgshì bù hfo kai It is true that this car isn’t expensive, but it isn’t a very good drive. Remember that once the implication is there, you need the conjunction kgshì ‘but’ or bùguò ‘nevertheless’ to signal the transition, and a degree adverb like hgn ‘very’ or a negator in the second clause to emphasize the contrast. 1
zhèi ping jij this bottle of wine guì expensive hfo hb good to drink
2
nèi gè pínggui that apple xifo small hfo chc delicious
3 fi low 4 5
nèi bf yhzi that chair hfo zuò comfortable to sit on
zhèi shiu gb this song nán chàng difficult to sing
hfo tcng pleasant to listen to
nèi gè huapíng that vase piányi cheap hfo kàn pretty
101
10 Adjectives: attributive and predicative
6
nèi zhc bh that pen jiù old hfo xig good to write with
7
zhèi bbi niúnfi this bottle of milk léng cold xcnxian fresh
8
zhèi tiáo jib(dào) that street ganjìng clean zhgngqí orderly
9
nèi gè rén that person cdngming intelligent
10
lfoshi honest
nèi zuò lóufáng that building gjlfo ancient piàoliang pretty
Pattern and vocabulary drill 10.2 Use the formula / ycdifnr yg/ddu bù ‘not . . . at all’ to contradict both statements made in each of the ten groupings in Drill 10.1 above: / zhèi liàng chb ycdifnr yg/ddu bù guì This car isn’t expensive at all. / zhèi liàng chb ycdifnr yg/ddu bù hfo kai This car isn’t a good drive at all.
102
UNIT ELEVEN shì and
yoˇu
A The verb shì ‘to be’ in Chinese is not exactly equivalent to the English verb ‘to be’. It is similar to its English counterpart in that it may generally be followed by a noun which defines the subject/topic: wimen shì xuésheng ta shì lfoshc jcntian shì xcngqc rì
We are students. He is a teacher. Today is Sunday.
The noun which follows shì may, of course, be modified in many ways. It may, for instance, be preceded by a possessive adjective or pronoun, another noun usually, with or without de, a ‘numeral/ demonstrative + measure word’ phrase or an adjective qualifier: ta shì wi zhàngfu He is my husband. nà shì ta de dàyc That is his coat. zhèi wèi shì zhang xiansheng de péngyou This is Mr Zhang’s friend. zhèi xib shì zhdngguó huà These are Chinese paintings. nà shì yc gè mántou That is a steamed bun. zhè shì yc bgn hgn yiu yìsi de she This is a very interesting book. If the noun that follows shì is qualified by an attributive and repeats the topic or if it is understood from the context, it may be omitted:
103
11
zhèi zhc bh shì wi de (pronoun attributive) This pen is mine.
shì and yoˇu
nèi ph mf shì zhang xiansheng de (noun attributive) That horse is Mr Zhang’s. zhèi yc gè shì hfo de (adjective attributive) This is a good one. B However, shì is not normally followed by an adjective on its own unless one is speaking emphatically to reiterate a case, contradict a previous speaker, etc. (see Unit 10): zhèi bgn she shì guì This book is expensive. (I admit, but another may be more expensive, etc.) ta shì fbicháng cdngming She is extremely intelligent. (The problem is that she isn’t really conscientious.) Normal unemphasized sentences have an adjectival predicative without shì (see previous unit): zhèi bgn she hgn guì This book is (very) expensive. ta fbicháng cdngming She’s extremely intelligent. Note: There is however a group of adjectives which can be called ‘non-gradable’ in that they are not purely descriptive but define an ‘either–or’ quality or situation (e.g. huó ‘alive’, i.e. ‘not dead’; hbi ‘black’, i.e. not of any other colour, etc.). These adjectives, when used predicatively, require shì to link them to the topic and they are followed by the particle de: zhèi tiáo yú shì huó de This fish is alive. zhèi liàng chb shì hbi de This car is black. C
104
shì is negated by
bù:
jcntian bù shì xcngqc tian Today is not Sunday.
míngnián bù shì zhe nián Next year is not the year of the pig. zhè shì lschá | bù shì hóngchá This is green tea, not black tea. (lit. this is green tea, not red tea)
11 shì and yoˇu
nèi zhang zhudzi shì fang de | bù shì yuán de That table is square, not round. zhèi xib ddu bù shì wi de | shì lh tàitai de None of these are mine, they’re Mrs Li’s. Note 1: Notice that if the adverb ddu ‘both; all’ is also present, the positioning of the negator bù with reference to ddu may affect the meaning of the sentence: zhèi xib bù ddu shì Not all of these are wi de mine. zhèi xib ddu bù shì None of these are wi de mine.
Note 2: The twelve animals of the Chinese zodiac, which are often used to identify the year of one’s birth, come in the following order: ( ) (lfo)shj ‘rat’, niú ‘ox’, ( ) (lfo)hj ‘tiger’, ( ) tù(zi) mf ‘horse’, yáng ‘goat’, ‘rabbit’, lóng ‘dragon’, shé ‘snake’, ( ) hóu(zi) ‘monkey’, jc ‘rooster’, giu ‘dog’, zhe ‘pig’. D shì is also used as an intensifier to highlight the initiator, recipient, time, place, means, purpose, etc. of the action expressed in the verb. It is placed immediately before the word or phrase to be highlighted, which may mean that it can sometimes be placed at the very beginning of the sentence if the subject is to be emphasized: nh shì zfoshang xhzfo ma Do you take a bath in the morning? shì shéi zài qiao mén Who is it knocking at the door? ta míngtian shì zuò chuán qù She is going by boat tomorrow. wimen shì lái zhfo jcnglh We are coming to see the manager.
105
11
Note 1: As we can see in the last two examples, shì is placed immediately before the verb when the object is emphasized.
shì and yoˇu
One cannot say: *
*wimen lái zhfo shì jcnglh
Note 2: It is not unusual for speakers to include de at the end of the statement where lái is used to indicate immediate purpose (see the last example above): wimen shì lái zhfo jcnglh de We have come to see the manager. wnmen shì lái zhèr lsxíng de We are tourists here. (lit. We have come here to travel.) If the action to be emphasized took place in the past, used with de:
shì is always
ta shì zuótian Did he leave yesterday? ziu de ma wimen bù shì We did not come on foot. ziulù lái de Under such circumstances, to highlight the object, shì is placed before the verb while de is inserted between the verb and the object: wi xifo shíhou shì xué de zhdngwén I studied Chinese when I was little. wimen gangcái shì jiào de chfomiàn What we ordered just now was fried noodles. It is however not unusual to find native speakers express this similar notion by using an alternative structure, where the topic assumes the form of an attributive marked by de with the qualified noun understood and the comment uses shì to introduce the element to be highlighted: wi xifo shíhou xué de shì zhdngwén It was Chinese that I studied when I was little. 106
wimen gangcái jiào de shì chfomiàn It was fried noodles that we ordered just now.
E
yiu indicates either possession ‘to have’:
11
ta yiu yc gè diànnfo She’s got a computer. ta zhh yiu lifng gè érzi He only has two sons.
shì and yoˇu
or existence ‘there is/are’. A regular pattern is ‘location phrase + yiu + noun’, which normally translates into English as ‘There is/are (something/some things) (somewhere)’ (see Unit 2): chduti li yiu xìnzhh There is some writing paper in the drawer. caochfng shang yiu hgn dud yùndòngyuán There are a lot of athletes on the sportsfield. shù xià yiu yc zhc tùzi There is a hare under the tree. hú shang yiu yc qún yazi There is a flock of ducks on the lake. Note: The noun following (see Unit 2). F
yiu is negated by
yiu is always of indefinite reference
méi:
wi méi yiu diànnfo I haven’t got a computer. wezi li méi yiu rén There isn’t anybody in the room. chduti li zhh yiu xìnzhh | méi yiu xìnfbng There is only writing paper in the drawer, and no envelopes. Note: When yiu is negated, the noun object is not usually modified by a ‘numeral + measure word’ phrase unless the number is the central issue:
guìzi li zhh yiu yc jiàn máoyc | méi yiu lifng jiàn máoyc There is only one sweater in the wardrobe, not two. G shì may also be used to indicate existence like differs from yiu in two ways.
yiu, but it
107
11
(i)
shì and yoˇu
shì (but not yiu) may be preceded by quán or ddu ‘all; entirely’ to suggest that the location is occupied solely by one kind of being or thing: dì shang quán shì shuh The ground was covered with water. jib shang ddu shì rén The street was full of people.
(ii) while yiu focuses mainly on what exists, emphasize the location as well:
shì tends to
diànyhngyuàn duìmiàn yiu jh jia shangdiàn There are a few shops (amongst other things) opposite the cinema. fángzi hòumian shì gè càiyuán Behind the house is a vegetable garden.
Exercise 11.1 Translate the following sentences into Chinese, bearing in mind that shì may, or may not, have to be present: 1 2 3 4 5 6 7 8 9 10 11 12
She is my neighbour. My younger sister is beautiful. Yesterday was Tuesday. My car is red. This fish is alive. Our room is clean. That story is very interesting. These vegetables are fresh. This skirt isn’t too dirty. The concert was wonderful. All these clothes are old. Whose is that pair of glasses?
Exercise 11.2 Rewrite the Chinese sentences below in the negative to match the English: 108
1
xifo wáng yiu yc tiáo giu Xiao Wang hasn’t got a dog.
2 3 4 5 6 7 8 9 10
huayuán li yiu hgn dud huar There aren’t many flowers in the garden. tamen ddu shì ycngguó rén None of them is English. zhèi zhuàng fángzi shì ta de This house isn’t his. nèi bbi kafbi shì wi péngyou de That cup of coffee isn’t my friend’s. lóuxià yiu rén There’s no one downstairs. ta shì jcnglh She isn’t the manager. ta yiu lifng jiàn xíngli He doesn’t have two pieces of luggage. wi de tóngxué ddu shì zhdngguó rén Not all my classmates are Chinese. túshegufn hòumian shì diànyhngyuàn It isn’t the cinema behind the library.
11 shì and yoˇu
Exercise 11.3 Indicate which of the two Chinese translations for the English sentences below is correct in each case: 1 There is some writing paper in the drawer. chduti li shì xìnzhh chduti li yiu xìnzhh 2 The picture is beautiful. nèi fú huàr hgn mgi nèi fú huàr shì mgi de 3 This snake is alive. ( shé ‘snake’) zhèi tiáo shé shì huó zhèi tiáo shé shì huó de 4 I haven’t got a pair of gloves. wi méi yiu shiutào wi méi yiu yc shuang shiutào 5 He isn’t a manager. ta méi shì jcnglh ta bù shì jcnglh 6 There aren’t any rabbits under the tree. shù xià bù yiu tùzi shù xià méi yiu tùzi 7 Those trousers aren’t mine. nèi tiáo kùzi bù shì wi de nèi tiáo kùzi méi shì wi de
109
11
8 The bookshelf was filled with books. shejià shang ddu shì she shejià shang ddu yiu she
shì and yoˇu
Exercise 11.4 Translate the following sentences into Chinese: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
There are two red jumpers in the wardrobe. There is a large cooker in the kitchen. ( lúzi ‘cooker’) There are many books on the bookshelf. There are many students in the classroom. The swimming-pool is full of people. There isn’t a single chair in the room. There is nothing in the drawer. There are no flowers in the garden. There isn’t a telephone in the office. There is a flock of sheep at the foot of the hill. Opposite the restaurant is the cinema. There is quite a lot of cooked rice in the pot. There is only a little milk in the bottle. There are toys all over the floor. ( dìbfn ‘floor’) There is nobody in the house.
Exercise 11.5 Translate the sentences below into Chinese:
110
1 This is a bus ticket, not a cinema ticket. 2 That is a pair of mandarin ducks, not ordinary ducks. ( pjtdng ‘ordinary’) 3 Those are potatoes, not sweet potatoes. ( fanshj ‘sweet potato’) 4 These are bees, not flies. ( mìfbng ‘bee’) 5 This is petrol, not vegetable oil. ( càiyóu ‘vegetable oil’) 6 That is Mr Zhang, the manager, not Mr Li, the engineer. 7 There is only a bicycle outside, not a car. 8 There are pearls but no earrings in the box. ( hézi ‘box’) 9 There is only a map on the wall, not a picture. 10 I have a packet of cigarettes, but not a box of matches. ( bao ‘packet’) 11 There is a cooker but no fridge in the kitchen.
12 13 14 15
I have only got a knife, but not a pair of scissors. None of these is hers. Not all of those are good. Those are all bad/no good.
11 shì and yoˇu
Pattern and vocabulary drill 11.1 Translate the following into Chinese, using shì or de to highlight the italicized parts of the sentences:
...
shì . . .
Are you going to China this summer? Are you coming back to the UK next year? nh shì jcnnián xiàtian qù zhdngguó ma ( ) nh shì míngnián huí (lái) ycngguó ma 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
I am going to China in the autumn of next year. I am coming back to the UK the year after the next. I am not going by boat. I am going by plane. When are you going to China? Where are you going next year? Are you going to China tomorrow? It is my friend, not me. Did your friend leave yesterday? No, he left the day before yesterday. He went/left by plane. He will come back to the UK on Saturday. Who was it made by? Did she make it? She didn’t make it. He did.
Pattern and vocabulary drill 11.2 Translate the sentences below into Chinese. Notice that the noun in the first clause is replaced or represented by an attributive phrase or a demonstrative and measure in the second. Remember however that in Chinese human nouns or nouns that represent institutions are not usually omitted. The fried noodles you ordered are delicious, but the ones I ordered aren’t. nh jiào de chfomiàn hgn hfochc | wi jiào de bù hfochc
111
1 2 3 4 5 6 7 8 9 10
11 shì and yoˇu
112
The bottle of milk you bought is fresh, (but) the one I bought isn’t. This table is square (but) that one’s round. Her book is interesting, (but) mine is boring. Father’s car is blue, (but) mother’s is red. This shirt is mine, (but) whose is that one? Those trousers are long enough, (but) these aren’t. His friends are all very rich ( yiuqián), (but) mine aren’t. Your room is clean, (but) his isn’t clean enough. Mr Zhang’s horse is black, (but) Mrs Li’s is white. These apples are expensive, (but) those are cheap.
UNIT TWELVE Comparisons
A The standard way to express a comparison in Chinese is to use the word bh ‘to compare with’ in conjunction with an adjectival predicate. ‘X is better/larger, etc. than Y’ in English, for example, becomes ‘X + bh + Y + good/large, etc.’ in Chinese: zhèi gè bh nèi gè hfo This one is better than that one. zhèi gè xuéxiào bh nèi gè xuéxiaò dà This school is larger than that school. zhèi gè xiangzi bh nèi gè xiangzi zhòng This box is heavier than that box. As an adjective on its own in the predicative position implies a contrast in Chinese (see Unit 10), it therefore follows that bh comparisons require an adjective used by itself that does not have an adverbial modifier like hgn ‘very’, shífbn ‘extremely’, fbicháng ‘exceptionally’, etc. One cannot say, for example, zhèi gè bh nèi gè hgn hfo This one is better than that one. However, the adjective may be modified by degree adverbs like gèng and ( ) hái (yào) ‘even (more)’ or followed by degree complements like ycdifnr ‘slightly’, ycxib ‘a little’ and de dud or dud le ‘much’: (i) with degree adverbs: zhèi gè bh nèi gè gèng hfo This one is even better than that one.
113
12 Comparisons
( ) zhèi gè xuéxiào bh nèi gè (xuéxiào) gèng dà This school is even larger than that school. ( ) ( ) zhèi gè xiangzi bh nèi gè (xiangzi) haí (yào) zhòng This box is even heavier than that box. lifng jiàn dàyc ddu hgn cháng | hóng dàyc bh lán dàyc gèng cháng Both coats are very long, but the red one is even longer than the blue one. ( ) ( ) zhèi zhing màozi hgn guì | nèi zhing màozi (bh zhèi zhing màozi) hái (yào) guì A hat like this is very expensive, but one like that is even more expensive (than this one). (ii) with degree complements: zhèi gè bh nèi gè hfo dud le This one’s much better than that one. ( ) zhèi zhuàng fángzi bh nèi zhuàng (fángzi) dà ycdifnr This house is slightly larger than that house. ( ) zhèi jiàn xíngli bh nà jiàn (xíngli) zhòng de dud This case is much heavier than that one. (lit. This piece of luggage is much heavier than that piece.) shànghfi bh bgijcng nufn ycxib Shanghai is a bit warmer than Beijing. Sometimes a degree complement registers an actual amount or extent: wi bh bàba fi yc cùn I’m an inch shorter than my father. gbge bh dìdi zhòng lifng gdngjcn (The) elder brother is two kilos heavier than the younger brother.
114
B Negative comparison is expressed by either placing the negator bù ‘not’ directly before bh or using the pattern: ‘X + ( ) méi(yiu)
+Y+ nàme/ zhème ‘so’ + adjective’. The difference between the two is that the former emphasizes the fact that A is no better (etc.) than B, whereas the latter, the fact that A is worse (etc.) than B:
12 Comparisons
zhèi gè bù bh nèi gè hfo This one isn’t better than that one. zhèi gè xuéxiào bù bh nèi gè xuéxiào dà This school isn’t larger than that school. zhèi gè xiangzi bù bh nèi gè xiangzi zhòng This box isn’t heavier than that box. or ( ) / wi méi(yiu) nh nàme/zhème cdngming I’m not as intelligent as you. ( ) / zhèi gè méi(yiu) nèi gè nàme/zhème hfo This (one) is not as good as that (one). ( ) wi jigjie méi(yiu) wi zhème gao My elder sister isn’t as tall as I am. ( ) lfoshj méi(yiu) sdngshj nàme dà Mice aren’t as big as squirrels. The latter pattern can occur in the positive with a question is being asked:
yiu, usually when
nh jigjie yiu nh zhème gao ma Is your elder sister as tall as you are? lfoshj yiu sdngshj nàme dà ma Are mice as big as squirrels? C Similarity is conveyed by ycyàng ‘the same’ (lit. ‘one type’), in conjunction with the word gbn (or hé, tóng, yj) ‘with; and’. ycyàng itself functions as an adjectival predicative: nà lifng gè ycyàng wi gbn nh ycyàng zhèi gè gbn nèi gè ycyàng
Those two are the same. I’m the same as you. This (one) is the same as that (one).
115
12 Comparisons
ycyàng is also followed by an adjective to express more specific similarity, in the pattern: ‘X + gbn ( hé, tóng, yj) + Y + ycyàng + adjective’: wi gbn nh ycyàng dà I’m as old as you. zhèi gè gbn nèi gè ycyàng hfo This (one) is as good as that (one). xifo wú gbn xifo hóng ycyàng zhòng Xiao Wu and Xiao Hong are the same weight./Xiao Wu weighs as much as Xiao Hong. mama hé bàba ycyàng gao Mother and Father are the same height./Mother is as tall as Father. bù comes before ycyàng, Note: In expressing dissimilarity, e.g. xifo wú gbn xifo hóng bù ycyàng dà therefore means ‘Xiao Wu and Xiao Hong are not the same age.’ It does not mean ‘Xiao Wu is not as young (or old) as Xiao Hong’ (see section B above). D So far, the comparisons discussed have related to an entity’s attributes (expressed as adjectival predicates). If the comparison involves an action, de is placed immediately after the verb that expresses the action whilst the comparative formats discussed above, positive or negative, similarity or otherwise, come either before or after the ‘verb + de’ phrase: wi bh nh zuò de hfo wi zuò de bh nh hfo I did it better than you. wi gbn nh zuò de ycyàng hfo wi zuò de gbn nh ycyàng hfo I did it as well as you. wi bù bh nh zuò de hfo wi zuò de bù bh nh hfo I did not do it better than you.
116
wi méiyiu nh zuò de hfo wi zuò de méiyiu nh hfo I did it worse than you.
12 Comparisons
wi bù gbn nh zuò de ycyàng hfo wi zuò de bù gbn nh ycyàng hfo I did not do it as well as you. Here are some more examples: ( ) yc hào yùndòngyuán pfo de bh èr hào (yùndòngyuán) kuài Athlete No. 1 ran faster than athlete No. 2. ( ) yc hào yùndòngyuán pfo de gbn èr hào (yùndòngyuán) ycyàng kuài Athlete No. 1 ran as fast as athlete No. 2. ta chc de bh wi dud He ate more than I did./He eats more than I do. ta chc de gbn wi ycyàng dud He ate as much as I did./He eats as much as I do. If the action verb has an object, the verb is repeated with the verb-object expression in either of the above patterns:
de after
ta tiàowj tiào de bh wi hfo ta tiàowj bh wi tiào de hfo She dances better than I do./She is a better dancer than I am. ta páshan pá de gbn wi ycyàng kuài ta páshan gbn wi pà de ycyàng kuài He climbs a hill as fast as I do. E
The superlative degree is expressed simply by placing the adverb zuì before the adjective: zhè san zhing huar | bái hua zuì xiang Of these three flowers, the white one smells the nicest. (lit. is the most fragrant) ban shang èr shí jh gè xuésheng | xifo zhang zuì qínfèn Out of the twenty or so pupils in the class, Xiao Zhang is the most diligent. wj yiu sì gè háizi | dì èr gè háizi kfo de zuì hfo I have four children. The second child did best in the examination.
117
12 Comparisons
F Increasing or intensifying comparison in the pattern ‘more . . . and more . . .’ follows the pattern: ‘ yuè lái yuè + adjective’: / báitian/hbiyè yuè lái yùe cháng The days/nights are growing longer and longer. / tianqì yuè lái yuè rè/lgng The weather is getting hotter and hotter/colder and colder. wimen de shbnghuó yuè lái yuè hfo Our life is getting better and better. The ‘ (i) ‘
yuè . . .
yuè . . . ’ pattern is in fact used in a number of ways:
yuè + adjective +
yuè + adjective’:
yuè dud yuè hfo The more the better (merrier). jiang yuè lfo yuè là The older ginger gets the hotter it is (i.e. old ginger gets hotter). (ii) ‘
yuè + verb +
yuè + adjective’:
ta yuè tiào yuè gao She jumped higher and higher. ta yuè pfo yuè kuài He ran faster and faster. (iii) ‘
yuè + verb +
yuè + verb’:
ta yuè dj yuè she | yuè she yuè dj The more he gambled the more money he lost, and the more money he lost the more he gambled. ta yuè shud yuè qì The more she spoke, the angrier she became. (iv) where meaning allows, each ‘ its own subject:
yuè + verb’ construction may have
ta yuè shud wi yuè qì The more she spoke, the angrier I became. 118
kafbi yuè tián wi yuè xhhuan The sweeter the coffee, the better I like it.
G Finally, it is not uncommon to make comparisons using adverbs such as / zfo/xian ‘early’ or / wfn/chí ‘late’ and the usual construction is:
12 Comparisons
/ ta bh wi xian/chí dào He arrived earlier/later than I did. / ta bh wi zfo/wfn qhchuáng He gets up earlier/later than I do. If a degree complement is used, it usually comes after the verb if the verb is monosyllabic: ( ) ta bh wi zfo lái bàn (gè) xifoshí He came half an hour earlier than I did. However, if the verb is disyllabic, the degree complement is more likely to come after the adverb: ( ) ta bh wi zfo bàn (gè) xifoshí qhchuáng He got up half an hour earlier than I did. In fact, the longer the verbal expression, the more likely it is that the degree complement will come after the adverb: ( ) ta bh wi zfo bàn (gè) xifoshí dàodá mùdìdì He reached the destination half an hour earlier than I did.
Exercise 12.1 Using the words supplied, construct Chinese sentences expressing comparison or similarity and then translate them into English. wi
nh
dà
gbn
ycyàng
wi gbn nh ycyàng dà You and I are the same age. 1 fbijc plane
huichb train
bh
kuài fast
ffguó France
mgiguó America
bù ycyàng
dà
2 gbn
119
12 Comparisons
3 ddngtian winter
chentian spring
bh
nufnhuo warm
mao cat
lfohj tiger
de dud a lot
xifo
bh
a’grbbisc shan
gao
nàme
méiyiu
The Alps
xhmflayf shan The Himalayas
zhdngguó de rénkiu China’s population
éguó de rénkiu Russia’s population
dud
chángchéng The Great Wall
jcnzìtf The Pyramids
yiumíng well-known
hé
ycyàng
xifo lh Xiao Li
lfo zhang Lao Zhang
nàme
qínfèn industrious
méiyiu
chfofàn fried rice
chfomiàn fried noodles
hfochc delicious
de dud a lot
bh
wi de xíngli my luggage
nh de xíngli your luggage
lifng gdngjcn zhòng two kilos heavy
4
5
high
6 bh
many
7
8
9
10 bh
Exercise 12.2 Rewrite the following negative comparison sentences using bh without changing the meaning, and then translate them into English. dìdi méiyiu wi zhème gao My younger brother isn’t as tall as I am. wi bh dìdi gao I am taller than my younger brother. 1
shayú méiyiu jcngyú nàme dà Sharks are not as big as whales.
2
120
zhàoxiàngjc méiyiu shèxiàngjc nàme guì Cameras aren’t as expensive as video cameras. 3 táozi méiyiu pínggui nàme yìng Peaches are not as hard as apples.
4 zhèi gè chéngshì méiyiu nèi gè chéngshì nàme mgilì This city isn’t as beautiful as that one.
12 Comparisons
5 ycngguó de chentian méiyiu xiàtian zhème rè The spring isn’t as hot as the summer in Britain. 6 ffyj méiyiu déyj zhème nán French is not as difficult as German. 7 nh méiyiu wi nàme zhòng You are not as heavy as me. 8 huánghé méiyiu chángjiang nàme cháng The Yellow River is not as long as the Yangtze River. 9 ta de jianbfng méiyiu nh de nàme kuan ( kuan ‘broad’) His shoulders are not as broad as yours. 10 zhèi shiu gb méiyiu nèi shiu gb nàme hfotcng This song is not as nice as that one.
Exercise 12.3 Complete the Chinese sentences below with either: ‘(adjective) + ycxib/ ycdifnr/ de dud’ or ‘(adjective) + numeral + measure word’, to match the English translations (note: ycdifnr is represented as two spaces ): 1 nèi gè chúshc bh wi That cook is much fatter than I am.
(
pàng ‘fat’)
2 mao de wgiba bh tùzi de wgiba A cat’s tail is much longer than a rabbit’s tail. 3 ( ) qiúxié bh píxié Sports shoes are slightly cheaper than leather shoes. 4 mèimei bh jigjie ( shòu ‘thin’) The younger sister is slightly thinner than the older sister. 5 yéye bh nfinai Grandma is two years younger than Grandpa. 6 zhèi jiàn ycfu bh nèi jiàn ycfu This dress is two pounds more expensive than that one.
121
12 Comparisons
7 zhèi gè gùshi bh nèi gè gùshi This story is much more interesting than that one. 8 zhèi zhuàng fangzi bh nèi zhuàng This house is slightly prettier than that one. 9 nèi xib xiangjiao bh zhèi xib Those bananas are much fresher than these. 10 wi de niúzfikù bh nh de My jeans are a little cleaner than yours.
Exercise 12.4 Complete these sentences with either
gèng/
hái yào or
zuì:
1 zhème dud de xiézi | hbi de nèi shuang piàoliang Of all these shoes that black pair is the most beautiful. 2 zhèi xib she ddu hgn yiu yìsi | nèi bgn yiu yìsi All these books are interesting, but that book is even more interesting. 3 nèi san gè xcgua ddu hgn tián | zhèi gè tián ycdifnr Those three water melons are sweet, but this one is even sweeter. 4 dào shìzhdngxcn qù | zhèi tiáo lù jìn This is the quickest way to the city centre. 5 wi qù guo de chgngshì zhdng | bùlagé mgilì Of all the cities I have been to, Prague is the most beautiful. 6 san niánjí wj shí gè xuésheng | ta qínfèn Amongst the fifty students of the Third Year, she is the most industrious. 7 zhèi xib cài ddu hgn hfochc | kgshì nèi gè cài hfochc ( ‘dish (of food)’) These dishes are tasty, but that dish is even more tasty. 122
cài
8 nèi shiu gb hgn hfotcng | kgshì zhèi shiu gb That song is nice, but this song is even nicer.
hfotcng
12 Comparisons
9 zhèi zhing hua hgn xiang | nèi zhing hua xiang This kind of flower is fragrant; but that kind is even more fragrant. 10 èr hào yùndòngyuán pfo de bh yc hào yùndòngyuán kuài Athlete No. 2 runs even faster than athlete No. 1.
Exercise 12.5 Translate the sentences below into Chinese (more than one version of the translation may be possible): 1 He came earlier than others. ( zfo ‘early’) ( qíta rén ‘others/other people’) 2 She walks more slowly than he does. ( ziulù ‘to walk’) 3 Yesterday he went to bed later than I did. ( wfn ‘late’) 4 My wife is a better driver than I am. ( qczi ‘wife’) 5 One of my coursemates sings better than I do. ( chànggb ‘sing’) 6 My husband is a better tennis player than I am. ( zhàngfu ‘husband’; df wfngqiú ‘to play tennis’) 7 My elder brother is an inch taller than I am. ( gao ‘tall’) 8 (The) younger sister is a half kilo lighter than the elder sister. ( qcng ‘light’) 9 Is a squirrel as big as a mouse? fángzi ‘house’) 10 This house isn’t as pretty as that one. (
Exercise 12.6 Translate the following sentences into Chinese, using the patterns for intensifying comparison: 1 I am growing more and more hungry. 2 The chef was getting fatter and fatter. ( chúshc ‘chef’) 3 That horse runs more and more slowly in races. ( zài bhsài zhdng ‘in races’) 4 The soccer match became more and more exciting. 5 The road gets wider and wider. 123
12 Comparisons
6 Grandfather’s illness was growing more and more serious. ( yánzhòng ‘serious’) 7 The more he drinks the more drunk he becomes. 8 The quicker the better. 9 The more he sings, the unhappier I become. 10 The more peppery the food, the more I like it.
Pattern and vocabulary drill 12.1 Reformulate the following Chinese sentences as two different negative comparisons: zhèi píng nijnfi bh nèi píng xcnxian This bottle of milk is fresher than that one. a zhèi píng nijnfi bù bh nèi píng xcnxian This bottle of milk is no fresher than that one. b nèi píng nijnfi méiyiu zhèi píng xcnxian That bottle of milk is less fresh than this one. 1
2
3 4 5
6 7 8 9 124
( ) zhèi zhang zhudzi bh nèi zhang (zhudzi) ganjìng This table is cleaner than that one. ( ) zhèi gè fángjian bh nèi gè (fángjian) zhgngqí This room is tidier than that one. zhèi gè rén bh nèi gè rén lfoshi This person is more honest than that person. ( ) zhèi gè gùshi bh nèi gè (gùshi) yiuqù This story is more interesting than that one. ( ) zhèi chfng bhsài bh nèi chfng (bhsài) jcngcfi This match is more exciting than that one. ( ) zhèi tiáo qúnzi bh nèi tiáo (qúnzi) cháng This skirt is longer than that one. ( ) zhèi shuang xiézi bh nèi shuang (xiézi) xifo This pair of shoes is smaller than that pair. ( ) zhèi jiàn ycfu bh nèi jiàn (ycfu) zang This shirt/jacket/etc. is dirtier than that one. ( ) zhèi liàng chb bh nèi liàng (chb) piàoliang This car is better looking than that one.
10
11
12
13 14 15 16 17 18
19
20
( ) zhèi zuò lóufáng bh nèi zuò (lóufáng) gjlfo This building is more ancient than that one. ( ) zhèi xib shecài bh nèi xib (shecài) xcnxian These vegetables are fresher than those. ( ) zhèi jia shangdiàn bh nèi jia (shangdiàn) dà This shop is bigger than that one. ( ) zhèi bbi kafbi bh nèi bbi (kafbi) tián This cup of coffee is sweeter than that one. zhèi gè háizi bh nèi gè (háizi) cdngming This child is more intelligent than that child. ( ) zhèi jiàn xíngli bh nèi jiàn (xíngli) zhòng This piece of luggage is heavier than that one. ( ) zhèr de tianqì bh nàr de (tianqì) hfo The weather here is better than the weather there. ( ) zhèi kuài jiang bh nèi kuài (jiang) là This piece of ginger is hotter than that one. zhèi gè yùndòngyuán bh nèi gè yùndòngyuán gao This athlete is taller than that athlete. ( ) zhèi zhing huar bh nèi zhing (huar) xiang This flower smells sweeter than that one. qùnián ddngtian bh jcnnián ddngtian lgng Last year’s winter was colder than this year’s winter.
12 Comparisons
Note: In comparisons, positive or negative, if the second item is similar to the first, it may often be omitted for the sake of brevity; but it is less likely to be omitted if it refers to people rather than things or if misunderstanding might occur.
Pattern and vocabulary drill 12.2 Translate the sentences below into Chinese, adding a degree complement in each case as indicated: I am two centimetres taller than my younger brother. ( gdngfbn ‘two centimetres’) wi bh dìdi gao lifng gdngfbn
lifng 125
12 Comparisons
126
1 I am heavier than my younger brother. ( wj gdngjcn ‘five kilograms’) 2 My friend is shorter than me. ( san cùn ‘three inches’) 3 Your luggage is heavier than mine. ( sì gdngjcn ‘four kilograms’) 4 Today is warmer than yesterday. ( lifng dù ‘two degrees’) 5 Last winter was colder than this one. ( lifng | san dù ‘two to three degrees’) 6 This road is broader than that one. ( lifng gdngchh ‘two metres’) 7 His trousers are longer than yours. ( yc | lifng cùn ‘one to two inches’) 8 Your camera is more expensive than mine. ( yc bfi kuài qián ‘one hundred yuan’) 9 Your watch ( bifo) is faster than mine. ( shí fbn zhdng ‘ten minutes’) 10 This journey ( lùchéng) is farther than that one. ( èr shí gdnglh zuiyòu ‘twenty kilometers or so’) 11 I got up earlier than he did. ( yc gè zhdngtóu ‘one hour’) 12 He graduated later than I did. ( yc nián ‘a year’) 13 They set out earlier than we did. ( lifng tian ‘two days’) 14 She came later than I did. ( ( ) bàn (gè) xifoshí ‘half an hour’) 15 The train arrived earlier than the bus. ( wj fbn zhdng ‘five minutes’)
UNIT THIRTEEN Verbs and location expressions
A A number of the most common words that indicate place may be formed by linking the root words lh, wài, shàng, xià, qián and hòu with bian, mian or tou: lhbian wàibian shàngbian xiàbian qiánbian hòubian
( ( ( ( ( (
Others are linked with zuibian yòubian ddngbian nánbian xcbian bgibian
lhmian, wàimian, shàngmian, xiàmian, qiánmian, hòumian, bian or
( ( ( ( ( (
lhtou) inside wàitou) outside shàngtou) above xiàtou) below qiántou) in front hòutou) behind
mian:
zuimiàn) yòumiàn) ddngmiàn) nánmiàn) xcmiàn) bgimiàn)
left right east south west north
Others have only one form: pángbian duìmiàn zhdngjian
at/by the side of opposite in the middle/between
Note: A colloquial variant of xiàmian is dhxia.
xiàbian/
xiàtou/
B These place words may all be used after nouns to form more complex location expressions: 127
13 Verbs and location expressions
zhudzi shàngbian xuéxiào qiánmian guìzi lhtou fángzi wàimian yóuyingchí pángbian lhtáng duìmiàn dàtcng zhdngjian kètcng hé wòshì zhdngjian wi jia nánmiàn shànghfi bgibian
on the table in front of the school in(side) the cupboard outside the house next to/by the side of the swimming-pool opposite the auditorium in the centre of the hall between the sitting-room and the bedroom (to the) south of my home (to the) north of Shanghai
There are a few other words which convey less specific locations: /
sìzhdu/zhduwéi fùjìn nàr
around near at the home of/where someone is
dàxué fùjìn lh xiansheng nàr
near the university at Mr Li’s place or over there where Mr Li is on all sides of/around the garden
For example,
huayuán sìzhdu
C For some of these disyllabic place words that are often suffixed to nouns and which can be called postpositions (comparable to English prepositions), there are a number of monosyllabic variants, which are in fact the root or stem of these disyllabic forms (as we have seen in A above): li wài shang xià qián hòu zhdng páng/
128
in/inside outside on/above/over under/below/beneath in front of behind in/among/between bian by/beside
li and shang are the most widely used of these monosyllabic postpositions, but they all regularly occur:
yhzi shang fángzi li chéng wài mén qián shù xià péngyou zhdng lù bian bèi hòu
on the chair in the house outside the city in front of the door under the tree amongst friends by the side of the road behind someone’s back
13 Verbs and location expressions
Note: As we can see from the last example, these monosyllabic postpositions are often used in contexts where idiom rather than the strict concept of location prevails: xcn zhdng huì shang lhlùn shang
in one’s heart at the meeting in theory
Also Chinese postpositions in actual use do not always match their English prepositional counterparts: yàoshi zài mén shang The key is in the door. she shang méi zhème It doesn’t say so shud in the book. D Location expressions are used in the following positions in a Chinese sentence: (i) before the verb, in conjunction with words such as zài ‘in; at’, dào ‘to’, cóng ‘from’, etc., to indicate location, destination or direction: tamen zài qiáng shang xig biaoyj They are writing slogans on the wall. háizimen zài cfodì shang wánr The children are playing on the grass. wimen dào chéng li qù mfi she We went to town to buy some books. qhng zài lhmian dgng ta Please wait for him inside. ta cóng hézi li ná che yc zhc qianbh lái She took a pencil out of the box.
129
13 Verbs and location expressions
tamen zài xuéxiào pángbian gài yc zuò xcn fángzi They are putting up a new building next to the school. Note: Verbs that follow the location expressions usually have more than one syllable (see Section F). (ii) after a verb which denotes an action that will naturally end up in a location: yéye zuò zài shafa shang Grandpa is sitting on the sofa. ( ) ta dai zài jia li She stayed at home. tamen ddu zhù zài chéng wài All of them live in the outskirts. (lit. out of the town) hgn dud rén tfng zài cfodì shang shài tàiyang There are many people lying on the grass, sunbathing. qhng zuò zài qiánmian Please sit in front. bié rbng dào chuang wài qù Don’t throw it out of the window. Note: Verbs which do not denote actions that will naturally end up in a location cannot, of course, follow the pattern discussed in (ii), therefore One cannot say: tamen xuéxí zài túshegufn * (lit. They are studying at the library.) (iii) at the beginning of a sentence to indicate the location of something or someone (see Unit 11): dòngwùyuán yòubian shì zhíwùyuán To the right of the zoo is the botanical garden.
130
zhàntái shang yiu hgn dud rén There are a lot of people on the (station) platform.
wàibian méi yiu yhzi There are no chairs outside. E The postposition li (or lhbian/ lhtou/ used after geographical names. For example,
lhmian) is not
13 Verbs and location expressions
tamen zài zhdngguó lsyóu They are on a tour in China. bgijcng yiu hgn dud jùchfng There are a lot of theatres in Beijing. One cannot say: * *
tamen zài zhdngguó li lsyóu bgijcng li yiu hgn dud jùchfng
On the other hand syllables:
li is optional after a location noun of two
( ) ta zài huayuán (li) zhòng hua She is planting flowers in the garden. ( ) dìdi cóng xuéxiào (li) che lái (My) younger brother came out of the school. ( ) jigjie hé ta de péngyou zài fàngufn (li) chcfàn (My) elder sister and her friends are having a meal in a restaurant. However, it is less likely for the omission to take place if the location noun is of one syllable. For example: mama zài chéng li mfi ddngxi Mother is shopping in town. but not: *
mama zài chéng mfi ddngxi
unless, of course, the noun refers to a location very familiar to the person: ( )
wi zài jia (li) xuéxí ta zài xiào zhíban
I was studying at home. He is on duty at school.
131
13 Verbs and location expressions
If the location noun has three syllables, wi zài yuèlfnshì kàn bào
li ‘in’ is generally not used: I am reading newspapers in the reading room.
wi zài huichbzhàn I’ll wait for you at the dgng nh railway station. F Where location expressions with zài come before the verb (see examples under D (i) above), the verb that follows usually consists of more than one syllable: ta zài jiàoshì li xuéxí (a disyllabic verb) He is studying in the classroom. D bìngrén zài chuáng shang tfng zhe (a monosyllabic verb with an aspect marker) The patient is lying in bed. yiu hgn dud rén zài zhàntái shang dgng chb (a verb with an object) There are a lot of people on the platform waiting for the train. One cannot say: * *
ta zài jiàoshì li xué (lit. He is studying in the classroom.) bìngrén zài chuáng (lit. The patient is shang tfng lying in bed.)
Note 1: The aspect marker that changes a monosyllabic verb into a two-syllabled verb phrase, as we can see from the second example above, is usually D zhe, which indicates a continuous action or state and gives the sentence a descriptive nature.
Note 2: The exception to this rule is that monosyllabic verbs may be used in questions (and their associated answers) and in imperatives: nh zài nfr dgng
132
Where are you going to wait? wi zài huichbzhàn dgng I’ll wait at the railway station. nh zài zhèr zuò You sit here!
Exercise 13.1 Complete the sentences below by adding correct postpositions: 1
fbng hgn dà | lù xíngrén hgn shfo ( xíngrén ‘pedestrian’) The wind was strong and there were very few people on the street. D jc zài kfoxiang 2 kfo zhe The chicken was cooking in the oven. D 3 ( ) ta zhàn zài mén ( ) kàn zhe bàba lí qù She stood by the door and watched her father leave. 4 chuang chuán lái qìchb de lfba shbng ( lfba ‘horn (of a car)’) The sound of a car horn came from outside./A car horn sounded outside the window. 5 lfoshj dui zài chuáng ( dui ‘to hide’) The mouse hid under the bed. 6 chbzhàn zài xuéxiào The station is near the school. 7 wimen de zuòyè bgnzi zài lfoshc Our course-work books are with the teacher. 8 ycngguó ddu shì hfi Britain is surrounded by sea. 9 rìbgn zài zhdngguó Japan is east of China. 10 yínháng shì xié diàn | shì fúzhuang diàn On the left of the bank is a shoe shop and on the right, a clothes shop. 11 cèsui zài diàntc The toilet is next to the lift. 12 ycngjílì hfixiá zài ycngguó hé ffguó The English Channel lies between England and France. 13 ( ) wàzi hé shiutào ddu fàng zài guìzi ( ) ( fàng ‘put; keep’) Socks and gloves are all kept in the wardrobe. 14 bcngxiang zài xhycjc The fridge is on the left of the washing-machine.
13 Verbs and location expressions
133
13 Verbs and location expressions
15 bìngrén zuò zài ycshbng hé hùshi ( ycshbng ‘doctor: either physician or surgeon’) The patient was sitting between the doctor and the nurse. 16 dìtú guà zài hbibfn The map is hanging on the right-hand side of the blackboard. 17 bówùgufn zài yínháng ( bówùgufn ‘museum’) The museum is behind the bank. 18 yc qún rén zhàn zài dàlóu A crowd of people were standing all around the building.
Exercise 13.2 Translate the following phrases into Chinese. In some cases there may be two possible versions: 1 2 3 4 5 6 7 8 9 10
at the university at the bus-stop in the wardrobe in the north of the city in a box in bed in the middle of the room at the foot of the mountain on the bus under a tree
11 12 13 14 15 16 17 18 19 20
next to Mother above the swimming-pool in front of the library behind the house by the river on the table near the park around the child at my grandpa’s house in the west
Exercise 13.3 Decide which of the following sentences is incorrect and make corrections where necessary, paying special attention to the use of appropriate postpositions: 1
134
bàozhh zài zhudzi The newspaper is on the table. 2 wezi li tamen zài kaihuì They are having a meeting in the room. tàiwùshì hé shì ycngguó li yiumíng 3 de hé The Thames is a famous river in Britain.
4
5 6 7 8 9 10 11 12 13 14
ycshbng zài bìngrén de chuáng zhàn le ychuìr | méiyiu shud huà The doctor stood by the patient’s bed for a while without saying a word. mèimei zài túshegufn kàn she My younger sister was reading in the library. D yéye zài chuáng shang tfng zhe Grandpa was lying in bed. nh de yàoshi zài mén li Your key is in the door. sheshu gdngzuò zài lúnden My uncle works in London. ta zài mén qián zhàn She was standing in front of the house. (lit. in front of the door) nfinai zuò zài shafa shang Grandmother is sitting on the sofa. jcnyú yóu zài shuhchí li The goldfish are swimming in the pool. diànyhngyuàn zài xiédiàn zui The cinema is to the left of the shoe shop. bàozhh li yiu bù shfo gufnggào There are quite a few advertisements in the newspaper. tian li méi yiu yún There are no clouds in the sky.
13 Verbs and location expressions
Exercise 13.4 Six people have rooms in a block of flats. The diagram shows where they live in relation to one another. Complete these sentences with the words in the list. (Each word may only be used once): zuibian zhdngjian WEST
A D
lóuxià ddngmiàn B E
C (upstairs) F (downstairs)
1 B A C B zhù zài | zhù zài A hé C 2 E D F | zhù zài F 3 F C | zhù zài C
xiàmian lóushàng EAST
E zhù zài D F zhù zài 135
13 Verbs and location expressions
Exercise 13.5 Tick the correct Chinese translation(s) for each of the English sentences below, paying particular attention to the positioning of the location phrase: 1 The beef is cooking in the pot. ( niúròu ‘beef’) D niúròu zài gud li zhj zhe D niúròu zài gud zhj zhe niúròu zhj zài gud li 2 A friend of mine works in a hospital. wi de yc gè péngyou zài yc jia ycyuàn gdngzuò wi de yc gè péngyou gdngzuò zài yc jia ycyuàn wi de yc gè péngyou zài yc jia ycyuàn li gdngzuò 3 We live in Paris. wimen zhù zài balí wimen zhù zài balí li wimen zài balí zhù 4 She is waiting for you at the museum. ta zài bówùgufn dgng nh ta dgng nh zài bówùgufn ta zài bówùgufn li dgng nh 5 A flock of sheep is feeding at the foot of the hill. yiu yc qún yáng zài shanjifo xià chc cfo yiu yc qún yáng chc cfo zài shanjifo xià 6 My uncle is sunbathing by the sea. wi sheshu zài hfi bian shài tàiyang wi sheshu shài tàiyang zài hfi bian
Pattern and vocabulary drill 13.1 Put the given subject, location, and verb phrase together into a sentence, using first zài and then ... dào . . . qù (following the models given below), and translate the finished sentences into English: a 136
jigjie zài cfodì shang shài tàiyang Sister is sunbathing on the grass.
b
1 2 3 4 5 6 7 8
9
10
11
12
13
14
15
jigjie dào cfodì shang qù shài tàiyang Sister went sunbathing on the grass.
dìdi younger brother shafa shang on the sofa shuìjiào sleep yéye grandpa gdngyuán li in the park df tàijíquán practise T’ai Chi bàba father hé bian by the river diào yú go fishing/angling mama mother chéng li in town mfi cài buy food nfinai grandma péngyou jia a friend’s place df májiàng play mah-jong mèimei younger sister xuéxiào li at school xué chànggb learn singing/take singing lessons gbge elder brother túshegufn library kàn she do some reading bóbo father’s elder brother (paternal uncle) bówùgufn museum gdngzuò work sheshu father’s younger brother (paternal uncle) càiyuán li in the vegetable garden zhòng cài plant vegetables gemj father’s elder sister (paternal aunt) huayuán li in the garden zhòng hua plant flowers yímj mother’s elder/younger sister (maternal aunt) ycyuàn in the hospital kànbìng see a doctor jiùjiu mother’s elder/younger brother (maternal uncle) caochfng shang on the sports ground pfobù go jogging bóbo hé bómj father’s elder brother and his wife (paternal uncle and aunt) balí Paris dùjià spend their holidays gemj hé gezhàng father’s elder sister and her husband (paternal uncle and aunt) bgijcng Beijing lsxíng on a tour yímj hé yízhàng mother’s elder/younger sister and her husband (maternal aunt and uncle) lúnden London kàn qiúsài watch a football/tennis/etc. match
13 Verbs and location expressions
137
13 Verbs and location expressions
16
17
18
19
20
21
22
gbge hé wi my elder brother and I diànyhngyuàn cinema kàn diànyhng see a film/movie wi hé dìdi my younger brother and I jia li at home kàn diànshì watch television (Please note that only one version is possible here.) gbge hé ta de ns péngyou elder brother and his girlfriend kafbigufn coffee bar hb kafbi drink coffee jigjie hé ta de nán péngyou elder sister and her boyfriend yc jia shangdiàn li in a shop mfi ycfu buy clothes (D) jiùmj dài (zhe) wi mother’s elder/younger brother’s wife (maternal aunt) taking me with her wàimàidiàn a Chinese/etc. take-away mfi wàimài buy take-away food (D) jiùjiu dài (zhe) wi dìdi mother’s elder/younger brother (maternal uncle) taking my younger brother with him shatan shang on the beach qí mf ride on horseback/ride horses, go horse riding (D) sheshu dài (zhe) wi gbge father’s younger brother (paternal uncle) taking my elder brother with him jib shang in the street qí zìxíngchb cycle, ride bicycles
Pattern and vocabulary drill 13.2 Translate into Chinese: 1 2 3 4 5 6 7 8 9 10 138
Inside is better than outside. I’ll wait for you inside the cinema. There is no one upstairs. There’s someone behind you. Is there a public toilet in here? In the photograph, my father is sitting on the left, my mother is sitting on the right and I am standing between them. Where do you live in China? Please park your car on the road in front of the library. Don’t sit on that chair. His money is in a box under the bed.
UNIT FOURTEEN Verbs and time expressions
A Expressions which indicate the time at which something happens are generally placed before the verb. They have an important relationship with the verb, which in Chinese does not inflect or change its form to indicate tense (see also Unit 15). They therefore set the time context for the action of the verb. The following examples illustrate this: wimen míngtian qù sànbù We’ll go for a walk tomorrow. wimen zuótian qù sànbù We went for a walk yesterday. ( ) wimen mgi tian (ddu) qù sànbù We go for a walk every day. We can see from the above that the verbal phrase qù sànbù ‘go for a walk’ remains unchanged in each case though the English translations differ to convey tense. Note: A time expression may also be placed before the subject at the beginning of the sentence, where it tends to have a slightly more emphatic meaning: míngtian wimen qù sànbù We are going for a walk tomorrow. ( ) xiàtian wimen mgi tian (ddu) qù sànbù We go for a walk every day in the summer. An unmarked verb in Chinese without a preceding time expression usually indicates either habit or intention: wi ziulù shàngban wimen qù sànbù
I go to work on foot. We are going for a walk.
(habit) (intention)
139
14 Verbs and time expressions
B Time expressions may take a number of different forms from the simple, as in the examples in A above, to the more complex (see also Unit 8). Other examples of simple time expressions are: xiànzài yh qián yh hòu guòqù jianglái yuèche yuèdh zhdumò qián jh nián guò jh tian shàng gè shìjì yiu yc tian
now/nowadays previously afterwards in the past in the future at the beginning of the month at the end of the month at the weekend over/in the past few years in a few days’ time in the last century one day
tamen zhdumò qù hfi bian dùjià They are going on holiday by the sea at the weekend. wi de dà érzi xiànzài zài yóujú gdngzuò My eldest son is working at the post office now. guò jh tian wi de fùmj lái zhèr tànwàng wimen In a few days my parents will come here to visit us. yiu yc tian ta lái wi jia kàn wi One day he came to my place to see me. Note: When both time and location expressions are present in a sentence, the time expression always precedes the location expression. Other more complex phrases indicating before, after and during an action or (period of) time are formed by putting one of the following at the end of the time or verb phrase: . . . ( / ) . . . (yh/zhc) qián ‘ago/ before’; . . . ( / ) . . . (yh/zhc) hòu ‘later/after’; . . . ( ) ( ) . . . (de) shí(hou) ‘when . . . /while . . .’; and . . . ( ) (zhc) zhdng ‘during’: san gè xcngqc yh qián huí jia zhc qián lifng gè yuè qián 140
three weeks ago/three weeks before before going home two months ago/two months before
wj fbn zhdng zhc hòu
five minutes later/in five minutes’ time/after five minutes chc wfnfàn yh hòu after (eating) supper yc nián hòu a year later/in a year’s time/after a year cfi cfoméi de shíhou while picking strawberries wimen qù zhdngguó when we went to de shíhou China kàn she shí when reading xùnliàn zhdng during training
14 Verbs and time expressions
lifng gè yuè yh hòu wi qù kàn tamen I went to see them two months later. ta chc wfnfàn yh hòu qù kàn diànyhng After (she’s had) supper she is going to see a film./After supper she went to see a film. wi xiàban de shíhou pèngjiàn ta I met him when I came off work. huí jia zhc qián ta qù túshegufn jiè she She is going to borrow some books from the library before she goes home./She went to borrow some books from the library before she went home. Note 1: A more general time expression always precedes a more specific one when both are present: nèi tian xùnliàn zhdng that day during the training session xià xcngqc liù shàngwj shí difn líng wj fbn five past ten/10:05 a.m. next Saturday morning
Note 2: Specific time expressions formed by a ‘verb or activity noun + / / / qián/hòu/shí/zhdng’ may sometimes incorporate the word zài ‘at/in/on’. nèi gè yùndòngyuán zuótian zài xùnliàn zhdng shòu le shang That athlete was injured yesterday during a training session.
141
14 Verbs and time expressions
C Time words like chángcháng ‘frequently/often’, yhjcng ‘already’ and mfshàng ‘immediately/at once’, etc., which indicate less specific time, must follow (and not precede) the subject, if there is one: ta chángcháng qù yóuying He often goes swimming. ( ) wi mfshàng (jiù) lái I’ll be with you in a minute. (lit. I immediately come) One cannot say: * *
( )
chángcháng ta qù yóuying mfshàng wi (jiù) lái
D Time words or expressions are sometimes used in conjunction with aspect markers which indicate the completion, the continuation, the experience, etc. of an action (see Unit 15): wi yhjcng kàn wán le nèi bgn xifoshud I’ve already finished reading that novel. ta san suì de shíhou shbng guo lìjí ( dysentery) He suffered from dysentery when he was three.
lìjí
E Duration expressions, which indicate the length of time an action lasts or the time since an action has taken place, are generally placed immediately after the verb (compare the discussion of the time duration question in Unit 9): ta zài zhèr zhù le bàn nián He stayed here for six months. (lit. He stayed here for half a year.) wi jcntian gdngzuò le ba xifoshí I worked for eight hours today. nh de péngyou yhjcng dgng le èr shí fbn zhdng le Your friend has already been waiting twenty minutes.
142
/ wimen dào le/lái le yc gè bàn yuè le It’s one month and a half since we arrived./We’ve been here for a month and a half.
lh xiansheng líkai le san gè dud xcngqc le It’s over three weeks now since Mr Li left./Mr Li has been gone for over three weeks. Note 1: In the last two examples, the verbs dào ‘to arrive’, lái ‘to come’, líkai ‘to leave’, do not themselves express any duration of action, but the time phrase that follows indicates the time since the action took place.
14 Verbs and time expressions
Note 2: The implication of the presence of le at the end of the sentence, as seen in a number of the sentences above, is analysed in Intermediate Chinese, Units 1 and 8. If the verb has a noun object, the duration expression is placed de: between the verb and the noun object with or without ( ) I read for two hours. ( ) We danced all evening.
wi kàn le lifng gè xifoshí (de) she wimen tiào le yc gè wfnshang (de) wj
( ) ta xué guo san nián (de) zhdngwén He’s studied Chinese for three years. However, if the object is a personal (pro)noun or a noun indicating location, the duration expression is normally placed after the object: / wáng lfoshc jiao le wimen/wimen háizi lifng nián Mr/Miss Wang, our teacher, taught us/our children for two years. wi fùmj lái bgijcng wj gè yuè le My parents have been in Beijing for five months now. An alternative for that is to repeat the verb after the verb object phrase and then follow this verb with the duration expression (compare duration questions in Unit 9): wimen tántian tán le yc gè zhdngtóu We chatted for an hour. tamen xué zhdngwén zúzú xué le san nián They studied Chinese for fully three years.
143
14 Verbs and time expressions
In this format the emphasis is more on the actual period of time and involves some degree of comment on the part of the speaker. F Brief duration is generally expressed by the idiomatic expression ycxià ‘a moment’ or ychuìr ‘a while’: qhng nh xian zuò ycxià Please first take a seat for a moment. qhng dgng ycxià Please wait a minute. zánmen xiexi ychuìr ba Let’s rest for a while. nh néng zài zhèr dgng wi ycxià ma (following a pronoun object) Can you wait here a minute for me? Note: ba is a sentence particle indicating a tentative request (see Unit 20). If the verb has a noun object, the brief duration expression is likewise placed between the verb and the noun object but without de: / wimen zài gdngyuán li sàn le ychuìr/ycxià bù We went for a walk in the park. One does not usually say: * / wimen zài gdngyuán li sàn le ychuìr de/ycxià de bù An alternative way of expressing brief duration is to repeat the verb. If the verb is a monosyllable, yc may be placed between the two verbs, or le if a past action is referred to: zánmen yánjie yánjie We’ll look into/consider it. qhng nh zài wàimian dgng yc dgng Please wait outside for a moment.
144
qhng dàjia kàn yc kàn jcntian de bàozhh Will everyone please have a look at today’s newspaper.
14 Verbs and time expressions
geniang xiào le xiào The girl gave a smile. ta difn le difn tóu He nodded. zánmen qù sàn sàn bù Let’s go for a walk. G A duration expression may be placed before the verb with ddu and/or a negator to emphasize the fact that for that whole specified period of time something did/does/will happen all the time or did/ does/will not happen at all. ta zhgngtian ddu zài jia li kangufn háizi All day she was looking after the children at home. ) ta yc gè lhbài (ddu) méi chduyan le He hasn’t smoked for a whole week. H Expressions indicating frequency, like those indicating duration, are placed immediately after the verb: wimen tán guo lifng cì We have talked to each other twice./We’ve had a couple of talks. tamen lái le san tàng They came three times. If the verb has a noun object, the frequency expression is placed between the verb and the noun object: wi fùxí le lifng biàn kèwén I revised my lessons twice. ta yhjcng kai guo san cì dao le She’s been operated on three times already. wimen jiàn guo hgn dud cì miàn We have met many times.
Note: Unlike duration expressions, quency expressions.
de is not used with fre-
One cannot say: *
wi fùxí le lifng biàn de kèwén
145
14 Verbs and time expressions
If the object is a noun indicating place, the frequency expression may also follow the object: wi qù le yínháng lifng tàng I went to the bank twice. (lit. I made two trips to the bank.) If the object is a personal (pro)noun the frequency expression must normally follow the pronoun: / duìzhfng zhfo le nh/nh gbge jh cì The team captain looked for you/your elder brother several times. Note: cì indicates the number of times (in general), tàng, the number of trips made and biàn the number of times from beginning to the end. It is also possible, but not particularly common, for the frequency expression to follow a repeated verb (as with duration expressions discussed above): wi zhfo ta zhfo le san cì I looked for him three times. tamen qù bgijcng qù guo hfo jh tàng They have been to Beijing quite a number of times. I Like duration expressions, frequency expressions may also be placed immediately before the verb with ddu and/or a negator to indicate that for all the specified time or times something did/does/will happen or did/does/will not happen: tamen mgi cì ddu dài háizi lái They brought (their) children each time. duìzhfng san chfng bhsài ddu méi jìn qiú le The team captain hasn’t scored in the last three matches. ta shí cì ddu méi zhòng He hasn’t won (a prize) in ten attempts. (lit. for ten times)
Exercise 14.1 146
Place the time/duration/frequency expression or expressions given in brackets, in the Chinese sentences below, to provide a correct translation of the English:
1 I am going to Beijing tomorrow. wi qù bgijcng ( míngtian ‘tomorrow’) 2 I am going to Beijing for two days. wi qù bgijcng ( lifng tian ‘for two days’) 3 I went to Beijing last year. wi qù le bgijcng ( qùnián ‘last year’) 4 I am going to Beijing in two days’ time. wi qù bgijcng ( lifng tian hòu ‘two days later’) 5 I am going to Beijing before I get married. wi qù bgijcng ( jiéhen qián ‘before getting married’) 6 I am going to Beijing twice next year. wi yào qù bgijcng ( míngnián ‘next year’; lifng cì ‘twice’) 7 I have not been to Beijing for six months. wi méi qù bgijcng le ( bàn nián ‘half a year; six months’) 8 I go to Beijing for a fortnight every summer. wi qù bgijcng ( bàn gè yuè ‘half a month; a fortnight’; mgi nián xiàtian ‘every summer’ (lit. every year summer))
14 Verbs and time expressions
Exercise 14.2 Re-write the following sentences to include the time expressions given in brackets: 1 2 3 4 5 6 7 8 9
ta qù le shànghfi He went to Shanghai. (the year before last) mama líkai ycngguó My mother left Britain. (last month) gbge qù yóuying (My) elder brother went swimming. (on Tuesday) yéye mgi tian ddu kàn xifoshud Grandpa reads novels every day. (for 2 or 3 hours) wi zài xuéxí hànyj I’m learning Chinese. (now) wimen quán jia qù hfibcn Our whole family are going to the seaside. (next weekend) wimen qù tiàowj We go to a dance. (every Thursday evening) xifo zhang qù yínháng Xiao Zhang is going to the bank. (next Monday) qhng zài zhèr dgng wi Please wait for me here. (for five minutes)
147
14 Verbs and time expressions
10
wi qùnián qù tànwàng wi fùmj I went to see my parents last year. (twice)
Exercise 14.3 Decide which of these sentences are incorrect and make corrections as required: 1 2 3 4 5 6
7 8
tamen chángcháng qù kàn diànyhng They often go to see a film. ta zài hfi li yóu le ying ychuìr He swam in the sea for a while. mfshàng wi shàngban I am going to work immediately. ycnyuèhuì ganggang kaishh The concert has just started. wimen jìde ta yingyufn ( yingyufn ‘for ever’) We will remember him for ever. wi bàba zingshì hgn wfn shuìjiào ( ) zingshì ‘always’) My father always goes to bed late. wi xig le xìn yhjcng le I have already written the letter. duìzhfng kànjiàn ganggang xifo lh The team captain saw Xiao Li just now.
9 zhèi duì fefù zhgng nián ddu zài wàidì lsyóu This couple were away travelling all the year long. 10 ta lifng cì ddu lái le She turned up both times. ta lifng cì lái le zhèr 11 She’s been here twice. 12 yéye hé nfinai jcntian bàn gè zhdngtóu sànbù My grandparents went for a walk for half an hour today.
Exercise 14.4
148
Translate these sentences into English, paying attention to the way in which Chinese time expressions affect the tenses of the English verb.
1
( ) jcntian zfoshang wi yóu le lifng gè xifoshí (de) ying
2 wi de ycngguó péngyou zài zhdngguó zhù le lifng gè yuè 3
14 Verbs and time expressions
tamen yhjcng xué le lifng nián zhdngwén le 4 huìyì kaishh le sì shí fbn zhdng le (
huìyì ‘meeting’)
5 míngtian xiàwj wi hé tóngxué qù tc zúqiú ( tc zúqiú ‘to play football’ (lit. to kick football)) 6 mèimei zhgng wfn ddu zài nàr xig xìn ( zhgng wfn ‘the whole evening’) 7 wáng xiansheng hé ta de qczi míngnián qù zhdngguó dùjià 8 ta qùnián liùyuè bìyè (
bìyè ‘to graduate’)
9 dìdi mfi le yc shuang hgn piàoliang de qiúxié ( shoes’)
qiúxié ‘sports
10 wi bàba chángcháng qí zìxíngchb qù shàngban 11 wi san cì ddu zài ta jia dai le bàn gè zhdngtóu 12 nèi tian wfnshang ta tiào le san gè zhdngtóu de wj
Exercise 14.5 Translate the following sentences into Chinese: 1 2 3 4 5 6 7 8 9 10
Did you try steamed bread when you were in China? Can you wait outside for a minute? Let’s sit in the park for a while. Can you look after my child for a while? We went strawberry-picking for an hour. zhàopiàn She glanced briefly at that photograph. ( ‘photograph’) Please have a look at today’s paper first. He hasn’t touched alcohol for the whole year. I have known him for three years. I’ve already had a bath. ( xhzfo ‘to have a bath’)
149
14 Verbs and time expressions
150
Pattern and vocabulary drill 14.1 Formulate sentences after the given model: person: I time: guòqù ‘in the past’ venue: zài yc jia yínháng ‘in a bank’ action: work / wi guòqù zài yc jia yínháng shàngban/gdngzuò I used to work in a bank. 1 person: my neighbour time: next month venue: at home qhngkè lit. ‘invite guests to dinner’ action: 2 person: wi de yc gè zhdngxué tóngxué a secondary schoolmate of mine time: next week venue: zài yc jian jiàotáng in a church action: jjxíng henlh get married (lit. hold a wedding ceremony) 3 person: I time: next week destination: dào jiàotáng qù go to the church action: canjia henlh attend the wedding ceremony 4 person: my (maternal) uncle time: last year destination: China action: canjia àolínphkè yùndònghuì take part in the Olympic Games 5 persons: my elder sister and her boyfriend time: last month destination: Europe action: spend their holidays 6 persons: my grandpa and grandma time: next year destination: Beijing action: visit their Chinese friends 7 person: my Chinese teacher time: six months ago destination: dào ycngguó lái come to Britain action: see me 8 person: my paternal aunt’s husband time: tomorrow morning
destination: hospital action: have an injection 9 persons: my two fellow students time: next Saturday venue: in London action: watch a football match 10 persons: my younger brother and I time: last Sunday venue: in a park near the university action: learn T’ai Chi
14 Verbs and time expressions
Pattern and vocabulary drill 14.2 Formulate sentences after the given model: person: I time: yesterday afternoon venue: in the university library action: read duration: two hours and a half / wi zuótian xiàwj zài dàxué túshegufn kàn le lifng gè bàn xifoshí/zhdngtóu de she 1 person: yiu (yc) gè ycngguó yùndòngyuán a British athlete general time: last summer specific time: zài xùnliàn zhdng during training action: dfpò le zìjh de jìlù break his/her own record frequency: three times 2 person: a bank manager time: last March venue: in China action: stay duration: two weeks 3 person: a friend of mine time: three years ago venue: in Britain action: xué diànnfo learn computing duration: two months 4 person: my younger brother time: next autumn destination: China
151
14 Verbs and time expressions
5
6
7
8
9
10
action: learn Chinese duration: two months and a half person: I time: the day before yesterday venue: in the street action: ride a bicycle duration: half an hour person: a Chinese chef time: a year and a half ago venue: zài diànshì shang on television action: / bifoyfn le/yfnshì le demostrated (his skills) frequency: many times persons: my parents time: yesterday evening venue: at the railway station action: wait for me duration: 20 minutes person: my uncle (i.e father’s younger brother) time: this morning venue: on the beach action: sunbathe duration: an hour and a half persons: we (the speaker and the listener) time: tomorrow after school destination: park action: go for a walk duration: an hour person: my elder brother time: every week venue: in the post office action: work duration: two days
Pattern and vocabulary drill 14.3 Translate the following sentences into Chinese, making use of the rhetorical effect of placing a duration or frequency expression before the verb and being aware of the need for the sentence particle le, where appropriate, to highlight the changed or changing situation:
152
1 The patient did not eat anything for the last three days. 2 I haven’t seen my doctor even once for the last two years. 3 I stayed at my parents’ home the whole summer.
4 5 6 7 8 9 10
For the whole month she looked after her children at home. He has not smoked for a year now. I haven’t touched beer for a whole week now. He brought a bottle of wine with him every time he came. I haven’t bumped into him for the last few years. He goes to Beijing once a year. They see each other twice a week.
14 Verbs and time expressions
153
UNIT FIFTEEN Verbs and aspect markers
A Although as indicated in Unit 14 Chinese verbs do not express tense they are often linked with an aspect marker which may indicate the completion, experience, continuation, etc. of an action. With the exception of zài (see below) aspect markers are placed directly after the verb. The most common aspect markers are:
D
le guo zài zhe qhlái xiàqù xiàlái
completed action past experience an action in progress a continuous state resulting from an action/an accompanying action an action/a state which has just started an action which is to be continued an action/a state which is gradually changing into non-action or a quieter state
B le indicates that the action of the verb has been completed. It therefore often occurs in narrative sentences, where the marking of an action as being completed becomes important. However, a verb with le is naturally followed by a noun which is the subject/initiator’s premeditated goal, that is, something which the subject/initiator sets out to do. This means that all nouns that occur after le on their own are bound to be of definite reference unless they are specified as indefinite. For example, (i) nouns that occur after
le on their own:
* . . . wi xig le xìn I wrote the letter . . . 154
. . . ta mfi le pínggui He bought the apples . . .
(ii) nouns that occur after ( ) I wrote a letter.
le with some kind of extension:
wi xig le (yc) fbng xìn
15 Verbs and aspect markers
ta mfi le hgn dud pínggui He bought a lot of apples. As we can see from the sentences in (ii), xìn is modified by ( ) (yc)fbng and pínggui by hgn dud. If le is followed by an unmodified noun as in (i), for example: * wi xig le xìn or * ta mfi le pínggui, the sentence will sound incomplete and it cannot stand on its own. Grammatically, there are two ways to make such a sentence sound complete: one is to end the sentence with the particle le; the other is to add another clause to round it off: 1 Add the sentence particle
le
wi xig le xìn le wi mfi le pínggui le
I have finished writing the letter(s). I have bought the apples (we need).
2 Add another verb or verb phrase wi xig le xìn jiù qù jì xìn le As soon as I had written the letter, I went to post it. wi mfi le pínggui jiù huí jia le I went home as soon as I had bought the apples. Completed action of course in most cases refers to something completed in the past and an English translation would naturally use the present perfect tense or the simple past (or even past perfect) tense. A completed action, however, may take place in the future, as the following examples show: wi xià le ban jiù qù zhfo nh When I finish work/have come off work I will come (lit. go) and see you. qhng nh kàn le ycshbng jiù qù dfzhbn When you have seen the doctor, please go and have the injection.
155
15 Verbs and aspect markers
Note 1: jiù is usually placed before the verb in the second part of the sentence and implies that the action of this verb follows from the action of the verb in the first part of the sentence. Note 2: le is also used after adjectives, intransitive verbs or verbs indicating or incorporating complements of results to indicate a situation or state which has emerged or is emerging. This use of le, particularly when it occurs at the end of a statement, links with the sentence particle le at the end of sentences to indicate a change of state as the speaker sees it. (For a full discussion of sentence le see Intermediate Chinese, Unit 1.) yéye de bìng hfo le (adjective) Grandpa is well again. wi de bifo tíng le (intransitive verb) My watch has stopped. ta de kùzi pò le (verb indicating result) His trousers are torn. dìdi de ycfu quán lín shc le (verb incorporating result complement) (My) younger brother got soaked. C guo implies past experience. It occurs often in expository sentences, where statements are of a factual nature: wi chc guo jifozi I have had (tried) Chinese dumplings before. wi mèimei qù guo chángchéng My younger sister has been to the Great Wall. zhèi san gè yuè wi zhh jiàn guo jcnglh yc cì I have seen the manager only once in the last three months.
156
Note: We can see that the experience indicated by guo does not necessarily refer to what has been experienced in one’s lifetime. It may also refer to a specified period – e.g. ‘the last three months’ as in the last example. Likewise, the common enquiry or greeting: nh chc guo fàn méiyiu ‘Have you eaten?’ refers in the speaker’s mind to the immediate past. The distinction between
completed action following:
le and experience
guo can be seen from the
tamen qù le zhdngguó le They have gone to China (and they are in China now).
15 Verbs and aspect markers
tamen qù guo zhdngguó They have been to China before (and they are now back here or somewhere else). guo like le, as we have seen in Unit 2, is often associated with yes/no questions using méiyiu: nh chc le jifozi méiyiu Have you tried the Chinese dumplings? nh chc guo jifozi méiyiu Have you ever tried Chinese dumplings before? D ( ) (zhèng)zài, which precedes the verb, indicates that an action is in progress: ( )
( )
( )
bàba (zhèng)zài xie(lh) qìchb
Father is repairing his car.
tamen (zhèng)zài kaihuì
They are having a meeting.
Note 1: If a location phrase with aspect marker zài is not needed:
zài precedes the verb the
( ) ta (zhèng)zài huayuán li gb cfo He is/was in the garden mowing the grass. One does not say: * ( ) ta (zhèng)zài zài huayuán li gb cfo (lit. He is/was mowing the grass in the garden.)
Note 2: Like le, ( ) (zhèng)zài itself carries no indication of tense, since the action may be in progress at any time, in the past, present or future (other particles indicating progress will be discussed in Intermediate Chinese):
157
15 Verbs and aspect markers
( ) ta xiànzài (zhèng)zài xuéxí zhdngwén She is studying Chinese now. ( ) ta nèi nián (zhèng)zài xuéxí zhdngwén She was studying Chinese that year. míngtian zfoshang ta ycdìng zài xuéxí zhdngwén She’ll certainly be studying Chinese tomorrow morning. E
D zhe conveys either
(i) a continuous state resulting from an action: D ta chuan zhe yc tiáo hóng qúnzi She is/was wearing a red skirt. D ta dài zhe yc dhng bái màozi He is/was wearing a white hat. (The action of ‘putting on’ the skirt or the hat results in the ‘wearing’ of them.) D qiáng shang guà zhe yc fú shanshuh huà A Chinese landscape painting is hanging on the wall. (lit. On the wall is hanging a Chinese landscape painting.) (The action of ‘hanging a picture’ results in the picture ‘being hung’.) or (ii) an accompanying action (an action which takes place at the same time as another action): D tamen zuò zhe liáotian They sit/sat chatting./They are/were sitting there chatting. D ta xiào zhe difn le difn tóu She nodded smiling. D tamen hbng zhe gbr ziu le jìnlái They came in humming a tune.
158
As we can see from the above illustrations, if ( ) (zhèng)zài occurs more often in narrative sentences, recounting an action in progress, D zhe occurs more often in descriptive sentences, where it associates an action with a manner of execution or a resultant state.
F
qhlái implies that an action or state has just started:
15 Verbs and aspect markers
tamen chfo qhlái le They (have) started to quarrel. ta ke qhlái le She (has) started crying. tian lgng qhlái le It began/has begun to get colder. When an object follows the verb, it is placed between
qh and
lái:
tamen df qh jià lái le They (have) started fighting. tamen chàng qh gb lái le They (have) started to sing. wàimian xià qh yj lái le It began/has begun to rain (outside). One cannot say: * fighting) * G
dfjià qhlái/*
df qhlái jià (lit. start/have started
chànggb qhlái (lit. start/have started singing)
xiàqù indicates the continuation of an action: nh shud xiàqù
Go on!/Carry on (talking)! tamen huì dai xiàqù ma Will they stay on? xiàqù is not used where the verb has an object. One cannot say: * nh shud xià huà qù/* (lit. Go on!/Carry on (talking)!)
nh shudhuà xiàqù
H xiàlái implies that an action has gradually ceased or subsided or a situation has become more settled or quiet: chb tíng xiàlái le The car came to a stop. (originally, the car was moving.)
159
15 Verbs and aspect markers
wi xifng zài zhèr zhù xiàlái I would like to settle down here. (originally, I was always on the move) dàjia ddu jìng xiàlái le Everybody has become quiet. (originally there was a lot of noise) As with xià and
qhlái, if the verb has an object, the object comes between lái:
ta tíng xià chb lái He brought the car to a stop. ta an xià xcn lái She feels at ease (now)./She is no longer worried. Note: In most of the examples for qhlái and xiàlái, le occurs at the end of the sentence. Here le is functioning as a sentence particle, not an aspect marker, and implies a change of circumstance (see Intermediate Chinese, Unit 1). For further uses of qhlái, xiàqù and xiàlái as directional complements, see Unit 21.
Exercise 15.1 Add D zhe, le, guo or zài to the sentences below to complete the translation of the English in each case. In some cases there may be more than one possibility: 1
ta
chànggb
He is singing. 2 3 4 5 6 160
yéye dài yc fù yfnjìng Grandpa is wearing a pair of glasses. wi jiàn dà xióngmao I have seen a giant panda. ta xiào shudhuà She spoke smiling. ta bbi bbibao qù pá shan He went climbing with a rucksack on his back. wi die yc bf yàoshi I (have) lost a key.
7 8 9 10 11 12 13 14
wi péngyou hb zhdngguó píjij My friend has tried Chinese beer. lfoshc jifngjig kèwén The teacher is explaining the text. jigjie mfi yc shuang píxié (My) elder sister bought a pair of leather shoes. tamen qù bgijcng They have been to Beijing. shìjiè biànhuà The world is changing. shéi/shuí bang nh de máng Who is helping you? ta jifnféi She is slimming/trying to lose weight. wi yhjcng chc wfnfàn le I’ve already had dinner.
15 Verbs and aspect markers
15 xifo wáng gang shbng yc gè háizi Xiao Wang has just had a baby.
Exercise 15.2 Translate the following sentences into Chinese, paying particular attention to the use of appropriate aspect markers: 1 He was wiping the window. ( ( ) ca chuang(hu) ‘to wipe the window’) 2 They have been here. 3 I was watering the flowers. ( jiao ‘to water’) 4 My friend is drinking beer. 5 The teacher was standing teaching the lesson. ( zhàn ‘to stand’, jifngkè ‘to teach the lesson’) 6 He started dancing. 7 He is driving. 8 She bought a pair of shoes. ( yc shuang ‘a pair of’) 9 Grandfather is watching television. ( kàn diànshì ‘to watch television’) 10 Mother is wearing a beautiful hat.
Exercise 15.3 Complete these sentences with either qhlái, xiàlái, according to the English translation:
xiàqù or 161
15 Verbs and aspect markers
1
tamen chàng
le
They began to sing. 2 3 4 5 6 7 8 9 10
huichb tíng le The train came to a halt. nhmen zuò ba Carry on (with what you are doing). tianqì rè le The weather got warmer. dàjia jìng le Everyone quietened down. qhng nh shud Please go on! xifohái ke le The child began to cry. lifng tiáo yùnhé lián The two canals were connected together. zhèi jiàn shì wi xifng I recalled this matter. jìhuà dìng le The plan was decided upon.
le le
Exercise 15.4 Decide which of the following Chinese phrases are wrong and make corrections as necessary: 1 2 3 4 5 6 7 8 9 10
jifng xiàlái Carry on (with your story)! xué qh xí lái begin to study xig qhlái xìn start to write letters xué xiàlái carry on learning yj tíng xiàlái le the rain stopped chfo qhlái jià start quarrelling yóuying qhlái start swimming nufnhuo qhlái get warmer cdngming xiàlái become more intelligent màn xiàlái gradually become slower
Pattern and vocabulary drill 15.1
162
Form sentences with the 12 nouns and verbs/adjectives below using qhlái to imply that the action or state specified by the verb has just started. Sentence particle le must be added in each case to indicate
that a new situation has emerged or begun. Translate the resultant sentences into English. 1 2 3 4 5 6 7 8 9 10 11 12
mèimei dìdi tóngxuémen bàba hé mama tian tian gbge jigjie tianqì báitian lfo lh hé xifo lh nèi gè háizi
ke xiào chànggb tiàowj lgng xià yj xué zhdngwén chuan hóng qúnzi rè cháng chfo chduyan
15 Verbs and aspect markers
Pattern and vocabulary drill 15.2 The following sentences feature the aspect markers D zhe and zài. Indicate in each case whether the sentence presents (a) a narrative, recounting an action, or (b) a description. If it is (b), say whether it describes a manner of execution or a resultant state. 1
2 3 4 5 6 7 8 9 10
D / jiùjiu dài zhe yc fù hbiyfnjìng/tàiyángjìng ( / hbiyfnjìng/tàiyángjìng ‘sunglasses’) D mèimei ke zhe ziu le jìnlái bàba hé sheshu zhèngzài tántian D dìdi zài shafa shang tfng zhe mama zài chúfáng li zuòfàn D jiùmj chuan zhe yc shuang hbi píxié wàimian zài xià yj D yéye zài huayuán li zuò zhe jigjie zài fángjian li xig xìn D bàba shud zhe xiào le qhlái
Pattern and vocabulary drill 15.3 Translate the following sentences into English and point out for each sentence whether qhlái, xiàlái, or xiàqù are indicative of time or of space:
163
15 Verbs and aspect markers
1 2 3 4 5
D
háizimen dóu zhàn le qhlái nsshìmen ddu zuò le xiàlái tamen zuò zhe liáo qh tian lái zhè shíhou wàimian xià qh xug lái le zhèi jiàn shì wi jì bu qhlái le ( jì ‘to
recall’) 6 7 8
D ta shud bu xiàqù le
mèimei shud zhe ke le qhlái |
wimen zài nàr zhù le xiàlái zhè shíhou lfoshc ziu le jìnlái | tóngxuémen ddu jìng xiàlái le 9 chb dào le chbzhàn jiù tíng le xiàlái | gègè chéngkè ddu ziu xià chb lái D 10 gbge ná qh yc bgn she lái | ta kàn zhe xiào le qhlái | zài yg kàn bu xiàqù le zài yg ‘ever again, any more’; ( ná ‘to hold in hand’; kàn bù xiàqù ‘could no longer carry on reading’)
164
UNIT SIXTEEN Modal verbs
Modal verbs in Chinese are very much like those in English (e.g. can, must, should, etc.). They are placed directly before other verbs to indicate particular moods or attitudes. They are generally negated by bù. A
yào and
xifng are used to express wishes or desires:
/ wi yào/xifng hb bbi chá I would like a cup of tea. (lit. I would like to drink a cup of tea.) / / wi yào/xifng hb kafbi | bù yào/xifng hb chá I’d like coffee not tea. (lit. I would like to drink coffee not tea.) / / nh yào/xifng xué zhdngwén/ycngwén ma Do you want/Are you going to learn Chinese/English? Note: In an instruction or command yào used with a secondperson pronoun can only express obligation: nh yào zfo difn huí lái You must come back early. nh yào xifoxcn You must take care. bù yào duì wi sahufng You mustn’t lie to me./Don’t lie to me. B
yuànyi and
kgn both indicate ‘willingness’:
/ ta kgn/yuànyi bangzhù nh ma Is he willing to help you? / ta bù kgn/yuànyi rèncuò She is unwilling to admit her mistakes.
165
16 Modal verbs
C
gfn ‘dare’: ta gfn tíche zìjh de kànff He dares/dared to put forward his own ideas. wi bù gfn qù jiàn ta I daren’t go and see her. nh gfn Dare you (do it)? nh gfn df ta Dare you hit him?
D
( )
(ycng)gai ‘ought to’ and
dgi ‘have to’:
( ) / nh (ycng)gai shuì le/qhchuáng le You ought to go to bed/get up. wi dgi ziu le I must be off now. Negative sentences with ( ) (ycng)gai, on the other hand, imply reproach or blame for something that has already happened, and those with bù dé indicate (official) prohibition: nh bù gai gàosu ta You shouldn’t have told him. nh bù gai mà ta You shouldn’t have scolded her. xiánrén bù dé rù nèi No admittance./Admittance to staff only. (lit. casual people shouldn’t enter)
Note: Note that bù dé is used only for official prohibition. The negative equivalent for the colloquial dgi ‘must’ is in fact bù yòng ‘no need’ or bù bì ‘no need’.
bìxe ‘must; have to’ is, strictly speaking, an adverb but is used E like a modal verb:
166
míngtian wi bìxe dàodá nàr I must get there by tomorrow.
16 Modal verbs
wimen jcntian bìxe wánchéng zhèi gè gdngzuò We must finish this work today. Note: As bìxe is an adverb, it does not have a negative form, and bù bì/ bù yòng ‘need not’ are used instead: / nh bù bì/bù yòng qù le You needn’t go. (lit. There is no need for you to go.) F néng ‘can; may; be able to; be capable of’ and may’ to some extent overlap in function:
kgyh ‘can;
nh xiànzài kgyh ziu le You may leave/can go now. ta shí fbn zhdng néng pfo yc ycnglh He can run a mile in ten minutes. wi néng jìn lái ma May I come in? Note: kgyh implies permission from an outside authority, whereas néng refers to the ability to do something in particular circumstances: / nh bù kgyh zài zhèr xcyan/chduyan You can’t smoke here. wi zuó wfn bù néng lái I wasn’t able to come last night [because something cropped up, I missed the train, etc.]. G huì indicates either probability: ‘be likely to; be sure to’ or inherent or acquired ability/skill: ‘can; be able to; be good at; be skilful in’: / míngtian huì xià yj/xià xug ma Will it rain/snow tomorrow? (probability) nh huì shud zhdngwén ma Can you speak Chinese? (ability)
167
16 Modal verbs
Note: The difference between huì and néng which both mean ‘can; be able to’ can be illustrated by the following:
wi huì kaichb | dànshì xiànzài hb le jij | wi bù néng kai I can drive, but, as I have been drinking, I can’t. wi huì hb jij | dànshì xiànzài yào kaichb, wi bù néng hb I can drink, but, as I am going to drive, I can’t have one.
Exercise 16.1 Replace to do so: 1 2 3 4 5 6
yào with
xifng in the following where it is appropriate
wi yào xiexi ychuìr I would like to have a rest. nh yào zfo difnr qhchuáng You must get up early. ta yào qù zhdngguó lsyóu He wants to go travelling in China. nh yào hb difnr shénme What would you like to drink? nh yào hfohaor xuéxí You must study hard. mama yào mfi yc jiàn wàitào Mother would like to buy a coat.
Exercise 16.2 Choose the appropriate modal verb for the Chinese sentences so that they match the English translations: 1
nh
bang wi de máng ma
Can you help me? a 2
huì
b
néng
c
yào
jcn wfn Is it going to be windy tonight?
168
a
huì
b
néng
c
yào
gua fbng ma
3
hgn wfn le | wi It’s getting very late. I must go home now. a
yào
b
gai c
huí jia le
16 Modal verbs
kgyh
4 duìbuqh | nh bù zài zhèr chduyan I’m sorry. You can’t smoke here. a
yào
b
néng
c
huì
5 wi zài zhèr tíng chb ma May I park my car here? a
kgyh b
bìxe c
ycnggai
6 ta shud zhdngwén | kgshì ta xiànzài bù shud He can speak Chinese, but he’s not willing to speak it at this moment. a 7
néng;
yào
b
huì;
kgn c
huì;
néng
/ wi gfnmào le | wi jcntian dai/dai zài jia li I have a cold. I should stay at home today. a
bìxe b
ycnggai c
yuànyi
8 ta da gdnggòng qìchb lái | nh bù qù jib ta le She’ll come by bus. You don’t have to go and meet her. a
dgi b
bì
c
gai
Exercise 16.3 Add modal verbs with negatives, where necessary, to the Chinese sentences below so that they are a correct translation of the English: 1 He is not willing to do this. 169
ta
zuò zhèi jiàn shì
2 She doesn’t dare to go climbing at night. ta zài yè li pá shan 3 You may go home now. nh xiànzài huí jia le 4 He is not willing to admit his mistakes. ta rèncuò 5 I wouldn’t want to write a novel. wi xig xifoshud 6 She wants to go and see her friend in hospital. ta qù ycyuàn kàn péngyou 7 Don’t you dare ask her? nh wèn ta ma 8 I have to tell her the truth about the matter. wi gàosu ta shìqing de zhbnxiàng 9 You don’t have to go to school. nh jcntian qù shàngxué 10 I ought to phone her this evening. jcn wfn wi ggi ta df diànhuà 11 We must call the doctor. wimen jiào ycshbng 12 The prize shouldn’t have gone to him/been his. zhèi gè jifng shì ta de 13 Can I bring my cat? wi dài mao lái ma 14 Do you know how to use chopsticks? nh yòng kuàizi ma 15 Can the patient go jogging? bìngrén qù pfobù ma 16 Please may I have a piece of cake.
16 Modal verbs
qhng wèn | wi chc yc kuài dàngao ma 17 Mr Wang was ill and wasn’t able to come to class. wáng lfoshc bìng le | lái shàngkè 18 Will it snow tomorrow? míngtian xià xug ma 19 He can swim. ta yóuying 20 I can dance, but the floor was too slippery so I couldn’t dance on it. 170
wi tiàowj | dànshì dìbfn tài huá | wi shàngmian tiàowj
zài
21 You can speak both English and Chinese so you can be our interpreter. nh shud ycngyj hé hànyj | nh 22 You can’t cheat me. nh 23 I shall be able to come tomorrow. míngtian wi 24 This girl is small but she can eat a lot.
16 Modal verbs
zuò wimen de fanyì qcpiàn wi lái
zhèi gè ns háizi hgn xifo | dànshì ta chc hgn dud 25 Do you know how to repair cars? nh xielh qìchb ma 26 Is Manager Li likely to turn up tomorrow? lh jcnglh míngtian lái ma 27 Can you wait for me here? nh zài zhèr dgng wi ma 28 You shouldn’t quarrel (with each other). nhmen chfojià
Exercise 16.4 Translate the following sentences into Chinese: 1 2 3 4 5 6 7 8 9 10
Do you know how to drive? Is it likely to rain at the weekend? Do you want to go and visit your parents? You must go and revise your lessons. Can we go to the beach this week? I must remember the time of the concert. You shouldn’t have come to blows (with each other). May I take a holiday next March? Are you willing to help him? She daren’t fly in a plane.
Pattern and vocabulary drill 16.1 Translate the following sentences into English to show that you understand the meanings of all the modal verbs in their particular contexts: 1 2 3
ta kgn ma nh míngtian yào jìn chéng ma nh yào quàn quàn ta
171
16 Modal verbs
4 nh huì df tàijíquán ma 5 bù yào piàn rén 6 shuí néng bang wi ycxià máng ma 7 zhèr yiu rén huì shud ycngwén ma 8 nh néng bang wi fanyì zhèi jù huà ma 9 wi gai ziu le 10 nh gai xiexi le 11 shuí yuànyi liú xiàlái 12 wimen míngtian bìxe huí qù 13 (Mother to a child) nh xià cì hái gfn sahufng ma 14 míngtian zfoshang huì yiu wù ma 15 nh dgi qù kàn ycshbng
Pattern and vocabulary drill 16.2 In the groups of sentences below, translate each one into Chinese, making use of the appropriate modal verb. In some cases more than one modal verb may be possible and in others a modal verb may not be necessary. Also note that there are no one-to-one equivalents between English and Chinese modal verbs.
172
1 (a) (b) (c) (d) (e)
Are you going home tomorrow? Do you have to go home tomorrow? Do you want to go home tomorrow? Can you go home tomorrow? (Do you have the means?) Can you go home tomorrow? (Will you be allowed?)
2 (a) (b) (c) (d) (e) (f)
I I I I I I
3 (a) (b) (c) (d) (e)
Do you want to get off at the next stop? Do you have to get off at the next stop? Are you going to get off at the next stop? Can you get off at the next stop? Are you willing to get off at the next stop?
daren’t tell him. mustn’t tell him. won’t tell him. don’t want to tell him. needn’t tell him. shouldn’t have told him.
4 (a) Can you help me? (b) You are going to help me, aren’t you?
(c) (d) (e) (f) 5 (a) (b) (c) (d) (e) (f) (g) (h)
Are you willing to help me? You must help me! Shall I help you? I would like very much to help you, but I can’t.
16 Modal verbs
Do you speak Chinese? Is it possible for you to speak Chinese? May I speak Chinese? Shall I speak Chinese? Must I speak Chinese? I should speak Chinese, shouldn’t I? I know English. You needn’t speak Chinese. I would like very much to speak English, but . . .
173
UNIT SEVENTEEN Negators:
bù and
( ) méi(yoˇu)
We have already discussed some uses of bù and ( ) méi(yiu) in previous units (see Units 11 and 12). Here we shall review the functions of these two negators and draw attention to differences in the ways they are employed. A bù generally refers to the present or the future. It precedes the verb to indicate that something does not happen habitually or intentionally or that something will not happen in the future: wi bù qù kàn diànyhng I don’t go and see films./I’m not going to see the film. nèi gè yùndòngyuán bù chuan yùndòngxié That athlete doesn’t wear sports shoes. túshegufn míngtian bù kaimén The library isn’t/won’t be open tomorrow. chén xifojie bù chduyan | bù hb jij | bù df pái Miss Chen doesn’t smoke or drink or play mah-jong. However, bù may also be used to highlight intentional or wilful action even though the context is set in the past:
nèi gè yùndòngyuán yhqián bù chuan yùndòngxié That athlete didn’t wear sports shoes in the past. xifo shíhou wi chángcháng bù qù shàngkè When I was a child, I often missed classes. 174
B In contrast with bù, ( ) méi(yiu), which likewise goes before the verb, refers to the past and indicates that something has not
taken place or did not take place on one particular occasion or, if guo is suffixed to the verb, as a past experience: ( ) ta shàng gè yuè méi(yiu) pèngjiàn lh xiansheng She didn’t bump into Mr Li last month.
17 Negators: bù and ( ) méi(yoˇu)
( ) dìdi nèi tian méi(yiu) qù yóuying (My) younger brother didn’t go swimming that day. ( ) wi méi(yiu) chc guo bgijcng kfoya I’ve never had/eaten Peking duck. Note:
méiyiu may be abbreviated to
méi:
nèi gè háizi zuótian méi chcfàn That child didn’t eat (any food) yesterday. C The two negators are different in the way they are used with aspect markers: (i)
bù, and not ( ) méi(yiu), is normally used with the continzài: uous action marker mama bù zài xcchén Mother is not vacuuming (at the moment). nèi shíhou mama bù zài xcchén Mother was not vacuuming at that moment. It is unusual to say: *
nèi shíhou mama méi zài xcchén
However, bù does not usually occur with the aspect markers D zhe, xiàqù and xiàlái except in the form of bù yào or bié ‘don’t’ in prohibitions:
D
bù yào chàng xiàqù le Don’t sing any more! bié tíng xiàlái Don’t stop! bié zhàn zhe Don’t just stand there. (Do something!)
bù may not be used with le, guo or qhlái though it does occur with le as sentence particle (see Intermediate Chinese, Unit 8):
175
17 Negators: bù and ( ) méi(yoˇu)
ta bù késou le He’s not coughing any more. ta bù chduyan She’s quit smoking. (lit. She’s le no longer smoking.) (ii)
( ) méi(yiu) may only be used with the aspect markers qhlái, xiàqù and xiàlái: ( )
guo,
wi méi(yiu) jiàn guo ta tamen méi(yiu) df qhlái
I have never met him. They did not fight with each other. lfodàye méi(yiu) The old man dai xiàqù didn’t stay on. qián tàitai méi(yiu) Mrs Qian an xià xcn lái did not stop worrying.
( )
( ) ( )
( ) méi(yiu) is not used with le and D zhe. It must be emphasized that as a negator of past actions, ( ) méi(yiu) replaces le and does not occur with it: Compare: shèyhngshc pai le hgn dud zhàopiàn The photographer took a lot of photographs. ( ) shèyhngshc méi(yiu) pai hgn dud zhàopiàn The photographer didn’t take many photographs. One does not say: * ta méi pèngjiàn le lh xiansheng (lit. She didn’t bump into Mr Li.) Compare also: D ( )
ta chuan zhe dàyc ta méi(yiu) chuan dàyc
He’s wearing an overcoat. He did not wear/was not wearing an overcoat.
One does not usually say:
176
* ( ) D ta méi(yiu) chuan zhe dàyc (lit. He wasn’t wearing his overcoat.)
D Time expressions like zuótian, yhjcng, usually come before bù or ( ) méi(yiu):
gangcái, etc.
yubhàn yhjcng bù xué zhdngwén le John doesn’t study Chinese any more.
17 Negators: bù and ( ) méi(yoˇu)
wimen gangcái méiyiu kànjiàn ta We didn’t see her just now. mflì zuó wfn méi shuìjiào Mary didn’t sleep last night. Note: The time expression with a negator:
cónglái ‘all along’ is always linked
zhèi gè rén wi cónglái méi jiàn guo ta cónglái bù djbó
I have never met this person (before). He has never gambled.
E If there are location expressions in the sentence, they usually come after bù or ( ) méi(yiu): wi bàba bù zài dàshhgufn gdngzuò My father doesn’t work at the Embassy. wi jia méi zài mgiguó zhù guo Our family has never lived in America. F Monosyllabic adverbs like ddu ‘both’; ‘all’, yg ‘also’, hái ‘still; yet’, etc. usually come before bù or ‘once again’, méi(yiu): tamen ddu méi lái wi yg bù xhhuan weya ta yòu bù lái shàngkè le wi dìdi hái méi shàngxué
yòu ( )
None of them came. I don’t like crows either. He did not turn up for his class again. My younger brother hasn’t started school yet. 177
17 Negators: bù and ( ) méi(yoˇu)
Note 1: The only exception is ddu which may also come after the negator when it has a different meaning. Compare the following sentences: tamen ddu méi qù None of them went. tamen méi ddu qù Not all of them went./They didn’t all go.
Note 2: Remember that when used in a past context, ( ) méi(yiu) implies what is ‘factual’ whereas bù indicates what is ‘deliberate or intentional’. G bù, in keeping with its use in intentional contexts, and not ( ) méi(yiu), is used with modal verbs or verbs that express attitude. (i)
It is generally placed before the modal/attitudinal verb: tamen bù yuànyi bangzhù wi They are/were not willing to help me. nèi gè xifotdu bù gfn shud shíhuà That thief doesn’t/didn’t dare to tell the truth. wi bù xhhuan chc ròu I don’t like meat. (lit. I don’t like eating meat.)
(ii) However, it may also occur between the modal verb and the main verb when the meaning requires or allows it: wi xifng bù hb jij | hb qìshuh I would rather have a fizzy drink than alcohol. (lit. I would like not to drink alcohol (but) to drink a fizzy drink.) Compare: nh bù kgyh ziu You can’t leave (now). nh kgyh bù ziu You can stay. (lit. You can NOT leave.)
178
Note: With the modal verb gai the different positioning of the negator does not make much difference in meaning but with huì, the alternative changes the meaning drastically:
nh bù gai gàosu ta You shouldn’t have told him. nh gai bù gàosu ta You shouldn’t have told him. (lit. You should have not told him.) ta bù huì shud zhdngwén ma Can’t he speak Chinese?
17 Negators: bù and ( ) méi(yoˇu)
ta huì bù shud zhdngwén ma Is it possible that he won’t speak Chinese? With
dgi, the second alternative simply does not exist:
*
nh dgi bù ziu You should not go.
H
Adjectival predicatives may only be negated by nèi tiáo qúnzi bù piàoliang zhèi jian wezi bù ganjìng wi de bàngdngshì bù dà zhèr de kdngqì bù xcnxian nàr de rén bù dud
Note: Only adjectival idioms beginning with negated by méi:
bù:
That skirt isn’t pretty. This room isn’t clean. My office isn’t big. The air here isn’t fresh. There aren’t many people there. yiu will have to be
( ) zhèi bgn xifoshud méi(yiu) yìsi This novel isn’t interesting. ( ) wi jcn wfn méi(yiu) kòng I am busy tonight. (lit. I tonight am not free.) I ( ) méi(yiu), however, is generally used to negate adjectives that are used as state verbs (as opposed to action verbs), with the sentence particle le (see Intermediate Chinese, Unit 8). Compare the following pairs of sentences:
( )
ta de bìng hfo le He’s well again. ta de bìng hái He isn’t well yet. méi(yiu) hfo
179
17 Negators: bù and ( ) méi(yoˇu)
( )
tian qíng le tian hái méi(yiu) qíng
The sky has cleared up. It is still raining. (lit. The sky hasn’t cleared up yet.)
Exercise 17.1 Complete the sentences below with either a correct translation of the English: 1 2 3 4 5
bù or
méi to provide
bàba hb jij Father doesn’t drink. ta qù kàn jcngjù He didn’t go to watch the Beijing Opera. zuótian xià xug It didn’t snow yesterday. yhqián wi xué guo hànyj I have never studied Chinese before. ta cónglái chdu guo yan She has never smoked.
6
7 8 9 10 11 12 13 14 15
180
guòqù wáng xiansheng chángcháng dài màozi Mr Wang didn’t often wear a hat before. wi qù yóuying I am not going swimming. ta yhjcng qí zìxíngchb le He has stopped riding a bike. jigjie nèi tian tiàowj My elder sister didn’t dance that day. mèimei mfi qúnzi My younger sister didn’t buy a skirt. wi dú zuótian de bàozhh I didn’t read yesterday’s newspaper. gbge xhhuan chànggb My older brother doesn’t like singing. wi cónglái chc niúròu I have never eaten beef. wi cónglái hb guo lqchá I have never drunk green tea before. dìdi huì kaichb My younger brother can’t drive.
Exercise 17.2 Add the adverb in brackets to the Chinese sentences below and then adjust the English translation to take account of this: 1 2 3 4 5 6 7 8
17 Negators: bù and ( ) méi(yoˇu)
háizimen bù xhhuan chc shecài The children don’t like eating vegetables. ( ddu) tamen méiyiu qù kàn jcngjù They didn’t go to watch the Beijing Opera. ( yg) ta chcfàn qián bù xh shiu He didn’t wash his hands before meals. ( chángcháng) wi bù chduyan I don’t smoke. ( cónglái) ta méi hb chá She didn’t drink any tea. ( gangcái) ta méi kàn diànshì He didn’t watch TV. ( jcntian) ta méi chc dàngao She didn’t eat any/touch the cake. ( nèi tian) mèimei méi zuò guo fbijc (My) younger sister has not flown in a plane before. ( cónglái)
Exercise 17.3 Indicate which of the Chinese sentences below is the correct translation of the English in each case: 1 I don’t think the answer is correct. wi rènwéi nèi gè dá’àn bù duì wi bù rènwéi nèi gè dá’àn duì 2 I don’t think it is worth considering any more. wi bù rènwéi zhè zhíde dud xifng wi rènwéi zhè bù zhíde dud xifng 3 I have never taken a liking to her. wi cónglái méiyiu xhhuan guo ta wi cónglái bù xhhuan guo ta 4 He was not wearing an overcoat. ta méi chuan dàyc D ta méi chuan zhe dàyc ta bù chuan dàyc 181
17 Negators: bù and ( ) méi(yoˇu)
Exercise 17.4 Insert an appropriate negator or negators in the right position in each of the following Chinese sentences to match the meaning of the English sentences: 1
2 3
4 5 6 7
8
ta kgyh zài nèi zhuàng fángzi de qiáng shang xig biaoyj He is not supposed to write any slogans on the wall of that house. nh huì bao jifozi ma Can’t you make Chinese dumplings? jcnglh yuànyi jia chén xiansheng de gdngzc The manager was unwilling to give Mr Chen a pay rise. / wi zhèi gè xcngqc/lhbài néng lái ma Can I not come this week? ta lái ycngguó qián jiàn guo sdngshj She had never seen squirrels before she came to Britain. mèimei gfn qù línje nàr jiè yhzi My younger sister dare not go and borrow chairs from our neighbour. / kùzi tài dufn | dìdi kgn/yuànyi chuan The trousers were too short and my younger brother was not willing to wear them. shuhgui hgn xcnxian | dàjia ddu xifng chc The fruit was not fresh at all and nobody wanted to touch it.
9 zuótian xià dà yj | wimen qù caochfng tc zúqiú There was heavy rain yesterday. We didn’t go and play football on the sports field. 10 nh ycnggai gàosu tamen zhèi jiàn shì You shouldn’t have told them about this. 11 zhèi xib huar xiang | mìfbng lái cfi mì These flowers aren’t fragrant and the bees don’t come to collect honey from them. 12 cfoméi bh táozi hfochc Strawberries are not as delicious as peaches.
Pattern and vocabulary drill 17.1 Translate the following pairs of sentences, making clear how one sentence differs in meaning from the other in each pair owing to the different positioning of the negator: 182
ta bù gfn qù ta gfn bù qù
He dare not go. Dare he not go!
( ) méi(yiu) rén bù gfn qù There is nobody who dare not go.
17 Negators: bù and ( ) méi(yoˇu)
( ) méi(yiu) rén gfn bù qù There is nobody who dare stay behind. (lit. dares not to go) 1 2 3 4 5 6 7 8 9 10
nh bù yuànyi qù kàn diànyhng ma nh yuànyi bù qù kàn diànyhng ma shuí bù xifng chc ròu shuí xifng bù chc ròu háizimen bù kgn hb qìshuh ma háizimen kgn bù hb qìshuh ma geniangmen bù kgn chuan qúnzi ma geniangmen kgn bù chuan qúnzi ma nh bù xifng hb kafbi ma nh xifng bù hb kafbi ma yiu rén bù xifng hgn zfo qhchuáng yiu rén xifng bù hgn zfo qhchuáng ta bù gfn huí jia ma ta gfn bù huí jia ma shéi bù yuànyi xué zhdngwén shéi yuànyi bù xué zhdngwén méi(yiu) rén bù yuànyi xué zhdngwén méi(yiu) rén yuànyi bù xué zhdngwén shéi bù néng hb jij shéi néng bù hb jij
Pattern and vocabulary drill 17.2 Make the following sentences more emphatic in two ways by adding (1) the word zài ‘again’ and (2) the phrase zài yg ‘never ever again’, and translate the two emphatic versions into English: ta bù chduyan le He has quit smoking. ta bù zài chduyan le He is not smoking any more. ta zài yg bù chduyan le He will never smoke again. 1 2 3
wi bàba bù zài cèsui li chduyan le wi línje bù yfng giu le ta de ns péngyou bù hb jij le
183
17 Negators: bù and ( ) méi(yoˇu)
4 5 6 7 8
ta jiùjiu bù djbó le ta hb kafbi bù jia táng le háizimen bù zài jib shang tc zúqiú le wi mèimei bù sahufng le wi de yc gè tóngxué bù df rén hé mà rén le
9 10
184
wi gbge bù kaichb le wi mama bù chc ròu le
UNIT EIGHTEEN Types of question (1)
A General questions in Chinese can be formed by adding the particle ma to the end of a statement. Answers to such questions often employ the verb or adjective in the question with or without a negator as required by the meaning: nh shì ycngguó rén ma shì de bù shì | wi shì ffguó rén
Are you English?
nh yiu língqían ma yiu duìbuqh | wi méi yiu
Have you got change? Yes. (lit. have) Sorry, I haven’t.
nh máng ma hgn máng bù máng
Are you busy? Yes. (lit. busy) No, I’m not. (lit. not busy)
nh qù xuéxiào ma qù a jcntian bù qù
Are you going to the school? Yes. (lit. go) I’m not going today. (lit. today not go)
Yes. (lit. be) No (lit. not be), I am French.
Note: a, as seen in the last example, is a particle often placed at the end of an affirmative response either to emphasize the answer or to query the true meaning of the question, depending on the tone used by the speaker. qù a in this case means either ‘Yes, I am definitely going’ or ‘Yes, I am going, so what?’
185
18 Types of question (1)
In the answer to ma questions, it is also possible to use words or phrases indicating confirmation or denial, for example shì or shì de ‘yes’ (lit. it is/does), duì ‘yes’ (lit. right; correct), or bù or bù shì ‘no’ (lit. it isn’t/doesn’t): nh de bàngdngshì hgn zang ma Is your office very dirty? shì de | quèshí hgn zang Yes, it’s really filthy. bù | ycdifnr yg bù zang No, it’s not at all dirty! míngtian kaihuì ma Is the meeting tomorrow? duì | míngtian kaihuì Yes, the meeting’s tomorrow. bù | hòutian cái kai No, it’s not till the day after tomorrow. ( cái is an adverb indicating ‘not . . . until . . .’) nh bù xhhuan chc yú ma shì de | wi bù xhhuan chc yú bù | wi hgn xhhuan chc yú
Don’t you like fish?
nh shbn shang méi yiu qián ma bù | wi shbnshang yiu qián duì | wi shbnshang méi yiu qián
Don’t you have any money with you? Yes, I do.
No, I don’t (like fish). Yes, I do (like fish).
No, I don’t.
Note: From the last two examples you can observe that in answering a question, Chinese will first use ‘yes’ or ‘no’ to signal agreement or disagreement with the proposition, before a precise answer is given, whereas English generally uses ‘yes’ or ‘no’ depending on whether the answer itself is in the affirmative or in the negative.
186
B General questions may also be expressed in an ‘affirmativenegative’ form by repeating the verb or adjective with the negator bù or in the case of the verb yiu with the negator méi. Answers to such ‘affirmative-negative’ questions likewise use the verb or adjective in the question with or without a negator:
/
nh shì bù shì wáng xiansheng Are you Mr Wang? shì/bù shì Yes./No. (lit. be/not be)
/
nh mFi bù mFi shuhgui Are you going to buy any fruit? mfi/bù mfi Yes./No. (lit. buy/not buy)
18 Types of question (1)
nh jcn wfn yIu méi yIu shìr Have you got anything to do tonight? / yiu/méi yiu Yes./No. (lit. have/not have) zuótian lGng bù lGng Was it cold yesterday? lgng a/bù lgng Yes./No. (lit. cold/not cold)
/
zhèi gè háizi guAi bù guAi Is this child disobedient? / zhèi gè háizi zhbn guai/zhèi gè háizi ycdifnr yg bù guai This child is really obedient./This child is not at all obedient. nh de xíngli zhòng bù zhòng Is your luggage heavy? ( ) (wi de xíngli) ycdifnr yg bù zhòng My luggage isn’t heavy at all. Note: As we can see in the answers above, it is not unusual to emphasize one’s agreement or disagreement by modifying the adjectival predicative used in the questions with hgn ‘very’, zhbn ‘truly’, a, ycdifnr yg bù ‘not at all’, etc. C It must be pointed out that méiyiu, when employed to negate a completed action or past experience (see Unit 17), follows two patterns in the formulation of affirmative-negative questions: (i) uses
méiyiu is placed at the end of a positive statement which le or guo:
/
/
nh chc le fàn méiyiu Have you eaten yet? chc le/méiyiu Yes (I have)./No (I haven’t). xifo wáng lái le méiyiu lái le/hái méiyiu
Has Xiao Wang arrived yet? Yes (he has)./No, not yet.
nh qù guo zhdngguó méiyiu
Have you ever been to China?
187
18 Types of question (1)
/ ( ) (ii)
qù guo/méi(yiu) qù guo
Yes (I have)./No (I haven’t).
yiu méiyiu is inserted before the verb (retaining but omitting le) in the question:
guo
nh yiu méiyiu mfi xiangjiao Did you buy any bananas? / mfi le/méiyiu Yes (I did)./No (I didn’t). zuó wfn nhmen yiu méiyiu kàn diànshì Did you watch television yesterday? / kàn le/méiyiu Yes (I did)./No (I didn’t). nh yiu méiyiu tán guo zhèi gè wèntí Have you talked about this question? / tán guo/méiyiu Yes (I have)./No (I haven’t). méiyiu may also be added to an adjectival predicative with le which indicates a change of state (see Intermediate Chinese, Unit 8) to form the affirmative-negative question: ta de bìng hfo le méiyiu Has she recovered from her illness? (lit. Her illness has got well or not?) / ( ) hfo le/hái méi(yiu) hfo Yes (she has)./No, not yet. ta zuì le méiyiu Is he drunk? / ( ) zuì le/méi(yiu) zuì Yes (he is)./No (he isn’t). shù shang de pínggui shú/shóu le méiyiu Are the apples on the tree ripe? (lit. Have the apples on the tree ripened?) / ( ) shú/shóu le/hái méi(yiu) shú/shóu Yes (they are)./No, not yet. Note: shú and shóu are pronunciation variants of
188
‘to ripen’.
D If modal verbs are present, they (rather than the main verb) alternate in their positive and negative forms to formulate the affirmativenegative question:
( )
( )
nh jcn wfn néng bù néng qù tiàowj míngtian huì bù huì xià xug nh kg(yh) bù kgyh bangbang wi de máng ta yuàn(yi) bù yuànyi bangzhù nh
Can you go dancing tonight? Will it snow tomorrow? Can you help me?
18 Types of question (1)
Is she willing to help you?
One does not say, *
nh jcn wfn néng qù bù qù tiàowj
Can you go dancing tonight?
Note: With a disyllabic modal verb the affirmative part of the affirmative-negative sequence may often drop the second syllable, as the last two examples show. E Questions can, of course, be formulated with question words. In Chinese, the question word is located where the answer is to be expected. That is to say, Chinese, unlike English, does not necessarily have to move the question word to the beginning of the sentence (see Units 4 and 9): ta shì shéi ta shì zhèr de ycshbng
Who is he? He is the doctor here.
nh qù nfr
Where are you going? I’m going to the railway station.
wi qù huichbzhàn shéi lái le zhang xifojie lái le
Who has arrived? Miss Zhang has arrived.
zhè shì shéi de baogui
Whose parcel is this? It is that gentleman’s parcel.
zhè shì nèi wèi xiansheng de baogui
189
18 Types of question (1)
nh xifng hb difnr shénme wi xifng hb difnr kglè
What would you like to drink? I’d like (to have) some coke.
nh zài nfr xuéxí
Where are you studying? I am studying at Peking University.
wi zài bgijcng dàxué xuéxí nh yào ngi yc gè
F The particle
wi yào zhèi gè
Which one do you want? I want this one.
nf liàng chb shì nh de nèi liàng hbi chb shì wi de
Which car is yours? That black one is mine.
ne is also used to formulate a variety of questions.
(i) It may be placed after a noun, noun phrase or pronoun when the speaker is expecting something (or someone) and queries this: yàoshi ne Where are the keys? (Shouldn’t they be here; you have not forgotten them, have you; etc.) ta ne Where is he? (Shouldn’t he be here too/by now) jiégui ne And what was the result?/What happened then? (ii) It also occurs after a noun, noun phrase or pronoun to ask about the condition of somebody or something with reference to a statement that has just been made. Here it is usually translated as ‘And how about . . . /And what about . . . ?’: wi hgn hfo | nh ne I’m very well. And you? wi de zuòyè jiao le | nh de ne I’ve handed in my course-work. How about you? (lit. how about yours?) (Compare: wi jiao le zuòyè le | nh ne) 190
chènshan xh le | kùzi ne The shirt has been washed but what about the trousers?
Note: Observe the formulation of the last two examples. They are very similar to English passive voice sentences.
18 Types of question (1)
(iii) It can raise a question relating to a particular situation (couched in terms of a general statement) and is often roughly equivalent to English ‘what if . . .’: ta bù tóngyì ne
What if he doesn’t agree (to it)? lfoshc méi kòng ne What if the teacher hasn’t got time? míngtian xià yj ne What if it rains tomorrow? (iv) It may be added to a question-word question or an affirmativenegative question to introduce a tone of surprise or impatience: ta shì shéi ne Who can she be? xifo mao zài nfr ne Where can the kitten be? tamen máng bù Are they really máng ne busy?
Exercise 18.1 Change the statements below into two forms of questions using ma and the ‘affirmative-negative’ structure, providing answers in both the affirmative and the negative: ta chduyan He smokes. ta chduyan ma/ chduyan Does he smoke? chdu Yes. bù chdu No.
(
)
tamen shì nóngmín They are farmers. 2 ta xifng df pcngpangqiú He wants to play table-tennis.
ta chdu(yan) bù
1
191
18 Types of question (1)
3 4 5 6 7 8 9 10
ta qù guo dòngwùyuán He has been to the zoo. nèi tiáo jib hgn ganjìng That street is very clean. ta míngtian huì lái She will come tomorrow. ta yiu túshezhèng He’s got a library card. ta dài le yàoshi She’s brought her keys. hui hgn wàng The fire was burning brightly. nh de péngyou huì hbng nèi gè qjzi Your friend can hum that tune. ta de dìdi xhhuan chuan niúzfikù His younger brother likes wearing jeans.
Exercise 18.2 Convert the questions below into the aspect marker translate the questions into English:
le structure and
nh yiu méiyiu yóuying nh yóu le ying méiyiu Did you swim?/Did you go swimming? 1 2 3 4 5 6
nh yiu méiyiu xh chènshan nh zuótian yiu méiyiu dú bào shàng gè yuè nh yiu méiyiu kàn diànyhng zuó wfn nh yiu méiyiu xig xìn nh yiu méiyiu mfi piào ta yiu méiyiu pèngjiàn zhang xiansheng
7 nhmen qiántian yiu méiyiu shàng jijbajian 8 nhmen nàr shàng xcngqc yiu méiyiu xià xug 9 ta jia qùnián xiàtian yiu méiyiu qù hfi bian dùjià 10 192
zhèi jiàn shì xifo huáng yiu méiyiu gàosu nh
Exercise 18.3 Translate the following sentences into Chinese, expressing the question in two ways in each case: 1 2 3 4 5 6 7 8 9 10
Have Have Have Have Have Have Have Have Have Have
you you you you you you you you you you
ever ever ever ever ever ever ever ever ever ever
18 Types of question (1)
been mountain-climbing? met your neighbour? blamed yourself? been to a soccer match? ridden a horse? been to the seaside? tried Chinese dumplings? seen a whale? ( jcngyú ‘whale’) kept a dog? been to a pub?
Exercise 18.4 Translate the following sentences into Chinese: 1 2 3 4 5 6 7 8 9 10 11 12
Is it quiet in the library? ( anjìng ‘quiet’) Is it hot in Beijing? Are your friends happy? ( gaoxìng ‘happy’) Are the dishes tasty? Was that television programme interesting? Was the soccer match exciting? Is this chair comfortable? ( shefu ‘comfortable’) Do the flowers smell nice? ( xiang ‘sweet-smelling’) Was the cake sweet? ( tián ‘sweet (to the taste)’) Is the table clean? ( ganjìng ‘clean’) Is the room tidy? ( zhgngqí ‘tidy’) Was the manager generous? ( kangkfi ‘generous’)
Exercise 18.5 Translate these questions into Chinese using 1 2 3 4 5 6
ne:
What if he gets drunk? The trousers have been washed but what about the skirt? What if it rains tomorrow evening? What if I haven’t got time? The coffee is nice but what do you think of the cake? I’m very busy. How about you?
193
18 Types of question (1)
7 8 9 10
Where can she have gone? Whose computer is this then? Where are my keys? Where can the kitten be?
Pattern and vocabulary drill 18.1 In a Chinese sentence where the human initiator of the action of the verb is unambiguous and the relationship of the verb with its inanimate object is clear, the order of the verb and object can be reversed to form what is called a notional passive. Following the model shown, change the 12 sentences below into notional passives, with or without the human initiator: wi mfi le piào le I have bought the ticket. piào wi mfi le piào mfi le 1 2 3
wi xie hfo le chb le I have mended the car. wi dài le yjsfn le I have had my umbrella with me. nh dài le yàoshi le ma Have you brought your key with you?
4 5 6 7 8 9 10 11 12
194
nh chc guo bgijcng kfoya ma Have you ever tried Peking duck? nh jiao le zuòyè méiyiu Have you handed in your homework? ta jì le xìn méiyiu Has she put the letter in the post? nh hb guo lqchá méiyiu Have you ever drunk green tea? wi xh le ycfu le I have washed the clothes. nh qù guo bgijcng méiyiu Have you ever been to Beijing? nh dào guo chángchéng méiyiu Have you been to the Great Wall? nh dài le qín méiyiu Have you got any money on you? ( ) nh kàn le jcntian de bàozhh (le) ma Have you read today’s paper?
Note: All Chinese notional passives normally end with the sentence particle le.
Pattern and vocabulary drill 18.2 You will see below two general questions, which each have different alternative forms. Following these patterns, restructure each of the 15 sentences into an appropriate alternative form:
18 Types of question (1)
zhè jh tian nh qù pfobù ma Are you going jogging in the coming few days? zhè jh tian nh qù bù qù pfobù ta dang le jcnglh le ma Has he been promoted to the managership? ta dang le jcnglh méiyiu 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
zhè jh tian nh qù xué tàijíquán ma Are you going to take T’ai Chi lessons in the coming few days? zhè jh tian huì xià yj ma Is it going to rain in the next few days? nh néng zài zhèr dgng ycxià ma Can you wait a little here? nh mfi le chb le ma Have you bought your car? nh xhhuan chuan niúzfikù ma Do you like wearing jeans? nh dài le túshezhèng le ma Have you brought your library card with you? nh tóngyì wi de jiànyì ma Are you agreeable to my suggestion? nh de péngyou huì df pcngpangqiú ma Does your friend know how to play ping-pong? nh míngtian zfoshang yiukòng ma Are you free tomorrow morning? nh xifng chc bgijcng kfoya ma Do you want to try Peking duck? nh yuànyi bang ta de máng ma Are you willing to help him? nh jia li yiu diànnfo ma Do you have a computer at home? nh wánchéng le nèi jiàn gdngzuò le ma Have you finished that work? nh dang guo lfoshc ma Have you ever been a teacher? nh jiàn le jcnglh le ma Have you seen the manager yet?
195
UNIT NINETEEN Types of question (2)
A Tag questions, which are seeking agreement to, or approval of, a suggestion or proposal, are formed by attaching / hfo ma/hfo bù hfo, / xíng ma/xíng bù xíng (lit. ‘is this OK?’), / ( ) kgyh ma/kg(yh) bù kgyh (lit. ‘is that all right?’), etc. to the statement. Answers to such questions repeat the tag words hfo, xíng or kgyh, sometimes with a in the affirmative, and with bù in the negative: zánmen qù sànbù | hfo ma hfo a
Shall we go for a walk? Fine/OK.
wi xifng df gè diànhuà | xíng ma xíng
Is it all right if I make a phone call? Yes/All right.
wimen jcntian zfo difnr huí jia | kgyh ma bù kgyh
Can we go home earlier today? No, you can’t.
B ba may be added to the end of a positive or negative statement to form a question implying surmise or supposition. Answers to these questions naturally invite the use of ( ) shì (de) or duì ‘yes’ or ( ) bù (shì) or bù duì ‘no’ (see Unit 18), as a direct response to the surmise or supposition itself: zhèi gè hànzì bù duì ba This Chinese character is wrong, isn’t it?/Isn’t this Chinese character wrong? shì | zhèi gè hànzì bù duì Yes, it is wrong. 196
nèi fú huàr shì ta huà de ba That picture was painted by him, wasn’t it?
bù | nèi fú huàr bù shì ta huà de No, it wasn’t painted by him. ta huì qí mótudchb ba He can ride a motorbike, can’t he? shì de | ta huì Yes, he can.
19 Types of question (2)
míngtian bù huì xià yj ba It won’t rain tomorrow, will it? kingpà huì xià yj I’m afraid it will. Note: ba at the end of a statement can also express a suggestion or exhortation: zánmen ziu ba
Let’s go. (See Unit 20.)
C An alternative question where the speaker presents two possibilities, e.g. ‘Are you English or French?’, is formed by placing háishi ‘or’ between the two possibilities: nh shì zhdngguó rén háishi rìbgn rén Are you Chinese or Japanese? wi shì zhdngguó rén I am Chinese. nh xhhuan kàn diànyhng háishi tcng ycnyuè Do you like watching films or listening to music? wi xhhuan kàn diànyhng I like watching films. nh huí jia háishi qù yínháng Are you going home or going to the bank? wi qù yínháng I am going to the bank. Note 1: The two posed alternatives must be of similar structure, i.e. zhdngguó rén . . . or rìbgn rén . . . (nouns); kàn diànyhng . . . or tcng ycnyuè . . . (verb + object), etc.
Note 2: The conjunction ‘or’ in English is rendered in Chinese by háishi in questions and huòzhg in statements.
197
19 Types of question (2)
nh xifng hb chá háishi hb kaifbi Would you like tea or coffee? chá huòzhg kaifbi ddu kgyh Either will do. (lit. tea or coffee will do)
D In Unit 11, it was explained that to emphasize the initiator, target, time, place, means, purpose, etc. of a past action the shì . . . de construction is used: kèren shì zuótian dào de The guests arrived yesterday.
(time)
tamen shì zuò fbijc qù de
(means)
They went by plane. ta shì lái zhfo de jcnglh She came to see the manager. For present and future action
(target)
shì is employed without
kèren shì míngtian dào tamen shì zuò fbijc qù wi shì qù tànwàng fùmj
de:
The guests are arriving tomorrow. They are going by plane. I am going to visit my parents.
However, with the verb lái ‘to come’, de often occurs at the end of the sentence even if it still indicates future. As the following example shows, the reason is perhaps that though the woman has yet ‘to see the manager’, the speaker wants to highlight the fact that she has already arrived on the scene: ta shì lái zhfo jcnglh de
She is coming to see the manager.
These sentences of emphasis with shì or shì . . . de can be formulated into various forms of question: question-word questions, general questions, or affirmative-negative questions: (i) past actions:
198
kèren shì shénme shíhou dào de When did the guests arrive?
kèren shì zuótian dào de ma kèren shì bù shì zuótian dào de Did the guests arrive yesterday?
19 Types of question (2)
kèren shì zuótian dào de | háishi qiántian dào de Did the guests arrive yesterday or the day before yesterday? tamen shì zgnme qù de How did they travel? tamen shì zuò fbijc qù de ma tamen shì bù shì zuò fbijc qù de Did they go by plane? tamen shì zuò fbijc qù de | háishi zuò chuán qù de Did they go by plane or by boat? ta shì lái zhfo de shéi/shuí Who(m) did she come to see? ta shì lái zhfo de jcnglh ma ta shì bù shì lái zhfo de jcnglh Did she come to see the manager? ta shì lái zhfo de jcnglh | háishi lái zhfo de kuàijì Did she come to see the manager or the accountant? (ii) present or future actions: kèren shì shénme shíhou dào When are the guests arriving? kèren shì míngtian dào ma kèren shì bù shì míngtian dào Are the guests arriving tomorrow? kèren shì míngtian dào | háishi hòutian dào Are the guests arriving tomorrow or the day after tomorrow? tamen shì zgnme qù How are they travelling? tamen shì zuò fbijc qù ma tamen shì bù shì zuò fbijc qù Are they going by plane?
199
19 Types of question (2)
tamen shì zuò fbijc qù | háishi zuò chuán qù Are they going by plane or by boat? ta shì lái zhfo shéi/shuí Who(m) is she coming to see? ta shì lái zhfo jcnglh de ma ta shì bù shì lái zhfo jcnglh de Is she coming to see the manager? (The speaker must have known that the visitor has arrived, as was explained above regarding sentences like this with lái.) ta shì lài zhfo jcnglh | háishi lái zhfo kuàijì Is she coming to see the manager or the accountant? The answer to all general, affirmative-negative questions is either ( ) shì (de) ‘yes’ or bù shì ‘no’: shì nh qù zhfo de ta ma shì bù shì nh qù zhfo de ta Was it you who went to see her?/Did you go to see her? shì de | shì wi Yes, it was me. nh shì qù kàn diànyhng ma nh shì bù shì qù kàn diànyhng Are you going to see a film? bù | wi bù shì qù kàn diànyhng | wi shì qù tiàowj No, I’m not going to see a film, I’m going dancing.
Exercise 19.1 Translate the following questions into Chinese using the tags ma, xíng ma or kgyh ma: Could you shut the door, please? qhng nh guan shàng mén | hfo ma
200
1 2 3 4 5 6
Could you close the window, please? Could you please speak Chinese? May I use the phone? Shall we go to the cinema? May I borrow a pen? ( jiè ‘to borrow’) Can I sleep in tomorrow? ( shuì lfn jiào ‘to sleep in’)
hfo
7 8 9 10
May I May I Could Could
sit here? make a suggestion? ( tí ‘to put forward’) you tell us a story, please? we go dancing tonight?
19 Types of question (2)
Exercise 19.2 Formulate questions, using shì bù shì and where necessary de on the basis of the statements below to elicit the required information: zhdu xiansheng zuò fbijc qù ycngguó Mr Zhou went to England by plane. (i) Did Mr Zhou go to England/Was it Mr Zhou who went to England? shì bù shì zhdu xiansheng qù de ycngguó (ii) Did Mr Zhou travel by plane? zhdu xiansheng shì bù shì zuò fbijc qù de (iii) Did Mr Zhou go to England/Was it England Mr Zhou went to? zhdu xiansheng shì bù shì qù de ycngguó 1
xifo lh qí zìxíngchb qù yùndòngchfng Xiao Li went to the sports field on his bike. (i) Is Xiao Li going to the sports field/Is it Xiao Li who is going to the sports field? (ii) Is Xiao Li going to the sports field/Is it the sports field that Xiao Li is going to? (iii) Is Xiao Li going on his bike to the sports field?
2
wáng xifojie gangcái qù yóujú Miss Wang went to the post office just now. (i) Did Miss Wang go to the post office/Was it Miss Wang who went to the post office? (ii) Did Miss Wang go just now/Was it just now that Miss Wang went? (iii) Did Miss Wang go to the post office/Was it the post office Miss Wang went to?
201
19 Types of question (2)
Exercise 19.3 Make questions using háishi which might be answered by the statements below. (Note that in some cases the pronoun may have to be changed.): 1
wi shì lfoshc | bù shì xuésheng I’m a teacher, not a student.
2 ta xhhuan kàn xifoshud | bù xhhuan kàn diànshì He likes reading fiction, but he doesn’t like watching television. 3 ta bù shì zuótian qù de zhdngguó | shì qiántian qù de He didn’t go to China yesterday, he went the day before. 4 wi shì zuò huichb qù shàngban | bù shì zuò qìchb I go to work by train, not by bus. 5 wi shì qù diànyhngyuàn | bù shì qù fàngufn I’m going to the cinema, not to the restaurant. 6 zhè shì ycyuàn | bù shì dàxué This is a hospital, not a university. 7 ta nèi tian shì chuan de qúnzi | bù shì kùzi What she wore that day was a skirt, not a pair of trousers. 8 wi qiántian shì pèngjiàn de lfo wáng | bù shì xifo zhang I bumped into Lao Wang, not Xiao Zhang, the day before yesterday.
Exercise 19.4 Change the following Chinese sentences into questions using ba, and then (1) provide English translations of the questions and (2) give positive and negative answers to the questions in Chinese and English. (Note again that in some cases the pronoun may need to be changed.) xiàtian tàiyáng wj difn bàn jiù che lái le The sun rises at five thirty in the summer.
202
xiàtian tàiyáng wj difn bàn jiù che lái le ba The sun rises at half past five in the summer, doesn’t it?
/ ( )
duì | shì (de)
Yes. /
( )
bù duì | bù shì (de)
No. 1 2 3 4 5 6 7 8
19 Types of question (2)
zhèi bgn she shì wi xig de This book was written by me. lúnden lí bgijcng hgn yufn London is a long way from Beijing. huichb yhjcng kai ziu le The train has already gone. nà/nèi tiáo qúnzi tài cháng le That skirt is too long. / wi mgi tian ddu tì/gua húzi I shave every day. wi bàba | mama xià gè yuè qù dùjià My parents will go away on holiday next month. wi bù xhhuan hb zhdngguó chá I don’t like Chinese tea. wi qczi bù chc niúròu My wife does not eat beef.
Exercise 19.5 Translate the following sentences into Chinese, giving emphasis to the expressions in italics and paying particular attention to whether or not de must be included to indicate past or future events: 1 2 3 4 5 6 7 8
Are you going to China next month? Did you go to China last year? Are you going by plane or by boat? Did you go by car or on a bike? Where did you learn your Chinese? Where are you going to learn your Chinese? Who washed the bowls last night? Who is going to wash the bowls tonight?
Pattern and vocabulary drill 19.1 Following the pattern below answer the 12 questions positively or negatively.
203
19 Types of question (2)
nh xhhuan chc yú ma Do you like eating fish? wi hgn xhhuan chc yú Very much. / wi ycdifnr yg/ddu bù xhhuan chc yú Not at all. 1 2 3 4 5 6
7
nh xhhuan df pcngpangqiú ma Do you like playing ping-pong/table-tennis? nh xhhuan kàn diànyhng ma Do you like watching films? dàngao hfochc ma Is the cake delicious? nèi bgn xifoshud yiu yìsc ma Is that novel interesting? nèi tiáo kùzi cháng bù cháng Is that pair of trousers long? nh sheshu de háizi kg’ài ma ( ‘lovely’) Are your uncle’s children lovely? nh jia de xifo mao kg’ài bù kg’ài Is your kitten lovely?
kg’ài
8 zuò huichb qù bh zuò qìchb qù kuài ma Is it faster going there by train than by car? 9 nh xifng qù zhdngguó wánr ma Do you want to go travelling in China? 10 nàr de xiàtian rè bù rè Is the summer there hot?
Pattern and vocabulary drill 19.2 Translate the following questions into Chinese using to give emphasis to the enquiry. Are you going out for a walk? nh shì bù shì che qù sànbù
204
1 2 3 4 5
Do you really want to learn Chinese? Are there a lot of athletes on the sports field? Is the street full of people? Are your parents coming to see you in a few days? Do you often go swimming?
shì bù shì
6 7 8 9 10
Is your friend waiting for you outside? Have they been to Beijing many times? Is she writing letters the whole evening? Have you had a lot of beer tonight? Does this dish not taste as nice as that one?
19 Types of question (2)
205
UNIT TWENTY Imperatives and exclamations
A Imperatives, as commands or requests directed at the listener in given contexts, do not usually need a subject (unless the speaker wants to single out a particular person from a group): jìn lái che qù zhàn qhlái zuò xià anjìng difnr yánsù difnr
Come in! Get out! Stand up! Sit down! Quieten down! (lit. a bit quieter) Be serious! (lit. a bit serious)
nh qù jiao shuh | nh qù gb cfo | nh qù jifn shùlí You, water the plants! You, mow the grass! And you, clip the hedge! B To soften the tone of an imperative to the level of a request, qhng ‘please’ is placed at the beginning of the imperative: qhng jìn lái qhng zuò xià qhng dàjia anjìng difnr
Come in, please! Please take a seat! Would everybody be quiet, please!
To soften the tone still further, the sentence particle qhng jìn lái ba qhng zuò ba ba occurs without zuò ba 206
jìn lái ba
ba can be used:
Won’t you please come in! Won’t you please sit down!
qhng and carries a casual tone: Sit down then!/Okay, take a seat!/Why don’t you take a seat! Come in then!/Okay, you can come in now.
C Commands and requests usually call for actions on the part of the listener. If they involve a third party, verbs like ràng ‘to let; to allow; to permit’, jiào ‘to order’, etc. are usually placed before the thirdperson pronoun: ràng ta ziu ba jiào ta lái jiàn wi ràng ta qù
20 Imperatives and exclamations
Let him go! Tell him to come and see me! Leave him alone! (lit. let him go)
Note: Observe the idiomatic use of the verb example.
qù ‘to go’ in the third
ràng is, of course, also used by the speaker in relation to him- or herself: ràng wi bang nh de máng ràng wi kàn yc kàn ràng wi xifng ycxià
Let me give you a hand! Let me have a look! Let me think about it!
D In the case of an imperative involving the action of the speaker and the listener, the pronoun zánmen ‘we/us’ is used together with the particle ba: zánmen ziu ba zánmen hb yc bbi ba
Let’s go! Let’s have a drink!
E Commands or requests may also be concerned with the manner in which actions are carried out. Under such circumstances, the relevant adverbials are placed before the imperative verb: kuài ziu mànmàn lái dui chc difnr
Hurry up! Take it easy!/Take your time! Have some more (food)!
F Negative imperatives (or prohibitions) are expressed by ‘don’t’ or its short form bié:
bù yào
dgng yc dgng | bié ziu Wait a minute!/Hang on! Don’t go (yet)! bié shudhuà Keep quiet! (lit. don’t speak)
207
20 Imperatives and exclamations
bié kèqi bù yào chduyan bù yào kai wánxiào
Make yourself at home! (lit. don’t be polite) Don’t smoke! Don’t (treat it as a) joke.
G Sentence particle le (sometimes in combination with pronounced la) is added to introduce a note of urgency: bié shudhuà le qhchuáng la
a and
Silence, please!/Stop talking! It’s time to get up./Up you get!
H More formal prohibitions which appear on public notices are expressed by bù zhjn ‘not allowed’, bù xj ‘not permitted’ and bù dé ‘must not’ bù zhjn chduyan bù dé rù nèi bù xj zài ch luàn die lajc
No smoking! No entry! No litter on the premises!
I Exclamations are formed by placing a degree adverb like ( ) dud(me) ‘how’, zhbn ‘really/truly’ before the adjective, which is often followed by a: lúnden de jibdào dudme fánmáng a How busy the streets in London are! qiáo | ta pfo de zhbn kuài a Look, he can run really fast! nh zhbn dòu You are really funny/witty! J There is a tendency for the particle a to be affected by the vowel or consonant ending of the word that precedes it. This leads to possible variants including the following: Endings -i -u, -ao -n le and
Variant ya wa na a (see G above) fuse to become la
Examples 208
tian na
Heavens!
20 Imperatives and exclamations
zhèi dào tímù zhbn nán na This question is really difficult! zhèi zhing yào dudme kj wa This medicine is so bitter/really awful/nasty! bù shì zhèi huí shì ya It is certainly not the case! qìchb xie hfo la The car has been repaired at last! yc zhc dudme mgilì de xifo nifo wa What a beautiful little bird! zhèi tóu xióngmao dud kg’ài ya Isn’t this panda sweet! zhèi chfng qiúsài dudme jcngcfi ya This football match is so exciting! Note: The above are not rigid rules and it is possible for individual speakers simply to use a or ya in many cases.
Exercise 20.1 Translate the following imperatives into Chinese: 1 2 3 4 5
Come in! Stand up! Get out! Sit down! Get up!
6 7 8 9 10
Be quick! Come back early! Close the door! Be serious! Don’t switch off the light!
Exercise 20.2 Translate the following imperatives into Chinese, using ba, ràng, jiào where appropriate: 1 2 3 4 5
Do have some more (food)! Let’s get off (the bus) here. Leave him alone. Hurry up! Please queue up here! ( páiduì ‘to queue’)
qhng and/or
209
20 Imperatives and exclamations
6 7 8 9 10
Switch on the light, please! Come in, please! Let’s have a little rest! Listen! Who is it? Please open the door.
Exercise 20.3 Rephrase the imperative sentences below as negatives: 1 2 3 4
guan chuang guan dbng liàng ycfu shàng chb
5 6
guò lái chuan zhèi shuang xié kaichb ràng ta ziu jiào ta huí lái qhng dàjia dài sfn
7 8 9 10
Close the window! Turn off the light! Hang the clothes out to dry! Get on the bus!/Get into the car! Come here! Wear this pair of shoes! (in a car) Let’s go! Let him go. Tell her to come back. Would everyone please bring umbrellas.
Exercise 20.4 Translate into Chinese the two imperative sentences (i) and (ii) in each of the following cases, building on the basic imperative provided: 1
jìn qù Go in! (i) Let’s go in! (ii) Okay, you may go in now!
2
qù gb cfo Go and cut the grass! (i) Would you please go and mow the grass! (ii) Go and mow the grass now please! (It’s time for you to go and mow the grass now.)
210
3
xià chb Get off the bus! (i) Let’s get off the bus! (ii) Come on, we’re getting off here!
4
20 Imperatives and exclamations
hb yc bbi Have a drink! (i) Let’s have a drink! (ii) It’s okay, you may have a drink!
Exercise 20.5 Complete the following sentences with a likely exclamatory particle in each case, such as a, ya, wa, na or la, remembering that with la an element must be replaced: 1
zhèi kuài shítou dud zhòng This stone is so heavy!
2 3 4 5 6 7 8
nèi zhuàng dàlóu zhbn gao That building is really tall! wàimian dud lgng How cold it is outside! wi è sh le I am so hungry! ta lái de zhbn zfo He’s here really early! nh kàn dìbfn ddu shc le Look, the floor is all wet! jcntian de tianqì dudme hfo What a nice day it is today! zhèi dào tí zhbn nán This question is really difficult!
9 zhè shì yc tiáo dudme piàoliang de qúnzi What a pretty skirt this is! 10 túshegufn li zhbn anjìng How quiet it is in the library! 11 zhèi gè háizi dud kg’ài How lovely this child is! 12 dudme kg’ài de yc zhc xifo mao What a lovely kitten! 211
20 Imperatives and exclamations
Pattern and vocabulary drill 20.1 Translate the 15 negative commands below using the verb indicated in each case: Don’t bother about me. ( bié gufn wi 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
bié ‘Don’t’ with
gufn)
Never mind him! ( gufn) Don’t come in! ( jìn lái) Don’t go out! ( che qù) Don’t go yet! ( ziu) Don’t touch it! ( pèng) Don’t go on! ( shud) Don’t swear at people! ( mà) Don’t sleep on the sofa! ( shuì) Don’t look for excuses! ( zhfo) Don’t borrow money from others. ( Don’t wait for me. ( dgng) Don’t smoke here. ( chduyan) Don’t tease him. ( dòu) Don’t stand up. ( zhàn) Don’t laugh at me. ( xiào)
jiè)
Reformulate the same 15 imperatives making use of the words in brackets, and then translate them into English: Don’t bother about me. ( bù yòng) ( ) (nh) bù yòng gufn wi ‘No need (for you) to bother about me!’
212
1 2 3 4 5 6 7 8 9 10 11 12 13
bù bì ) Never mind him! ( Don’t come in! ( bù yào) Don’t go out! ( bù xj ‘not allowed’) Don’t go yet! ( hái bù néng) Don’t touch it! ( bù zhjn) Don’t go on! ( bù yào) Don’t swear at people! ( bù xj) Don’t sleep on the sofa! ( bù kgyh) Don’t look for excuses! ( bù yào) Don’t borrow money from others. ( bù yào) Don’t wait for me. ( bù bì) Don’t smoke here. ( bù zhjn) Don’t tease him. ( bù yào)
14 Don’t stand up. ( bù yòng) 15 Don’t laugh at me. ( bù néng)
Pattern and vocabulary drill 20.2
20 Imperatives and exclamations
If sentence particle le is added to the 12 sentences below, it indicates that the speaker is getting increasingly impatient. He not only wants to bring the situation to a close, but does not want it to continue or occur again. With le, he sounds as if he were saying: ‘Enough is enough!’ Translate each of the following sentences first without le and then with le to bring out their subtle differences in meaning: bié ke Don’t cry! bié ke le Don’t cry any more! or Stop crying! 1 2 3 4 5 6 7 8 9 10 11 12
qhng bù yào xiào wi qhng bié kai wánxiào bù yào dfjià bié chfojià bié chfo bié chfo wi bié mà ta bù yào dgng ta bié chduyan bié hb jij bié kèqì zài jiàn
213
UNIT TWENTY-ONE Complements of direction and location (or destination)
Complements are those elements in a sentence which follow the verb (or adjective), apart from the object. They usually signify such meaning categories as direction, location, duration, result, manner, possibility, degree, etc. In this unit we are concerned with complements of direction and location. A The verbs lái ‘to come’ and qù ‘to go’ form the two basic complements of direction which are used after verbs of movement or action to indicate a direction ‘towards’ or ‘away from’ the speaker: (a) after verbs of movement pfo lái pfo qù fbi lái fbi qù
run over (here) run over (there) fly over (towards the speaker) fly away (from the speaker)
(b) after verbs of action ná lái ná qù dài lái dài qù
bring take bring with one take with one
gufngchfng shang fbi lái le bù shfo gbzi Quite a number of pigeons flew over/came flying to the square. qián yhjcng huì qù le The money was already remitted [to someone]. sheshu jì lái le hgn dud shèngdàn lhwù Uncle sent [us] (by post) a lot of Christmas presents.
214
zuótian chuán lái le jiùjiu che guó de xiaoxi The news of uncle’s going abroad came yesterday.
B lái or qù may be linked, in particular, to the following group of verbs to form a set of common disyllabic verbs of movement. These disyllabic verbs also function themselves as directional complements with either verbs of movement or verbs of action: lái ‘come’ (towards the speaker) jìn ‘enter’ che ‘exit’ shàng ‘ascend’
jìn lái che lái shàng lái xià lái
qù ‘go’ (away from the speaker) come in come out come up
xià
‘descend’
come down huí laí come back
huí
‘return’
guò
‘cross’
guò lái come over/ across
qh
‘rise’
qh lái
rise (from a lower position to a higher position)
jìn qù che qù shàng qù xià qù
21 Complements of direction and location (or destination)
go in go out go up
go down huí qù go back guò qù go over/ across qh qù is no longer used
Examples: (a) as independent verbs of movement ta jìn lái le qhng shàng lái ta che qù le tamen huí qù le tàiyáng che lái le wi bù gfn xià qù ta qh lái le
He came in (to the room). Please come up! He’s out. They have gone back. The sun came out. I dare not go down. He’s got up.
(b) as complements of direction following verbs of movement tamen gfn huíqù le ta bù gfn tiào xiàqù
They hurried back (to where they had come from). She did not dare to jump down.
215
21 Complements of direction and location (or destination)
huàr diào xiàlái le The picture fell down. chb kai guòqù le The car went past. tàiyáng shbng qhlái le The sun rose. (c) as complements of direction following verbs of action she fàng huíqù le
The books have been put back (where they were). The dishes were brought in. The Christmas cards have been sent (by post). The pictures were hung up. The coursework has been handed in. The money which had been lent was returned.
cài duan jìnlái le shèngdànkf jì cheqù le huàr guà qhlái le zuòyè jiao shàngqù le jiè cheqù de qián huán huílái le
Note: qhlái, xiàqù and xiàlái, as we have seen, may also be used as aspect markers (see Unit 15): ta chàng qhlái le nh kgyh zài zhèr zhù xiàqù chb tíng xiàlái le
He started singing. You can stay on here. The car came to a stop.
C When the verb has an object that indicates a location, it is placed between the verb and its directional complement lái or qù or between the two elements of a disyllabic complement of direction: (a) between the verb and
lái or
qù
ta jìn bàngdngshì lái le gbge chemén qù le
216
She came into the office. My elder brother is away. (lit. Elder brother went out of the door.)
xifo lh shàng tái qù le mama xià lóu lái le
Note:
Xiao Li went on to the stage. Mum came downstairs.
chemén ‘be away’ is a verb with an inbuilt object.
21 Complements of direction and location (or destination)
(b) between the two elements of a disyllabic directional complement (i) following a verb of movement mama pfo xià lóu lái
Mum came running downstairs. gdnggòng qìchb The bus kai guò qiáo qù went across the bridge. sheshu pfo huí jia (My) uncle has qù le gone home. gegu ziu jìn wezi (My) aunt walked lái le into the room. sdngshj pá shàng The squirrel shù qù le climbed up the tree. jiùshbngyuán tiào The life-guard jìn shuh li qù le jumped into the water. (ii) following a verb of action yàoshi fàng huí chduti li qù le The keys have been put back into the drawer. qián cún jìn yínháng qù le The money has been deposited in the bank. One cannot, for instance, say: *
ta jìn lái bàngdngshì le
*
sdngshj pá shàngqù shù le
(lit. She came into the office.) (lit. The squirrel climbed up the tree.)
217
21 Complements of direction and location (or destination)
If the object is not a location, it may precede or follow the monosyllabic directional complement lái or qù: jiùjiu dài le yc píng jij lái jiùjiu dài lái le yc píng jij (My) uncle brought a bottle of wine. sfosao jiè le lifng bf yhzi qù sfosao jiè qù le lifng bf yhzi (My) Elder brother’s wife has borrowed two chairs from us. If the directional complement is a disyllabic one, a non-location object may precede it or follow it as in the case of a monosyllabic directional complement. In addition a non-location object may go between the two syllables of the disyllabic directional complement as is shown in the third example: bàba ze le yc liàng xifo miànbaochb huílái bàba ze huílái le yc liàng xifo miànbaochb bàba ze huí yc liàng xifo miànbaochb lái Father has hired a mini-van. Note: In the last instance, the aspect marker le has to be dropped as it does not usually go between huí and lái. D Location (or destination) complements are usually formed by the verb zài ‘to be in/at’ or dào ‘to arrive in/at’ followed by a location phrase: (a) location yéye zhù zài chéng li yiu hgn dud rén zuò zài cfodì shang ycfu guà zài ycjià shang
Grandpa lives in town. There are a lot of people sitting on the grass. The clothes were hung on the coat-hangers.
(b) destination 218
gdnggòng qìchb kai dào qiáo bian
The bus went as far as the bridge.
wimen gfn dào huichbzhàn wi jia ban dào gdngyuán fùjìn qcngwa tiào dào shuh li qù le hfibào yóu dào àn shang lái le
We hurried to the station. We moved (home) to a place by the park. The frog jumped into the water. The seal swam on to the shore.
21 Complements of direction and location (or destination)
Note: In the last two examples above, we can see that qù and lái may also be integrated into a destination complement begun with dào, when a location object is present.
Exercise 21.1 Translate the following phrases into Chinese using directional complements: 1 2 3 4 5 6 7 8 9 10 11 12
go back come over here go up come down bring here go out come back take to get up go in go across come out
13 14 15 16 17 18 19 20 21 22 23 24
come back home drive over the bridge (to the other side) climb up the tree come down the hill bring to the classroom go out of the house run back to the office take back to the hospital jump into the swimming-pool go into the post office go across the street come out of the room
Exercise 21.2 Complete the Chinese translations with disyllabic directional complements: 1 The children have gone out. háizimen pfo 2 The clothes have fallen off the clothes-line.
le 219
liàngycshéng shang de ycfu diào
le
21 Complements of direction and location (or destination)
3 He lay down on the grass. ta zài cfodì shang tfng 4 The doctor has come in. ycshbng ziu
le
5 She just went past. ta ganggang ziu 6 Don’t throw it out of the window. bù yào rbng
chuang wài
7 The cups have been put back in the cupboard. bbizi fàng wfnguì li le 8 The teacher has gone back to the school. lfoshc pfo xuéxiào le 9 The kitten has jumped on to the bed. xifo mao tiào chuáng le 10 The dog jumped over the wall. giu tiào qiáng le 11 The letter has been dropped into the pillar-box. xìn yhjcng rbng yóuting 12 The ball did not go into the goal.
le qiú méiyiu tc
qiúmén
Exercise 21.3 Rephrase the following Chinese sentences, adding the location words shown in the brackets (note: in some cases a postposition may be needed), and then translate the rephrased sentences into English: xifo lh huí lái le ( jia) xifo lh huí jia lái le Xiao Li came home.
220
1
lfoshc ziu jìnqù le
2 3
fbijc fbi guòqù le wi pá shàngqù
4
háizimen pfo guòqù le
( túshegufn the library) ( shan the hill) ( shanpd the hillside) ( mflù the road)
5
tamen ziu cheqù le
( jiàotáng the church) ycshbng huí qù le ( ycyuàn the hospital) qcngwa tiào xiàqù le ( shuh the water) chb kai guòlái le ( qiáo the bridge) xifo jc zuan chelái le ( dànké the shell) xifo mao pá shàngqù le ( shù the tree) nifor fbi cheqù le ( lóngzi the cage) xuésheng ziu jìnlái le ( jiàoshì the classroom) lfoshj zuan huíqù le ( dòng hole) dùchuán kai guòqù le ( hé river)
6 7 8 9 10 11 12 13 14
21 Complements of direction and location (or destination)
Exercise 21.4 Fill in the blanks with an appropriate location or destination phrase in accordance with the English version provided, making use of the words given in the following list: yínháng lajcting liàngycshéng xiangzi bcngxiang bfoxifnguì xínglijià hfi bian tian shang chéng wài hú shang wedhng shang
bank garbage bin clothes-line box/trunk refrigerator strongbox/safe luggage rack the seaside the sky out-of-town areas surface of the lake top of the roof
1 ycfu ddu zhuang . . . qù le All the clothes have been packed into the box. 2 qián ddu cún . . . le All the money has been deposited in the bank. 3 lajc ddu dào . . . qù le All the rubbish has been tipped into the garbage bin.
221
21 Complements of direction and location (or destination)
4 nh de xíngli ddu fàng . . . le All your luggage was put on the luggage rack. 5
(
)
xh hfo de ycfu ddu liàng . . . le All the washing has been hung on the clothes-line [to dry]. 6 zhj hfo de cài ddu gb . . . le All the cooked dishes were left in the fridge. 7
shiushi ddu fàng ... All the jewels are in the safe.
8
tamen ban . . . lái le They have moved into the town.
9
qìchb yczhí kai . . . The car went straight to the seaside.
10
qìqiú yczhí shbng . . . qù le The balloon rose straight into the sky.
11
weya fbi . . . qù le The crow flew to the top of the roof.
12 wi de màozi ràng fbng ggi chuc . . . qù le My hat was blown into the lake by the wind.
Pattern and vocabulary drill 21.1 Translate into Chinese the English sentences below, making sure you use either monosyllabic or disyllabic directional complements with or without a location object. An example is given: The children went in. háizimen jìn qù le The children went into the classroom. ( ) háizimen (ziu) jìn jiàoshì qù le
222
1 2 3 4 5 6 7 8
The The The The The The The The
engineers went in. adults went out. boys went out. girls came back. Chinese friends came in. guests went back. Chinese guests came back. neighbours came out.
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26. 27 28 29 30
The patient came into the ward. Grandma took younger sister and brother to the zoo. The athletes climbed up the mountain. (mountain shan) Father came home after work. The kitten hid itself behind the sofa. (hide dui) A dog came running over the bridge. A crowd of people came walking into the shop. Elder brother came running upstairs. The little girl swam across the river. (swim yóu; river hé) The pigeon flew up into the tree. The moon came out. (moon yuèliang) The boy jumped into the water. The squirrel climbed down the tree. Mother hurried to the railway station. A group of boys came running on to the street. There rose many a balloon. The pen fell into the river. They moved into the village. The manager came walking out of his office. The students stood up. Everybody sat down. The life-guard came swimming back to the shore. (shore àn bian)
21 Complements of direction and location (or destination)
Pattern and vocabulary drill 21.2 Following the model, form two sentences in Chinese using each of the ten sets of words given below. For the first, introduce the location expression; for the second, add the action verb so that the original action verb becomes a direction complement. ta jìn lái le He came in. office: ta jìn bàngdngshì lái le He came into the office. walk hurriedly: ta pfo jìn bàngdngshì lái le He walked hurriedly into the office. 1
ta jìn qù le He went in. walk hurriedly 2 ta che qù le He went out. classroom walk 3 ta huí qù le He went back. home hurry 4 ta xià lái le He came down. stairs run room
223
21 Complements of direction and location (or destination)
5 6 7 8 9 10
224
ta guò qù le He went over (to the other side). drive (a car) ta shàng qù le He went up. tree climb ta guò lái le He came over (to this side). river swim ta che lái le He came out. house rush/dash ( chdng) ta guò qù le He went over (to the other side). fence ( zhàlán) jump ta shàng lái le He went up. stage/platform walk hurriedly bridge
UNIT TWENTY-TWO Complements of result and manner
This unit deals with complements of result and what are generally called complements of manner. These complements, like those of direction and location or destination, are invariably positioned after verbs. A Complements of result can be either adjectives or verbs and they imply that a result of the action of the verb has been achieved: (a) Adjectives dàjia ddu zuò hFo le nh cai cuò le nhmen tcng qCngchu le ma
Everybody has sat/settled down. You have guessed wrongly. Did you hear that clearly?
(b) Verbs tamen ddu zhàn zhù le nh kàn jiàn ta le ma wi xué huì kaichb le nh tcng dIng le ma
They all stood still. Did you see her? I have learnt to drive. Did you understand (what was said)?
B The objects of verbs with complements are regularly shifted to a preverbal position where they become the topic of the sentence and naturally have definite reference: wénzhang wi xig wán le I have finished writing the essay. zhudzi ca gAnjìng le The table has been wiped (clean). gdngzuò zuò wán le The work was done.
225
22 Complements of result and manner
nèi gè wèntí nh xifng qCngchu le méiyiu Have you thought out that question thoroughly? ta de huà wi ddu tcng míngbai le I understood every word he said. Note: The seemingly more logical verb-object order is certainly not ungrammatical but is in fact far less usual in everyday speech or writing: wi xig wán le wénzhang le I have finished writing the essay. C Complements of result by definition imply completed action and/or change of circumstances and therefore naturally occur with le. (For discussion of le as completed action, see Unit 15; for a detailed analysis of le as a ‘change-of-state’ sentence particle, see Intermediate Chinese, Unit 8.) For example, ta hb zuì le ycfu shài gAn le xìn jì zIu le
He’s drunk. The clothes are dry. The letter has been sent.
It follows that the negation of these statements will involve the use of ( ) méi(yiu) without le since the action has never been completed or the state achieved: ta méi hb zuì ycfu méi shài gAn xìn hái méi jì zIu
He isn’t drunk. The clothes are not dry. The letter has not been sent yet.
D The complement of manner in its simple form consists of de followed by an adjective, usually with a degree adverb or negator: ta xué de hgn hfo ta pfo de fbicháng kuài nh shud de hgn duì ta shuì de tài wfn 226
He studies very well. She runs/ran extremely fast. You are/were quite right (in what you said). He goes/went to bed too late.
shéi/shuí lái de zuì zfo ta xig de bù hfo ta jifng de bù tài qcngchu
Who arrived earliest? He writes/wrote badly. She does/did not put it too clearly.
22 Complements of result and manner
Note: In these cases a degree adverb is almost indispensable and that, as a state or situation is being described with no reference to a previous situation, sentence le is not generally used. Phrases with reduplicated words, which have phonetic resonance (phonaesthemes) make natural complements of manner: ta jifng de jibjiebaba de ta hb de zuìxenxen de
She hemmed and hawed (as she spoke). He (drank till he) was tipsy.
E More complex forms of the complement of result or manner entail the placing of a verb phrase or a clause after the de. These complements in fact normally convey a sense of resultant state, with the difference between result and manner being conveyed by the presence of the sentence particle le for result and by its absence for manner. The verb phrase usually follows an adjectival predicate, but the clause can come after an adjectival or verb predicate: (a) Verb phrases ta gaoxìng de tiào qhlái (manner) He jumped for joy. (lit. he was [so] pleased that he jumped up) ta téng de dfo xiàqù le (result) She collapsed with the pain./She was in such great pain she collapsed. mama jí de ke qhlái le (result) Mother was so anxious she started to cry. (b) Clauses tàiyáng zhào de wi yfn yg hua le The sun was so bright it dazzled my eyes. (lit. the sun shone [so that] my eyes were dazzled)
(verb) 227
22 Complements of result and manner
ta gao de shiu néng pèng dào tianhuabfn le (adjective) He is so tall he can touch the ceiling with his hands. ta zhàn de tuh ddu suan le She stood there for so long her legs began to ache.
(verb)
tamen chàng de sfngzi ddu yf le They sang until they were hoarse.
(verb)
ta gfn lù gfn de hàn zhí wfng xià liú (verb) He hurried ahead till sweat was pouring down/till he was sweating all over.
Note: As can be seen from the above, sentences that have clause complements more often imply result rather than manner, and le is therefore regularly present.
F If the verb in a sentence with a complement of manner is of a ‘verb + object’ form (e.g. yóuying ‘swim’; chànggb ‘sing’; liáotianr ‘chat’), the verb is repeated before the complement is added: ta chànggb chàng de sfngzi ddu yf le She sang until she was hoarse. ta yóuying yóu de hgn màn He swims very slowly./He is a slow swimmer. One cannot say: *
228
ta chànggb de sfngzi ddu yf le
Note: You may have noticed that most of the sentences containing ‘verb + complement’ expressions end with le. This is because the primary function of the sentence particle le is to indicate ‘change’ and the notion of a newly emerged result is naturally consistent with the notion of a changed situation. Examples without le, are statements of a present fact and therefore focus on manner rather than result. Notice the change in meaning if le is used in the following:
22 Complements of result and manner
Compare: ta yóuying yóu de hgn màn He swims very slowly./He is a slow swimmer. And ta yóuying yóu de hgn màn le He no longer swims as fast as before./ He is a much slower swimmer now than he used to be.
Exercise 22.1 Complete each of the following Chinese sentences with an appropriate complement of result or manner to match the English sentence: 1 The dog ran very fast. xifo giu pfo 2 The clothes have been washed (clean). ycfu xh le 3 I have understood this article. zhèi pian wénzhang wi kàn 4 Who writes Chinese the best?
le
shéi/shuí hànzì xig 5 The rice is cooked. fàn zhj le 6 Xiao Wang can speak English very fluently. xifo wáng ycngyj shud 7 All the children have sat down. háizimen ddu zuò le 8 My daughter has learned how to play the piano. wi ns’ér xué tán gangqín le 9 I managed to buy a good book. wi mfi le yc bgn hfo she 10 The grass dried (in the sun). cfo shài le 11 Mother went to bed very late. mama shuì 12 Did you see him? nh kàn ta le ma
229
22 Complements of result and manner
13 The kitten jumped really high. xifo mao tiào 14 The teacher has explained this problem extremely clearly. zhèi gè wèntí lfoshc shud 15 You are perfectly correct. nh shud 16 The car stopped. chbzi tíng
le
Exercise 22.2 Form sentences by matching an appropriate clause complement of manner (or resultant state) from the list on the right with a main clause from the list on the left. Naturally de will be needed at the beginning of the complement. Remember that with ‘verb + object’ constructions, the verb needs to be repeated before it can be followed by a complement. When you have constructed the sentences, translate them into English: 1 2 3
wi sfngzi téng ta yóuying ta pfo lù
4
6
lfoshc shudhuà wi yfnjing hua wi gaoxìng
7
gbge zuì
8
xuésheng xig zì mèimei ke ta kai wánxiào
5
9 10
tuh ddu suan le sfngzi ddu yf le fàn yg chc bu xià le shéi/shuí yg bù rènshi le dàjia ddu xiào qhlái le huà yg shud bu chelái le qì yg chufn bu guòlái le shénme yg kàn bu qcngchu le shiu yg suan le yfnjing ddu hóng le
Exercise 22.3
230
Complete the following Chinese sentences by choosing the appropriate verb or adjective from the list given (note: in some cases some form of modification is needed) to complete the translations of the English sentences:
piàoliang zuì dào duì
bfo dfo pò míngbai
hfo ganjìng zfo wfn
nh méi cai You didn’t guess it right. 2 nèi bgn she wi méi mfi I did not manage to obtain that book. 3 nèi tian dàjia ddu hb Everybody got drunk that day. 4 nèi tian dàjia ddu chuan That day everyone was dressed up beautifully. 5 ta hái méi chc He has not eaten his fill yet. 6 diànshìjc yg xie le The television set has also been repaired. 7 ta pèng le chuangtái shang de huapíng She knocked over the vase on the window sill. 8 gébì de háizi nòng le wi háizi de wánjù Next door’s child broke my child’s toy. 9 chuanghu wi ddu ca I have wiped all the windows (clean). 10 zhèi gè wèntí nh nòng le méiyiu Have you thrashed out this problem? 11 mama jcn zfo qh lái Mother got up very early this morning. 12 bàba zuó wfn shuì Father went to bed very late last night.
22 Complements of result and manner
1
le
le
Exercise 22.4 Translate the following into Chinese: 1 2 3 4
They danced beautifully. The life-guard swam extremely fast. The student read slowly. The child ate a lot.
231
22 Complements of result and manner
5 6 7 8 9 10
Everybody slept soundly. The actor sang very badly. We ran till we were too tired./We ran so much we were really tired. The athlete jumped really high. (My) Elder brother didn’t drink much. My fellow student didn’t speak fluently.
Pattern and vocabulary drill 22.1 You will have perhaps noticed that when a complement of result is in the form of a clause, ddu or yg is always present to refer back to the subject or topic of the clause for emphasis. It is not ungrammatical to leave them out, but the sentence as a result sounds less idiomatic. Formulate idiomatic sentences from the 12 sets of words below on the basis of the following: subject: jigjie ‘elder sister’ action verb: dfzì ‘to type’ result: shiu ‘hand’, suan ‘sour; to ache’ jigjie dfzì df de shiu ddu suan le Elder sister typed till her hands ached.
232
1 subject: mèimei ‘younger sister’; action verb: tiàoshéng ‘to skip with a rope, play with a skipping rope’; result: jifo ‘foot; feet’, téng ‘to ache, to hurt’ 2 subject: dìdi ‘younger brother’; action verb: pfobù ‘to jog’; result: tuh ‘leg’, rufn ‘soft; (muscles) to lack strength’ 3 subject: lfoshc ‘teacher’; action verb: jifngkè ‘to teach lessons’; result: hóulóng ‘throat’, téng ‘to ache, to hurt’ 4 subject: péngyoumen ‘the friends’; action verb: liáotian ‘to chat’; result: sfngzi ‘throat, voice’, yf ‘to be hoarse, to lose one’s voice’ 5 subject: nèi gè háizi ‘that child’; action verb: ke ‘to cry, to weep’; result: yfnjing ‘eyes’, hóng ‘red, (eyes) bloodshot’ 6 subject: wimen ‘we’; action verb: bbi xíngli ‘to carry luggage on one’s back’; result: bèi ‘the back’, téng ‘to ache, to hurt’ 7 subject: mama ‘mother’; action verb: xig xìn ‘to write letters’; result: shiu ‘hand’, rufn ‘weak; lose strength’ 8 subject: jigjie ‘elder sister’; action verb: la xifotíqín ‘to play the violin’; result: shiuzhh ‘fingers’, chexuè ‘to bleed’ 9 subject: gbge ‘elder brother’; action verb: tán gangqín ‘to play the piano’; result: shiuzhh ‘fingers’, suanténg ‘to ache’
10 subject: bàba ‘father’; action verb: shudhuà ‘to talk’; result: kiu ‘mouth’, gan ‘dry’ 11 subject: ygye ‘grandfather’; action verb: kàn bàozhh ‘to read the newspaper’; result: yfnjing ‘eyes’, hua ‘(eyes) to blur’ 12 subject: nfinai ‘grandmother’; action verb: chc pínggui ‘to eat apples’; result: yáchh ‘teeth’, téng ‘to ache, to hurt’
22 Complements of result and manner
Pattern and vocabulary drill 22.2 Using the model, construct versions ‘b’, ‘c’ and ‘d’ in Chinese for each of the twelve ‘a’ sentences given below. a b c
ycfu shài gan le The clothes are now dry. ycfu méi shài gan The clothes are not yet dry. ycfu shài de bùgòu gan The clothes are not dry enough.
d
ycfu shài de bù tài gan The clothes are not too dry.
1 a ycfu xh ganjìng le The clothes have been washed clean. 2 a wénzhang xig hfo le The essay is completed (and presumably well written). 3 a wèntí shud qcngchu le The question has been thoroughly explained. 4 a fàn zhj shú/shóu le The rice is well cooked. 5 a chb xie hfo le The car has been repaired (and presumably is now drivable). 6 a wèntí yánjie qcngchu le The problem has been thoroughly studied. 7 a tóufa jifn dufn le The hair has been cut short. 8 a gbcí bèi shú/shóu le The lines (of a song) have been well committed to memory. 9 a zhudzi ma ganjìng le The table has been wiped clean. 10 a qíngkuàng lifojig qcngchu le The situation has been thoroughly investigated. 11 a ddngxi fàng zhgngqí le The things are arranged in good order. 12 a fángjian shdushi ganjìng le The room has been tidied up. 233
UNIT TWENTY-THREE Potential complements
A Simple complements of direction and result may in fact be extended with the help of de and bù to indicate whether the said direction or result is likely or unlikely to take place or be attained. These complements may be called potential complements: (a) potential complements of result hbibfn shang de zì nh kàn de qcngchu ma Can you see the words on the blackboard clearly? ta shud de huà nh tcng de ding ma Can you understand what he said? D wi zuótian wfnshang shuì bu zháo I could not sleep last night. Note: In the last example the pronunciation of D is zháo which is here used as a verb meaning ‘to achieve a desirable result’. Virtually all complements of result, whether verbal or adjectival, can be used in the potential form:
234
kàn de jiàn kàn bu jiàn zuò de wán zuò bu wán bàn de dào bàn bu dào xie de hfo xie bu hfo shud de míngbai shud bu míngbai xh de ganjìng xh bu ganjìng
can see cannot see can finish (the job) cannot finish (the job) can be managed cannot be managed can be repaired cannot be repaired can be explained clearly cannot be explained clearly can be washed (clean) cannot be washed (clean)
(b) potential complements of direction (in terms of space or time) nh hái chc de xià ma Can you eat any more?
23 Potential complements
wi zhbn de chc bu xià le Honestly, I can’t eat any more. wi zhàn bu qhlái I could not stand up. lhmiàn rén tài dud | wimen jìn bu qù There were so many people inside. We [simply] could not get in. zhèr yiu tiáo gdu | nh tiào de guòlái ma There’s a ditch here. Can you jump over (here)? xiangzi guan bu shàng le The box cannot be closed. (e.g. too full; the lock is broken; etc.) ( ) ta dai bu xiàlái He cannot stay on. (e.g. He has been called away on business; always wants to be on the move; etc.) When directional complements are used in a potential form with de and bù, they often acquire a metaphorical meaning beyond their original sense of physical direction: ta shud bu xiàqù le She could not carry on (speaking). (e.g. She was choked by emotion; forgot what to say; etc.) tài guì le | wi mfi bu qh [It’s] too expensive. I [just] can’t afford [it]. B Some complements of result or direction exist only in the potential form (as can be seen from the last example cited immediately above). Other examples are: positive ziu de dòng lái de jí qù de chéng xíng de tdng tán de shàng
can walk on be in time for can (ultimately) go will do/work can be regarded as
235
23 Potential complements
kàn de qh hé de lái shud de guòqù zuò de xià jigjué de lifo
think highly of can get along with be justifiable can seat/have room for can be resolved
ziu bu dòng lái bu jí qù bu chéng xíng bu tdng tán bu shàng kàn bu qh hé bu lái shud bu guòqù zuò bu xià jigjué bu lifo
cannot walk (any more) be too late for cannot (ultimately) go won’t do/work can’t be regarded as look down upon cannot get along with cannot be justified does not have room for cannot be resolved
negative
Note: In the last two examples xià does not mean the same as in the non-potential form zuò xià ‘sit down’ and that , pronounced as lifo, which is widely used as a complement, only exists as a potential complement meaning ‘to do something successfully’. Sentence examples: ta zhèi gè huài xíguàn gfi de lifo ma Can this bad habit of his be changed/corrected? tamen lifng gè rén hé bu lái They too do not get on with each other. nh bié kàn bu qh ta Don’t you look down upon him. wi gfn bu shàng ta I can’t catch up with her. In some cases, there are only negative potentials:
236
ba bu de be more than willing/be only too anxious to guài bu de no wonder jcn bu zhù cannot help but mifn bu lifo can do nothing but/cannot avoid dà bu lifo if the worst comes to the worst (lit. it can’t be worse than)
These negative potentials are usually followed by verbal or clausal objects: dàjia jcn bu zhù xiào qhlái le Everybody could not help laughing.
23 Potential complements
ta ba bu de dàjia ddu xufn ta He longed for everybody to vote for him. dà bu lifo ta bù tóngyì At the worst, she will disagree. [That’s all.] C
Potential complements, as can be seen from above, may take objects: nh tcng de ding éyj ma Do you understand Russian (when you listen to it being spoken)? wi xifng bu qh nèi jiàn shìr lái I could not/cannot recall that (matter). wimen gfn de shàng nèi ban huichb ma Can we catch that train? zhèr zhù de xià wj gè rén ma Can five people be housed here?
D The distinction between the potential complements and the modal verbs néng and kgyh is that the modal verbs imply some degree of subjective influence while the potential complements indicate that external circumstances are the deciding factor. Compare: wi bù néng qù I can’t go [because I don’t want to/I don’t think it would be appropriate]. wi qù bu lifo I can’t go [because I am ill/the last train has gone etc.]. wi xiànzài hái bù kgyh chc ddngxi I don’t think I should eat anything now. (e.g. after the workout) wi xiànzài hái chc bu lifo ddngxi I don’t think I am able to eat anything now. (e.g. after the operation) E Potential complements may assume two different forms in an affirmative-negative question. Either:
237
23 Potential complements
nh míngtian lái de lifo lái bu lifo or: nh míngtian lái bu lái de lifo Can you come tomorrow or not? To add emphasis, the adverb
jiejìng ‘after all’ can be used:
nh míngtian jiejìng lái bu lái de lifo Can you come tomorrow after all?
Exercise 23.1 Complete the following sentences with the appropriate potential complements: 1
nh hái ziu de
ma
Can you walk on? 2 zhèi tiáo gdu zhème kuan | wi tiào bu This ditch is too wide for me to jump over. 3
238
zhèi jiàn shìr nh hái xifng de ma Do you still remember that? 4 zuó wfn wi shuì bu I couldn’t sleep last night. 5 nh hái chc de ma Can you eat any more? 6 zhèi gè huài xíguàn nh gfi de ma Can you do something about (change) this bad habit of yours? 7 zhème guì | wi mfi bu It’s so expensive, I can’t afford it. 8 wi zhfo bu wi de yàoshi le I can’t find my keys. 9 xiànzài hái lái de gfn nèi ban huichb ma Have we got enough time to catch the train? 10 zhèi gè gdngzuò wimen jcntian zuò de ma Will we be able to finish this job today?
Exercise 23.2 Translate the phrases below into Chinese using potential complements: 1 2 3 4 5 6 7 8 9 10
23 Potential complements
can eat one’s fill can’t stand up can’t drink any more can’t be washed (clean) can sit comfortably be too high to reach can’t see clearly can memorize (it) can get on with (someone) can get by (survive)
Exercise 23.3 Provide appropriate potential complements in each of the following sentences: 1
mén
le
The door can’t be closed. 2 jcntian tian ycn | ycfu ma It’s cloudy today. Will the washing get dry? 3 wimen rén zhème dud | wezi li There are so many of us. Can the room seat us all?
ma
4 wi hgn lèi | zhbn de I’m very tired. Honestly I can’t go on.
le
5 wimen hái nèi ban qìchb ma Are we still in time to catch that coach? 6 wi rènwéi zhè/zhèi zhing zuòff I don’t think this method will work. 7 tamen lifng gè rén Can the two of them get along with each other? 8 nh nèi jiàn shìr ma Can you recall that incident?
239
23 Potential complements
9 wi kàn le ta yc yfn I could not help casting him a glance. 10 wi de huà nh ma Can you understand what I’m saying?
Exercise 23.4 Translate the following sentences into Chinese, using a potential complement or a modal verb as appropriate. Do not translate the phrases in brackets. 1 2 3 4 5 6 7 8 9 10
I can’t go to bed yet (as I’ve got some more work to do). I couldn’t sleep (because I was worried). I can’t buy it today (because I can’t carry it). I can’t afford it. I can’t tell you (because it’s confidential). I can’t tell you (because I’ve forgotten). I can’t do it (because I haven’t the ability to). I can’t do it (because I don’t think it’s right). I couldn’t go on (talking – because I was choked by emotion). I couldn’t go on (talking – because I was disturbing other people).
Pattern and vocabulary drill 23.1 Translate the following short dialogues into Chinese, using either modal verbs or potential complements: 1 Can you see those words? ( zì ‘words’) I am sorry I can’t see a few of the words on the left. 2 Can you help me? Of course, I can. ( dangrán ‘of course’) 3 Can he afford those two pairs of jeans? Of course, he can. His father is rich. 4 Can you finish your essay tonight? ( lùnwén ‘essay’) I am sorry I can’t. I have a meeting to attend. 5 Can the patient stand up? I am afraid he can’t. ( kingpà ‘(I’m) afraid’) 6 Can you finish this piece of cake? Honestly, I can’t eat any more. 240
7 Can your car be repaired? I am afraid it is beyond repair. 8 Can we get in? I am afraid we can’t. There are so many people inside. 9 Can you understand what I say? ( tcng de ding ‘to listen with understanding’) I am sorry I can’t. I can only understand English. 10 Can you catch that bus? Of course, I can. I can run very fast indeed.
23 Potential complements
Pattern and vocabulary drill 23.2 Reword the following questions using the two affirmative-negative forms with potential complements: nh míngtian qù de lifo ma Can you go tomorrow? nh míngtian qù de lifo qù bu lifo nh míngtian qù bù qù de lifo 1 2 3 4 5 6 7 8
9 10
nh míngtian ziu de lifo ma Can you go/leave tomorrow? hbibfn shang de zì nh kàn de qcngchu ma Can you see the words on the blackboard clearly? ta shud de huà nh tcng de ding ma Can you understand what she says? zhème guì de ycfu nh mfi de qh ma Can you afford clothes as expensive as these? zhème dud rén zuò de xià ma Can so many people be seated here? nh hái chc de xià ma Can you eat any more? zhè gè diànnfo hái xie de hfo ma Can this computer still be repaired? nh shud nèi zhang xìnyòngkf hái zhfo de dào ma Do you think that credit card can still be found? nh shud nh míngtian gfn de huílái ma Do you think you can get back in time tomorrow? nh shud zhdngwén wi xué de huì ma Do you think I will master Chinese in the end? 241
UNIT TWENTY-FOUR Coverbal phrases
A A coverb (or preposition) with its attendant noun precedes the main verb or adjective of the sentence, setting the scene for the action or situation. That is to say it indicates to whom, for whom, the means by which, the purpose for which, the direction in which, etc. something is to be done or happens. The term coverb is perhaps preferable to preposition as the words in this category have a verb basis and can be used separately as verbs. The zài location phrases discussed in Unit 13 are, in fact, coverbal phrases; as are the comparison phrases with bh in Unit 12.
ta zài túshegufn kàn she ( He is reading in the library.
zài túshegufn coverbal phrase)
ta bh ta péngyou dà san suì ( bh ta péngyou coverbal phrase) She is three years older than her friend. Adverbs of time, negators, etc. are generally placed before the coverb:
ta ycguàn duì wi hgn hfo ( duì wi coverbal phrase) He has all along been very good (kind/respectful) to me./He always treats me very well. ta méi ggi wi lái xìn ( She didn’t write to me.
ggi wi coverbal phrase)
The main coverbs are: B
242
hé/
gbn/
yj/
tóng ‘with’:
wi gbn nh tántán zhèi gè wèntí I’ll discuss this matter with you.
24 Coverbal phrases
ta tóng nh hgn hfo She gets on very well with you. These four coverbs are often used with of ‘together with’:
ycqh to emphasize the notion
nh gbn wi ycqh qù kàn diànyhng ma Are you going to the cinema with me? lfo zhang hé xifo lh ycqh zuò shíyàn Old Zhang and Little Li did the experiment together. As we have seen (Unit 12), these coverbs may also be used with ycyàng to express similarity:
zhèi gè shiubifo tóng nèi gè shiubifo ycyàng zhjn This watch is as accurate as that one. gbge yj dìdi ycyàng cdngming The elder brother is as clever as the younger brother. C (i)
ggi/
wèi/
tì ‘for/to’ all in the sense of ‘rendering a service to’:
ggi ‘for/to’ wi jcn wfn ggi nh df diànhuà I’ll ring you this evening. ta méiyiu ggi wi xig xìn She didn’t write to me. wi ggi ns’ér mfi le yc tái diànnfo I bought a computer for my daughter.
(ii)
wèi ‘for’ implying ‘for someone’s benefit; in someone’s interest’ / He held a party for me.
ta wèi wi kai le yc gè cháhuì/jijhuì
mama wèi érzi caoxcn The mother is worried about her son. (iii)
tì ‘for/on behalf of’ ta tì ta huí le hgn dud xìn He replied to a lot of letters on her behalf.
243
24 Coverbal phrases
wi tì línje gb cfo I mowed the lawn for my neighbour. D
(i)
duì ‘to/at’, implying the idea ‘face to face’, is often used in conjunction with verbs such as shud ‘say’, xiào ‘smile’: ... ta duì wi shud . . . ‘ . . . ’ she said (to me). ( ) ta duì wi xiào le (yc) xiào He gave me a smile./He smiled at me.
(ii)
duì meaning ‘to(wards)’ is also often linked with adjectives expressing ‘attitude or frame of mind towards something or someone’ such as yiuhfo ‘friendly’, rèqíng ‘warmhearted; kind’, fùzé ‘responsible’: ta duì gdngzuò hgn fùzé He is very responsible about his work. wáng xiansheng duì xuésheng hgn rèqíng Mr Wang is very kind to his students. jigjie duì rén hgn yiuhfo My elder sister is very friendly towards people.
E
(i)
wàng or wfng/
xiàng/
cháo ‘towards/in the direction of’:
chbzi xiàng jcchfng kai qù The car headed for the airport. xifo lh wàng/wfng jiàoshì pfo qù Xiao Li hurried towards the classroom. tamen cháo jiàotáng ziu lái They came towards the church. (ii)
cháo/ xiàng can also mean ‘at/to’ in the sense of ‘facing somebody or something’. cháo is used with either static or dynamic action whereas xiàng is usually employed only when the action is dynamic: D xifohái cháo tiankdng wàng zhe The child gazed at the sky.
244
ta cháo wi difndifn tóu He nodded to me.
ta xiàng wi zhao shiu She beckoned to me.
24 Coverbal phrases
One does not say: D ta xiàng nán zhàn zhe * (lit. He is standing facing south.) wàng/wfng, on the other hand, must involve movement: ta wàng/wfng ycyuàn ziu lái She came towards the hospital. One cannot say: D ta wàng/wfng ycyuàn wàng zhe * (lit. She is looking in the direction of the hospital.) F
dào ‘to’ is used with objects indicating destination (see Unit 21): lfo zhang dào ycyuàn qù kànbìng Lao Zhang went to the hospital to see the doctor. wimen dào zhdngguó qù ffngwèn We went on a visit to China. tamen dào bówùgufn lái canguan They came to the museum for a visit. Note: As can be seen in the above examples, the coverb dào ‘to’ often occurs with the directional verbs lái or qù followed by another verb indicating purpose. dào may also be used with time expressions to mean ‘up to; until’: ta dào xiànzài hái méi lái Up till now he has not turned up./He has not turned up yet. jcnglh dào zuótian cái huí lái The manager did not come back till yesterday. wimen dào xià gè yuè jiù kgyh wánchéng zhèi gè rènwu le We shall be able to accomplish this task by next month.
245
24 Coverbal phrases
cóng ‘from (place); since (time)’
G (i)
cóng ‘from (place)’ is used either with verbs of movement (e.g. qù ‘go’; lái ‘come’; chefa ‘set off/set out’; qhchéng ‘depart’) or with verbs which incorporate a directional complement: ta cóng zhdngguó lái He came from China. wi cóng lúnden chefa I set out from London. wi cóng ycguì li ná che yc jiàn dàyc lái I took a coat out of the wardrobe. ta cóng kiudài li tao che yc bàng qián She took a pound from her pocket.
(ii)
cóng ‘since (time)’ often occurs together with qh or ‘start’, and also in conjunction with dào ‘till/to’:
kaishh
wi cóng qùnián qh jiù zài zhèi gè xuéxiào jiaoshe le I have been teaching at this school since last year. ta cóng shàng gè xcngqc kaishh chcsù le She became a vegetarian last week. (lit. Beginning from last week she started eating vegetarian food.) wi cóng shàngwj dào xiànzài méi chc guo ddngxi I haven’t eaten anything since this morning. (lit. from morning till/to now) H lí expresses the idea of ‘distance from (a place)’. (Note that cóng cannot mean ‘distance from’.) wi jia lí dàxué bù yufn My house is not far from the university. mànchéng lí lìzc hgn jìn Manchester is close to Leeds. 246
( ) lúnden lí zhèr yiu èr bfi dud ycnglh (lù) London is over two hundred miles from here.
I
24 Coverbal phrases
yóu ‘up to/by’ conveys the idea of ‘responsibility’: zhèi jiàn shì yóu wi fùzé I’ll be responsible for this. nèi xiàng gdngzuò yóu ta qù bàn That piece of work is up to him to handle/deal with. yóu, like
cóng, may also be used to mean ‘from (a place/time)’:
wimen yóu lúnden chefa We set off from London. ycngguó xiàlìng shíjian yóu shàng gè xcngqc jiéshù British Summer Time ended last week. yóu, however, cannot be used with postpositional phrases. Note: For example, One cannot say: * sdngshj yóu dà shù xià zuan chelái (lit. The squirrel came burrowing out from under a big tree.) yóu, like cóng ‘from’, can be used in conjunction with specify a period of time:
dào to
shangdiàn yóu shàngwj jij difn dào xiàwj wj difn yíngyè The shop is open from 9 a.m. to 5 p.m. yóu can also mean ‘by; out of’ to identify members of a group or components of a unit: zúqiúduì yóu shí yc gè duìyuán zjchéng The football team consists of 11 players. shuh yóu qcng hé yfng héchéng Water is composed of hydrogen and oxygen. J
yú ‘in; on; at’ is generally used with years or dates: ta yú yc jij jij wj nián bìyè He graduated in 1995.
247
24 Coverbal phrases
tdngzhc yh yú jcntian shàngwj fache The circular was issued this morning. huichb yú shí san difn líng wj fbn dàodá The train arrives at 1:05 (five past one). K yán ‘along(side)’, is used with monosyllabic nouns to describe a location: yán àn ddu shì shùmù There are trees all along the river. yán jib ddu shì shangdiàn There are shops all along the street. D yán zhe ‘along’, is employed when movement is involved: D D
ta yán zhe hé bian sànbù
She went for a walk along the river.
qìchb yán zhe dàlù xíngshh
The car was going along the main road.
L Some of the coverbs above (as well as zì ‘from’) may sometimes be used immediately after the main verb (see Unit 21 D): zhèi ban chb kai wfng bgijcng This train/coach goes to Beijing. zhèi ban fbijc fbi wfng shànghfi This is the flight for Shanghai. (lit. this plane flies to Shanghai) nèi sdu chuán tíngbó zài gfngkiu That ship is (lying) at anchor in the harbour. ta yczhí shuì dào zhdngwj She slept right through till noon. ta yckiuqì gfn dào huichbzhàn He got to the railway station in one breath. zhèi wèi xiansheng lái zì jianádà This gentleman is from Canada.
Exercise 24.1 248
Complete the following Chinese sentences with hé/ cháo/ wàng or duì to match the English:
gbn,
xiàng/
1
2 3 4 5 6 7 8
dàjia ta de jiànyì bifoshì zàntóng Everybody agreed to his suggestion. ta yhqián ycyàng cdngming She is as clever as she always was. nh mgi tian shéi ycqh xuéxí Who do you study with every day? qìchb diànyhngyuàn kai qù The car headed in the direction of the cinema. xifo lh bgijcng hgn shúxc/shóuxc Xiao Li knows Beijing very well. xuésheng túshegufn ziu qù The students walked towards the library. ta chuang wài kàn le ycxià He glanced out of the window. ta bàba ycqh zhù She lived with her father.
24 Coverbal phrases
Exercise 24.2 Complete the Chinese sentences below with appropriate: 1
wèi,
wimen ddu gaoxìng We congratulate you on this happy occasion.
tì or
ggi as
nh de xhshì
2 nh wi xifo lh df gè diànhuà | hfo ma Could you phone Xiao Li for me please? 3 ta mgi lifng gè xcngqc érzi xig yc fbng xìn He writes a letter to his son every two weeks. 4 bfomj ta kan háizi The nanny looked after her children. 5 ta ns péngyou mfi le yc tái ycnxifng He bought a hi-fi for his girlfriend. D 6 ta zhèi gè wèntí shuì bu zháo jiào She could not sleep because of this problem. 7 ta péngyou xh ycfu She did the washing for her friend. 8 xifo lh ta fùqin danxcn Xiao Li was worried about her father.
249
24 Coverbal phrases
Exercise 24.3 Identify in the examples below which of the sentences in Chinese is the correct translation of the English: 1 In which direction shall we go? wimen duì ngi gè fangxiàng ziu wimen cháo ngi gè fangxiàng ziu 2 She is very responsible about her work. ta tì gdngzuò hgn fùzé ta duì gdngzuò hgn fùzé 3 This book is very useful for my studies. zhèi bgn she duì wi xuéxí hgn yiuyòng zhèi bgn she gbn wi xuéxí hgn yiuyòng 4 Xiao Li is talking to Miss Shi (the teacher). xifo lh zhèngzài duì shí lfoshc tánhuà xifo lh zhèngzài gbn shí lfoshc tánhuà 5 He nodded to me. ta wàng wi difndifn tóu ta cháo wi difndifn tóu 6 We should learn from him. wimen ycnggai xiàng ta xuéxí wimen ycnggai cóng ta xuéxí 7 I’ll write the letter for you. wi tì nh xig xìn wi ggi nh xig xìn 8 I’ll ring you tonight. wi jcn wfn tì nh df diànhuà wi jcn wfn ggi nh df diànhuà 9 I’ll write to you. wi wèi nh xig xìn wi ggi nh xig xìn 10 This town is as old as that town.
250
zhèi gè xifo zhèn yj nèi gè xifo zhèn ycyàng gjlfo
24 Coverbal phrases
zhèi gè xifo zhèn xiàng nèi gè xifo zhèn ycyàng gjlfo
Exercise 24.4 Complete the Chinese sentences below with as appropriate:
cóng,
lí or
dào
1
nh jia shìzhdngxcn yiu dud yufn How far is it from your house to the city centre? 2 wi ycguì li ná che yc tiáo wéijcn I took a scarf out of the wardrobe. 3 ta sùshè chefa He set out from the dormitory. 4 zhèr lúnden yiu èr bfi ycnglh lù It’s two hundred miles from here to London. 5 túshegufn zhèr yiu san ycnglh The library is three miles from here. 6 diànyhngyuàn cangufn de lù hgn jìn It’s not far from the cinema to the restaurant. 7 yóujú yínháng bù yufn The post office is not far from the bank. 8 chén xifojie zhdngguó lái Miss Chen comes from China.
Exercise 24.5 Complete the following Chinese sentences with out cases where both are possible: 1
zhèi jiàn shìr
yóu or
cóng. Point
ta fùzé
He’s responsible for this. 2
wi qùnián qh kaishh xué hànyj I started learning Chinese last year. 3 jiàoshì xuésheng dfsfo The classroom was cleaned by students. 4 huichb shànghfi chefa The train set off from Shanghai.
251
24 Coverbal phrases
5
ta zuótian xiàwj qh kaishh fashao She started to have a fever from yesterday afternoon. 6 wi qiánbao li ná che yc bàng qián I took a pound out of my purse. 7 hfi’du hfimiàn shang fbi guòlái The gulls came flying across the surface of the sea. 8 shèngshcban shí gè nánhái hé shí gè nshái zjchéng The choir was made up of ten boys and ten girls.
Exercise 24.6 Complete the Chinese sentences below choosing the appropriate coverb from those in the brackets: 1
252
qìchb hé bian kai qù ( / xiàng/yán) The car went towards the river bank. 2 lù ddu shì chb ( / D yán/yán zhe) There are cars (parked) all along the road. tdngzhc zuótian fache ( / 3 cóng/yú) The circular was issued yesterday. 4 1949 yéye 1949 nián shìshì ( / yú/yóu) Grandfather died in 1949. 5 nèi gè geniang ddng ziu qù ( / cóng/wàng) The young woman walked towards the east. 6 túshegufn shìzhdngxcn bù yufn ( / cóng/lí) The library is not far from the city centre. 7 yóudìyuán zfo dào wfn zài sòng xìn ( / cóng/yóu) The postmen are delivering letters from morning till night. 8 qhng dàjia jij shí zhèng zài ch jíhé ( / yóu/yú) Would everyone please assemble here at 9 o’clock sharp! 9 qìchb chbkù li kai chelái ( / yóu/cóng) The car emerged from the garage.
10
qhng dì yc yè kaishh dú ( / yú/cóng) Please start reading from the first page.
24 Coverbal phrases
Exercise 24.7 Translate the following sentences into Chinese: 1 2 3 4 5 6 7 8
Please come with me. I’ll ring you tomorrow. They were very friendly to us. It is not too far from here to the station. I work from 9.00 to 5.00 every day. There are cars all along the street. Is this business all up to me? Why don’t you write to them?
Pattern and vocabulary drill 24.1 Using the ... cóng . . . dào ‘from . . . to’ structure, which can refer to time, distance, range, etc., translate the following phrases into Chinese. from morning till night ( ) ( ) cóng zfo(shang) dào wfn(shang) 1 2 3 4 5 6 7 8 9 10
from January to December from children to adults from here to the university from top to bottom from 9.00 a.m. till 6.00 p.m. from food (i.e. what can be eaten) to clothing (i.e. what can be worn) from primary school to secondary school from one to one hundred from A to Z (i.e. from beginning to end) from 1995 to 2005
Pattern and vocabulary drill 24.2 Translate the following Chinese sentences into English, using the vocabulary list if you need to:
253
24 Coverbal phrases
1 2 3 4 5 6
wi xifng gbn nh tán ycxià zhèi jiàn shì qhng nh bié wèi wi caoxcn nèi gè scjc duì chéngkè hgn yiuhfo wi dào xiànzài hái méiyiu chc guo lìchc cháo qián ziu yc bfi gdngchh jiù dào le kàn | yiu chb xiàng wimen zhèr kai lái | shì jh hào chb | nh kàn de jiàn ma 7 zhèi bgn she nh shì cóng shéi nàr jiè lái de 8 wi jia lí fbijcchfng hgn yufn | yào zuò yc gè xifoshí de chb D 9 (shopping mall) (laundry) (pharmacy) nh yán zhe zhèi tiáo dàlù xiàng qián ziu tàyub lifng bfi mh | dào dì èr gè lùkiu xiàng zui gufi | zài ziu wj shí mh zuiyòu | nh jiù néng kànjiàn yc gè dà shangchfng | shangchfng de duìmiàn shì yc gè xhycdiàn | xhycdiàn de bèihòu jiù shì nh yào zhfo de nèi jian yàofáng 10 (square) qiánmian nèi gè lùkiu | nh néng kànjiàn yc gè jiàotáng | yán jiàotáng yòubian de jibdào wfng nán ziu | dàyub wj fbn zhdng nh jiù jiàn dào le yc gè gufngchfng | gufngchfng de zuibian yiu yc tiáo xifo lù | nh yào zhfo de nèi jia shediàn jiù zài nèi tiáo xifo lù shang
254
UNIT TWENTY-FIVE Disyllabic prepositions
A Chinese disyllabic prepositions are distinct from their monosyllabic coverb cousins in two ways. First, these disyllabic prepositions may be used not only before nouns but also before verbs or clauses. Second, they are often placed at the beginning of the sentence rather than directly after the subject. These two distinctive features will be clearly illustrated by the examples below of the most common disyllabic prepositions. B wèile ‘in order to; so that’ expresses purpose and is usually followed by a verb phrase: / wèile bù chídào | ta hgn zfo jiù qh lái/qhchuáng le In order not to get there late, she got up very early. ( ) wèile mfi dào piányi de xìpiào | ta pái le yc (gè) xifoshí de duì In order to buy cheap theatre tickets, he queued for an hour. wèile also occurs in official statements to express formal objectives:
wèile jifnshfo shcyè rénshù | zhèngfj njlì bàn hfo jiàoyù In order to reduce the number of unemployed, the government strives to improve education. It is not normally used in casual, everyday situations and one does not usually say: * wèile mfi ddngxi wi jìn chéng qù (lit. In order to buy things/go shopping, I went into town.) * wèile zhfo wi ta lái sùshè (lit. In order to look for me, he came into the dormitory.)
255
25 Disyllabic prepositions
Everyday purpose or intention is usually expressed by a second verb (phrase) following the first: wi jìn chéng qù mfi ddngxi I went shopping in town. (lit. I went into town to shop.) ta lái sùshè zhfo wi He came to the dormitory to look for me. duìyú ‘as to; about’, guanyú ‘regarding; as regards’ and zhìyú ‘as for; as far as . . . is concerned’, yóuyú ‘because of’, all refer to a matter or person brought up for discussion.
C
duìyú zhèi jiàn shì | wi ycdifnr yg bù zhcdao As to this matter I know nothing./I know nothing about this matter. guanyú zhèi gè wèntí | wimen zài yánjie ycxià Regarding this matter, we will have more discussions./We will consider this matter further. zhìyú jiégui rúhé | wimen míngtian jiù zhcdao le As to how the results will come out, we will know tomorrow./We will know the results by tomorrow. / yóuyú tianqì bù hfo | wimen juédìng dai zài jia li We decided to stay at home because of the bad weather.
Note 1: duì (see Unit 24) can in fact be used interchangeably with duìyú, but in sentences where the verb specifically indicates ‘attitude’, duì is preferred:
wimen duì ta de shèngqíng kufndài bifoshì gfnxiè We expressed thanks for her generosity/hospitality.
256
Note 2: zhìyú, unlike guanyú and duìyú which are generally followed by a noun, may also be used with a clause: guanyú tianwén de zhcshi guanyú shèhuì de wèntí duìyú yímín de tiáolì
25 Disyllabic prepositions
knowledge about astronomy problems about society regulations on immigration/emigration
But: zhìyú zhèi jiàn shìr zhìyú tamen yuànyi bù yuànyi lái
D ...( as . . .’:
/
as far as this is concerned as to whether they wish to come or not (clause)
) chúle . . . (zhc wài/yh wài) ‘apart from . . . /as well
( ) ta chúle jiaoshe (yh wài) hái zuò xib yánjie gdngzuò As well as teaching he also does a bit of research. chúle nh | dàjia ddu tóngyì Everyone agrees except you. chúle ycngwén zhc wài | wi hái huì shud ffwén hé déwén As well as English, I can also speak French and German. E ànzhào ‘according to/in accordance with’ and ‘according to/on the basis of’:
gbnjù
ànzhào xuéxiào gucdìng | xuésheng bù dé wúgù qubxí According to school regulations, students must not be absent from school without good reason. gbnjù qìxiàng yùbào | míngtian xià xug According to the weather forecast, there will be snow tomorrow. 257
25 Disyllabic prepositions
Note: The coverb (D) píng (zhe) also means ‘on the basis of’. It is often used in the following collocations: píngpiào rùchfng Admittance by ticket only. nh píng shénme déche zhèi gè jiélùn On what basis did you arrive at/come to this conclusion? D ta píng zhe yìlì kèfú le zhingzhing kùnnan Through his perseverance, he overcame all kinds of difficulties.
Exercise 25.1 Rephrase the Chinese sentences below using meaning of the English:
wèile to express the
1 ta bù xifng wù le huichb | juédìng ziu jìn lù He didn’t want to miss the train, so he took a short cut. 2 xifo lh kai le lifng xifoshí de chb dào lúnden qù kàn nèi chfng zúqiúsài Xiao Li drove for two hours to London to see the football match. 3 ta jjxíng le yc gè wjhuì | qìngzhù ns’ér dàxué bìyè She held a party to celebrate her daughter’s graduation. 4 ta tèyì cóng ffguó lái kàn zhèi gè diànyhng He came from France specially to see this film. 5 hùshi yc yè méi shuì | zhàogù nèi gè bìngrén The nurse was up all night looking after the patient. 6 jcnglh dào bgijcng qù canjia yc gè zhòngyào huìyì The manager went to Beijing to attend an important meeting.
Exercise 25.2 258
Complete the following sentences using or zhìyú:
( ) duì(yú),
guanyú
1
( ) zánmen ( ) biéren de yìjian ycnggai bifoshì huanyíng We ought to welcome other people’s opinions.
2
25 Disyllabic prepositions
wáng xiansheng tándào zhdngguó xiàndài wénxué de wèntí Mr Wang talked about questions on Modern Chinese Literature. 3 wi qhng xifo lh lái wi jia canjia wfnhuì | ta néng bù néng lái wi hái bù zhcdao I have invited Xiao Li to come to my party, but I don’t know if he can come. 4 háizi de yaoqiú bù yào tài yángé Don’t be too hard on the children. 5 jcnnián xiàtian wimen qù yìdàlì dùjià | ngi tian chefa | xiànzài hái bù néng juédìng This summer we are going to Italy on holiday, but we haven’t decided which day we are leaving. 6 xifo lh ding de hgn dud diànnfo de zhcshi Xiao Li knows a great deal about computers. 7 ta lifojig bù shfo zhdngguó shèhuì de qíngkuàng He understands a lot about conditions in Chinese society. 8 ( ) ( ) nèi chfng bhsài, jiàoliàn méiyiu tíche shénme gèrén de yìjian As far as that match is concerned, the coach did not express his personal views.
Exercise 25.3 Rewrite the following Chinese sentences using ‘ chúle . . . ( ) (zhc wài/yh wài)’ to reflect the meaning of the English:
/
1 dòngwùyuán li yiu lfohj | shczi | hái yiu xióngmao There are tigers and lions as well as pandas at the zoo. 2 ban li yiu zhdngguó rén | hái yiu ycngguó rén hé ffguó rén In addition to Chinese students, there are also English and French students in the class.
259
25 Disyllabic prepositions
3 wi shénme ddu chc | zhhshì bù chc yángròu I eat everything apart from lamb. 4 chén xifojie huì tán jíta | hái huì tán gangqín Miss Chen can play the guitar as well as the piano.
Exercise 25.4 Fill in the blanks in the sentences below, choosing the appropriate preposition from the two in the brackets in each case: 1 zhè shì zhbnshí gùshi pai de diànyhng This is a film based on a true story. ( / ànzhào/gbnjù) 2 piào rùchfng Admittance is by ticket only. ( / ànzhào/píng) 3 zhèi xib yánjie | kgyh déche zhèngquè jiélùn Based on this research we can reach an accurate conclusion. ( / gbnjù/píng) 4 nh shénme gbn wi zhèyàng shudhuà On what grounds are you speaking to me like this? ( / gbnjù/ píng) 5 tamen lfo bànff qù zuò They do it according to the old method. ( / gbnjù/ànzhào) 6 ta yìlì zhànshèng le bìngtòng de zhémo She overcame the pain of her illness through strength of will. ( / D ànzhào/píng zhe)
Exercise 25.5 Indicate whether the Chinese translations below are correct or not, and, if not, make appropriate corrections: 1 The teacher is concerned about my work. lfoshc guanyú wi de xuéxí hgn guanxcn 2 I went to town to do some shopping. wèile mfi ddngxi wi jìn chéng qù 260
3 He got up very early so that he wouldn’t be late. wèile bù chídào | ta hgn zfo jiù qhchuáng le 4 According to the weather forecast there will be heavy rain tomorrow. píng qìxiàng yùbào | míngtian xià dà yj 5 As well as swimming I like playing football. chúle yóuying | wi hái xhhuan tc zúqiú 6 Regarding the problem of children’s bad behaviour, school teachers as well as parents should also be concerned.
25 Disyllabic prepositions
duì háizi tiáopí de wèntí | chúle jiazhfng zhc wài | xuéxiào lfoshc yg ycnggai gufn
Exercise 25.6 Translate the following into Chinese: 1 2 3 4 5 6 7
As regards this question, I have no opinion. I am very worried about this problem. I can come every day apart from Wednesday. As to whether we can come, please ask my wife. Apart from her, they all like Chinese food. I am going into town to see a friend. In order to come to a conclusion, they discussed this matter for five hours. 8 On what grounds does the government pursue this policy?
Pattern and vocabulary drill 25.1 Reformulate the 8 sentences or pairs of sentences below using the disyllabic prepositions given in brackets: ( yóuyú ‘because of’) xià dà yj | qiúsài gfi qc There was a heavy rain. The match was postponed. ( ) yóuyú (xià) dà yj | qiúsài gfi qc The match was postponed because of the heavy rain. 261
25 Disyllabic prepositions
1
2
3
4
5
6
7
8
( yóuyú ‘because of’) tianqì bù hfo | wimen ddu dai zài jia li The weather was bad. We all stayed at home. ( chúle ‘apart from’) ta xué ffyj | ta hái xué zhdngwén She is learning French. She is also learning Chinese. ( ) ( wèile ‘in order to’) ta xifng ràng háizi dédào hgn hfo de jiàoyù | ta njlì (de) gdngzuò She would like her children to have a good education. She worked hard. ( ànzhào ‘according to’) ta tcng le fùmj de jiànyì | ta bù zài chc ròu le He listened to his parents’ suggestion and never touched meat again. ( gbnjù ‘on the basis of’) nh píng shénme shud wi cuò le On what basis did you say I was wrong? ( zhìyú ‘as far as . . . is concerned’) ta shud ta bù yuànyi gufn zhèi jiàn shìqing As far as this is concerned, he says he doesn’t want to have anything to do with it. ( guanyú ‘as regards’) ta duì nàr de qíngkuàng shífbn lifojig He knows a lot about the situation there. ( duìyú ‘as to’) ta gdngzuò hgn njlì | wi duì ta de gdngzuò méi yiu shénme yìjian He works very hard. I have no qualms about his work.
Pattern and vocabulary drill 25.2 Translate into Chinese the following conversation between Wang and his young friend Li:
262
A: Hello, Li (use the familiar form of address here and below between people of different ages). B: Hello, Wang. A: Where are you off to? B: I am going to the post office (to post a letter). A: Who is the letter to? B: It’s to my parents. They are very good to me. A: Where do they live? B: They live in Beijing, very far from here.
A: B: A: B: A: B:
Do you go home to visit your parents very often? No, I don’t have the time. You can ask for leave. I have got so much to do. Honestly I can’t get away. Please send them my regards. Wish them good health. Thank you. I am flying to London tomorrow. I’ll ring them from there. A: Bye. B: Bye.
25 Disyllabic prepositions
263
KEY TO EXERCISES
Unit 1 Exercise 1.1 1 yc gè háizi 2 yc gè háizi 3 lifng gè háizi 4 san gè chéngzi 5 yc dá jcdàn 6 sì gè miànbao 7 wj piàn miànbao 8 yc gè chéngshì 9 lifng gè jiànyì 10 liù gè guójia 11 / ba gè/jia shangdiàn ( jia another measure word for ‘shop’) 12 jij gè xuésheng 13 qc gè gdngchéngshc 14 yc gè péngyou 15 yc gè rén 16 yc gè bbizi 17 lifng zhc bh 18 shí gè bbizi 19 lifng bbi chá 20 san bgn she 21 sì gè dàren 22 liù zhang zhh 23 yc gè dàngao 24 yc kuài dàngao 25 yc gè jièkiu 26 wj gè nán háizi 27 liù gè ns háizi 28 lifng kuài bù 29 jh kb shù 30 lifng gè zhdngguó rén
Exercise 1.2 yc may be omitted in sentences: 1, 2, 3, 4, 5, 7; omitted in sentences: 6, 8
yc cannot be
Exercise 1.3 1
wi pèngjiàn lifng gè péngyou 2 ta xifng zhfo yc gè jièkiu 3 háizimen yào chc pínggui 4 támen xifng qù san gè guójia 5 correct 6 ta yiu zhdngguó péngyou 7 nh yào chc jh piàn miànbao 8 correct
Exercise 1.4 264
1 I would like to buy a few bread rolls. 2 She would like to eat two pieces of cake. 3 I bumped into three Chinese people. 4 I would
like to have a cup of coffee. 5 I would like to go to/visit five countries. 6 She is an engineer. 7 I have two children. 8 I only want to go to one city. 9 Who would like to buy books? 10 I have a suggestion (to make).
Key to exercises
Exercise 1.5 1 pínggui hé chéngzi 2 / dàren hé háizi/xifohái ( xifohái little child) 3 san piàn miànbao | yc bbi kafbi hé yc kuài dàngao 4 sì bgn she hé liù zhc bh 5 wi xifng qù san gè guójia 6 ( ) wi xifng hb (yc) bbi chá 7 / ta zhh xifng qù lifng gè/jia shangdiàn 8 ta xifng mfi yc gè miànbao | lifng gè dàngao | wj gè pínggui hé yc dá jcdàn 9 háizi zhh yiu yc gè lhxifng 10 wi pèngjiàn sì gè zhdngguó péngyou 11 wi yào jh zhang zhh 12 wi xifng lifojig zhdngguó de jcngjì hé wénhuà
Drill 1.1 1 a
jh gè jcdàn b jh gè miànbao c yc bgn she hé yc zhc bh d jh gè chéngzi 2 a yc bbi chá b yc bbi kafbi c yc bbi píjij d yc bbi kglè 3 a yc gè pínggui b jh gè chéngzi c yc kuài gao d yc gè sanmíngzhì 4 a zhdngguó b ycngguó c bgijcng d lúnden 5 a jh gè zhdngguó péngyou b jh gè ycngguó péngyou
Drill 1.2 1 a shéi yào mfi jh gè jcdàn b shéi yào mfi jh gè miànbao c shéi yào mfi yc bgn she hé yc zhc bh d shéi yào mfi jh gè chéngzi 2 a shéi xifng hb yc bbi chá b shéi xifng hb yc bbi kafbi c shéi xifng hb yc bbi píjij d shéi xifng hb yc bbi kglè 3 a shéi xifng chc yc gè pínggui b shéi xifng chc jh gè chéngzi c shéi xifng chc yc kuài gao d shéi xifng chc yc gè sanmíngzhì 4 a shéi yào qù zhdngguó b shéi yào qù ycngguó c shéi yào qù bgijcng d shéi yào qù lúnden 5 a shéi xifng jiao jh gè zhdngguó péngyou b shéi xifng jiao jh gè ycngguó péngyou
265
Key to exercises
Unit 2 Exercise 2.1 1
zhèi zhc 2 zhèi xib 3 nèi gè 4 nèi xib 5 nà jh gè 6 zhè jh zhang 7 nèi gè 8 zhèi bgn 9 nèi xib 10 nà jh gè 11 zhèi gè 12 zhè jh gè 13 nèi gè 14 zhèi xib 15 nèi xib 16 nèi kuài 17 nèi gè 18 zhèi bf 19 nèi piàn 20 zhèi xib 21 nèi xib 22 / nèi gè/jia 23 nà jh bf 24 / zhè jh fú/zhang ( zhang another measure word for ‘picture’) 25 zhè lifng gè ycshbng 26 nà jh gè bìngrén
Exercise 2.2 1 She likes dogs. 2 I’ll buy this hat. 3 Either is correct depending on the context. 4 Where are the keys? 5 Either is correct depending on the context. 6 Has she got any children? 7 There is a bowl on the table. 8 There is a jumper in the wardrobe. 9 The chopsticks are on the table. 10 I know how to use chopsticks.
Exercise 2.3 1 Where is/are there a/some book(s)? 2 Where is/are the book(s)? 3 There is a cake in the kitchen. 4 The cat is in the room. 5 Are you looking for the key(s)? 6 Are you going to buy an umbrella? 7 Would you like a/some banana(s)? 8 We would like to buy some flowers. 9 The children are at school. 10 I like (eating) apples. 11 All the four jumpers and three hats are in the wardrobe. 12 All the ten students want to go to China. 13 Do you have any chopsticks? 14 All the apples, oranges, cake and bread are in the kitchen.
Exercise 2.4 1 hfochc 3 ( )
266
nfr yiu shangdiàn 2 chéngzi hgn zhudzi shang yiu jh gè bbizi 4 shejià shang yiu (yc)xib she 5 ( ) / nh (shbn shang) yiu bh ma/nh dài le bh méiyiu 6 / wfn zài guìzi/wfnguì li ( wfnguì a more specific term for ‘cupboard’, lit. bowl cabinet) 7 yàoshi zài nfr 8 ( ) / ( ) huapíng li yiu
(yc)xib huar/yiu (yc)xib huar zài huapíng li 9 nán háizimen zài nfr 10 nh yiu maoyc ma 11 / zhèi xib zhàopiàn nh xhhuan ma/nh xhhuan zhèi xib zhàopiàn ma 12 nh zhfo she ma 13 zhè lifng bgn she hgn yiu yìsi 14 wi xhhuan nà san fú huàr 15 nà wj gè xuésheng zài nfr
Key to exercises
Drill 2.1 1 a
nfr yiu bh b cèsui zài nfr b
nfr yiu yhzi 2 a chbzhàn zài nfr 3 a yiu yc gè nán ycshbng hé yc gè ns ycshbng zài bìngfáng li b yiu jij gè bìngrén zài bìngfáng li 4 a wfn hé kuàizi ddu zài chúfáng li b dao hé cha ddu zài chúfáng li 5 a guìzi li yiu chá hé kafbi b guìzi li yiu jh zhc bbizi
Drill 2.2 1 nh xhhuan chc dàngao ma 2 nh xhhuan hb píjij ma 3 nh xhhuan chc shecài ma 4 nh xhhuan jiao péngyou ma 5 nh xifng hb bbi kafbi ma 6 nh xifng mfi zhc bh ma 7 nh yào mfi jh bgn she ma 8 nh xifng mfi xib huar ma 9 nh de mao huì zhua lfoshj ma 10 nh huì huà huàr ma
Unit 3 Exercise 3.1 1
wi xhhuan ta | ta yg xhhuan wi 2 wimen xifng qù jiàn tamen | dànshì tamen bù xifng jiàn wimen 3 nh bù rènshi ta | dànshì ta rènshi nh 4 bàba | mama | nhmen yào hb kafbi ma 5 ta zài nfr | wi xifng gbn ta tántán 6 ( ) wimen yiu lifng tiáo giu | (tamen) ddu zhù zài ta de fángjian li 7 wi bù xhhuan nèi xib huar | nh xhhuan ma 8 nh xifng kàn nèi gè diànyhng ma | zánmen qù kàn ba
267
Key to exercises
Exercise 3.2 1 5 8
wi de 2 ( ) nh (de) 3 wi 4 wi gbge de ta de 6 wimen línje de 7 ( ) tamen (de) ( ) ta (de), ( ) wi (de) 9 / bàba/fùqin de 10 wimen de 11 zìjh 12 zìjh de
Exercise 3.3 1 wi gbge de, ( ) wi (zìjh) de 2 ta de, wi de 3 ta jia de 4 wi de, nh de 5 wi 6 ta 7 nh de, wi de 8 nh de, ta de 9 / bàba/fùqin de, ( ) (ta) zìjh de 10 nh jia de 11 wimen línje de nèi xib 12 ( ) (ta) zìjh de nèi jiàn
Exercise 3.4 1
nín 2 nín jh wèi
6
nín jh wèi nín
3
nín jh wèi 4
nín
5
Exercise 3.5 1 5
wimen 2 zánmen 6
zánmen 3 wimen
wimen
4
zánmen
Drill 3.1 1 Happy Birthday! 2 Happy New Year! 3 A Merry Christmas! 4 Wish you good health! 5 A safe journey home! 6 Wish you success!
Drill 3.2
268
1 nh de nèi xib she hgn yiuqù 2 ta de fùmj hgn yiumíng 3 nà san gè zhdnggúo rén hgn yiuqián 4 nh bàba de she hgn yiuyòng 5 zhèi gè fangff hgn yiuxiào 6 nh de nèi gè dàngao hgn hfochc | zhèi bbi kafbi hgn hfohb 7 wi mèimei de nèi jiàn máoyc hgn hfokàn 8 nèi shiu gb ta de nèi gè jiànyì hgn hfoxiào hgn hfotcng 9 10 wimen línje de nèi zhc xifo mao hgn hfowánr
Drill 3.3 1 yàoshi nh dài le méiyiu 2 yjsfn nh dài le méiyiu 3 máoyc nh dài le méiyiu 4 zhàopiàn nh dài le méiyiu 5 she nh kàn le méiyiu 6 wfn hé kuàizi nh mfi le méiyiu 7 chá nh hb le méiyiu 8 dàngao nh chc le méiyiu 9 mao nh zhfo dào le méiyiu 10 diànyhng nh kàn le méiyiu
Key to exercises
1 Have you brought the key(s)? 2 Have you brought the umbrella? 3 Have you brought your sweater? 4 Have you brought the picture(s)/photograph(s)? 5 Have you read the book(s)? 6 Have you bought the bowl(s) and the chopsticks? 7 Have you drunk the tea? 8 Have you eaten the cake(s)? 9 Have you found the cat? 10 Have you seen the film?
Unit 4 Exercise 4.1 1 a
shéi qù shìchfng mfi jcdàn b mama qù nfr mfi jcdàn c mama qù shìchfng mfi shénme d mama qù shìchfng zuò shénme 2 a bàba zài nfr xig tucjiànxìn b bàba zài bàngdngshì zuò shénme c bàba zài bàngdngshì xig shénme d shéi zài bàngdngshì xig tucjiànxìn 3 a jigjie zài nfr wèi mao b jigjie zài chúfáng li zuò shénme c shéi zài chúfáng li wèi mao 4 a gbge zài wàimian zuò shénme b gbge zài wàimian xie shénme c gbge zài nfr xie chb d shéi zài wàimian xie chb 5 a dìdi qù yóuyingchí zuò shénme b shéi qù yóuyingchí xué yóuying c dìdi qù nfr xué yóuying 6 a dìdi xifng qhng shéi bang ta de máng b dìdi xifng qhng jigjie zuò shénme c shéi xifng qhng jigjie bangmáng 7 a shéi de háizi zài jib shang qí zìxíngchb b shéi zài jib shang qí zìxíngchb c línje de háizi zài jib shang zuò shénme d línje de háizi zài jib shang qí shénme e línje de háizi zài nfr qí zìxíngchb 8 a shéi míngnián xifng gbn yéye qù zhdngguó
269
Key to exercises
lsxíng b
mèimei míngnián xifng zuò shénme c mèimei míngnián xifng gbn shéi qù zhdngguó lsxíng d mèimei míngnián xifng gbn yéye qù nfr lsxíng e mèimei míngnián xifng gbn yéye qù zhdngguó zuò shénme
Exercise 4.2 1 nfr yiu zìxíngchb ze 2 nfr yiu kafbi hb 3 / nfr yiu huar mfi/mài 4 nfr yiu píjij hb 5 nfr yiu ddngxi chc 6 nfr yiu diànyhng kàn 7 / nfr yiu bàozhh mfi/mài 8 nfr yiu she jiè 9 / nfr yiu xcnxian shecài mfi/mài 10 ( ) nfr yiu hfo (qì)chb ze
Exercise 4.3 1 shéi xifng hb chá 2 shéi xifng chc dàngao 3 / zhèi gè bbizi shì shéi de/zhè shì shéi de bbizi 4 nh xifng chc shénme 5 nh xhhuan ngi fú huàr 6 shéi huì shud zhdngwén 7 ngi gè háizi shì nh de 8 zhang xiansheng shì shéi de lfoshc 9 nh yào mfi ngi xib chéngzi 10 nh xhhuan shénme shecài 11 shéi huì xie chb 12 / shéi néng bang wi de máng/shéi néng bangzhù wi 13 nh xifng jiàn shéi 14 nh dài le nf lifng bgn she 15 / nh qù le shénme dìfang/nh qù le nfr 16 nh qù ngi xib guójia 17 wi de qiánbao zài nfr 18 nh qù nfr hb kafbi 19 nh hé/gbn / / / shéi qù zhdngguó/nh shì hé/gbn shéi qù zhdngguó 20 / nh zài nfr rènshi ta/nh shì zài nfr rènshi ta de
Drill 4.1 1 a
270
wi xifng chc difnr dàngao b wi xifng chc difnr bcngjilíng 2 a wi xifng wi xifng mfi difnr yú 3 a mfi difnr báicài b wi zhèi gè lhbài tian xifng qù kàn diànyhng b wi zhèi gè lhbài tian xifng qù yóuying
4 a
wi zhfo yàoshi b wi zhfo yjsfn 5 a wi zhfo lh xiansheng b / wi zhfo wi fùqin/bàba 6 a / wi dào/shàng yínháng qù b / wi dào/shàng dàxué qù
Key to exercises
Drill 4.2 1 Do you like keeping a cat? nh xhhuan yfng mao ba You like keeping a cat, don’t you? 2 Do you like keeping a dog? nh xhhuan yfng giu ba You like keeping a dog, don’t you? 3 Do you like keeping goldfish? nh xhhuan yfng jcnyú ba You like keeping goldfish, don’t you? 4 Do you like cycling/riding a bike? nh xhhuan qí zìxíngchb ba You like riding a bike, don’t you? 5 Do you like horse riding? nh xhhuan qí mf ba You like horse riding, don’t you? 6 Do you nh xhhuan zhù zài lúnden ba like living in London? You like living in London, don’t you? 7 Do you like living in Paris? nh xhhuan zhù zài balí ba You like living in Paris, don’t you? 8 Do you like buying things cheap? nh xhhuan mfi piányi de ddngxi ba You like buying things cheap, don’t you? 9 Do you like fresh flowers? nh xhhuan xianhua ba You like fresh flowers, don’t you? 10 Do you like your neighbour(s)? nh xhhuan nh de línje ba You like your neighbour(s), don’t you? 11 Do you like your work? nh xhhuan nh de gdngzuò ba You like your work, don’t you? 12 Do you like/fancy this sweater? nh xhhuan zhèi jiàn máoyc ba You like this sweater, don’t you?
Unit 5 Exercise 5.1 1 89 2 16 3 10,000 4 600,000,000 5 7,000,000 6 13,526 7 180,000 8 6,934 9 3,652 10 780,000,469 11 64,504 12 4,004.005
Exercise 5.2 1
ba wàn líng èr bfi líng wj 2 liù bfi san shí èr wàn jij qian ba bfi yc shí sì ( yc shí sì for fourteen is only used in counting when following a figure in the liù yì 4 yc qian líng ba shí 5 hundreds) 3 san shí liù fbn zhc qc 6 sì fbn zhc yc 7 bfi fbn zhc san 8 bfi fbn zhc jij shí qc 9
271
Key to exercises
sì difn yc san yc liù 10 san 11 qc qian líng wj 12 yc difn líng líng qc
wj bfi ba shí liù difn èr liù bfi líng
Exercise 5.3 1 bàn tian 2 ( ) lifng (gè) xcngqc/lifng / / gè lhbài/lifng zhdu ( zhdu is also used to mean ‘week’) 3 san nián bàn 4 liù gè yuè 5 èr lóu 6 bàn gè chéngzi 7 bàn píng jij 8 wj gè bàn lí 9 dì wj zhdu 10 dì sì gè háizi 11 dì shí èr chfng bhsài 12 san niánjí 13 dì èr tian 14 / qc gè bàn xifoshí/zhdngtóu
Exercise 5.4 1 7
lifng èr 8
2
lifng 3 lifng 9 èr
èr 10
4 èr lifng
5
èr
6
lifng
Exercise 5.5 1 / yc | lifng zhdu/yc | lifng gè / xcngqc/yc | lifng gè lhbài 2 lifng bfi nián 3 / / / liù shí lái suì/dàyub liù shí suì/liù shí suì zuiyòu/shàngxià 4 san | sì shí liàng zìxíngchb 5 shí dud tian 6 lifng bfi lái gè shangdiàn 7 bfi fbn zhc shí 8 / èr shí / zuiyòu/shàngxià/dàyub èr shí 9 / shí wj / mh zuiyòu/shàngxià/dàyub shí wj mh 10 / / yc gè yuè zuiyòu/shàngxià/dàyub yc gè yuè 11 yc wàn dud gè xuésheng 12 lifng | san gè háizi 13 dàyub wj shí gè péngyou hé línje 14 / / dàyub qc shí ycnglh/qc shí ycnglh zuiyòu/shàngxià 15 ba gdngjcn dud 16 shí dud gè chéngshì
Exercise 5.6 1 / wfnguì/guìzi li yiu san gè chéngzi | lifng gè lí | yc gè miànbao hé yc píng jij 2 zhudzi shang yiu yc gè wfn | yc gè bbizi hé yc shuang kuàizi 3 bcngxiang li yiu bàn dá jcdàn | yc gdngjcn báicài hé ycxib bcngjilíng 4 / ycguì/guìzi li 272
yiu lifng jiàn máoyc hé shí èr tiáo qúnzi ( ycguì is a more specific term for ‘wardrobe’ lit. clothes cabinet) 5 lh míng qhng le san | sì shí gè péngyou hé tóngxué 6 wi nán péngyou dài lái le yc shù huar hé jh píng píjij 7 wi xig le dàyub wj fbng tucjiànxìn 8 wi ns péngyou qù guo shí dud gè guójia 9 wi péngjiàn le èr shí dud gè tóngxué 10 wi érzi jcnnián kàn le shí lái gè diànyhng 11 nèi jiàn máoyc dudshao qián 12 ta yiu jh gè mèimei 13 bgijcng yiu dudshao rén 14 / nh bàba/fùqin rènshi dudshao zhdngguó rén 15 / nh yào/xifng mfi jh gdngjcn báicài
Key to exercises
Drill 5.1 1 Would the next person please come in. 2 When does the next train/coach leave? 3 The first half was brilliant. 4 We are going next Thursday. 5 He worked very hard in the last/previous academic year. 6 Are you getting off at the next stop? 7 The last/previous issue is sold out. 8 See you next time.
Drill 5.2 1 nh jiàn guo zhè jh gè gdngchéngshc méiyiu 2 nh qù guo ycngguó méiyiu 3 nh yfng guo giu méiyiu 4 nh qí guo luòtuo méiyiu 5 nh yòng guo kuàizi méiyiu 6 nh jiao guo zhdngguó péngyou méiyiu 7 nh hb guo ycngguó píjij méiyiu 8 nh hb guo zhdngguó chá méiyiu 9 nh kàn guo zhdngguó diànyhng méiyiu 10 nh kai guo chb méiyiu 11 nh ze guo chb méiyiu 12 nh qù guo nh péngyou jia méiyiu 13 nh jiàn guo ta fùmj méiyiu 14 ( ) nh bang guo nh péngyou (de máng) méiyiu 15 nh xué guo yóuying méiyiu
Unit 6 Exercise 6.1 1 3
yc ph mf a/one horse 2 san gè guójia three countries
4
lifng jià fbijc two planes sì | wj bf 273
Key to exercises
yhzi four or five chairs 5 jh zhang zhudzi a few/how many tables 6 liù jia shangdiàn six shops 7 qc sui xuéxiào seven schools 8 ba zuò shan eight mountains 9 jij bgn she nine books 10 shí kuài dàngao ten pieces of cake
Exercise 6.2 1
zhang zuò 8
2 chuáng duì
3
sui 4
fù
5
bù
6
gè
7
Exercise 6.3 1 yc tian 2 yc wfn fàn 3 yc nián 4 zhèi fù yfnjìng 5 ( ) yc shuang xié(zi) 6 ( ) / / yc (gè) xcngqc/yc gè lhbài/yc zhdu 7 yc gè grhuán 8 yc zhc wàzi 9 / yc kuài/piàn miànbao 10 ngi bf jifndao 11 / yc kuài/tiáo féizào 12 yc tiáo kùzi 13 yc gè yuè 14 lifng bàng pínggui 15 ( ) san ycnglh (lù) 16 qc shbng qìyóu 17 ngi zhc máobh 18 / / yh tiáo/zhc/sdu chuán ( sdu is another measure word for ‘ship’) 19 lifng shiu gb 20 / yc zhang/fú dìtú
Exercise 6.4 1 yc qún yáng 2 yc bbi píjij 3 yc qún rén 4 ( ) yc bf (yj)sfn 5 yc bf dao 6 nèi zhc nifo 7 ( ) nà lifng shù hua(r) 8 yc zhc yuèqj 9 zhèi zhang bàozhh 10 nf san zhc qianbh 11 yc gè jchuì 12 yc dc shuc 13 yc bbi chá 14 ( ) ngi dui hua(r) 15 yc tiáo shéngzi 16 yc zhang chuáng 17 yc tiáo kùzi 18 yc bf jifndao 19 zhèi tiáo giu 20 ( ) zhè san zhc (xiang)yan
Exercise 6.5 1
274
/ zhèi jian/gè sì zhang, wj bf 2 lifng tiáo, san zhc 3 sì liàng 4 yc dhng 5 sì bbi 6 nèi gè / jh gè/tiáo 7 ycxib 8 yc jia yc wfn 9 yc zhang 10 nà lifng zhc
Exercise
6.6
1 wi yiu lifng gè háizi | nh yiu jh gè háizi 2 nh hb le san bbi píjij | wi zhh hb le yc bbi 3 wi xhhuan zhèi zhc giu | wi bù xhhuan nèi zhc giu 4 ( ) wi mama yiu shí èr shuang xié(zi) | wi jigjie yiu èr shí dud shuang 5 ( ) wimen (zhh) yiu yc liàng chb | nhmen yiu lifng liàng ba 6 ta chc le yc wfn fàn | ta chc le san | sì wfn 7 zhèi gè shì shuí de 8 ngi gè shì ta de
Key to exercises
Drill 6.1 1
shejià shang yiu shí jh/shí dud bgn she 2 huapíng li yiu yc shù xianhua 3 zhudzi shang yiu lifng zhc wfn hé lifng shuang kuàizi 4 ycguì li yiu lifng jiàn chènshan | lifng tiáo qúnzi hé lifng tiáo kùzi 5 / wi fùmj jia yiu lifng zhc mao hé yc zhc/tiáo giu 6 bcngxiang li yiu yc kuài ròu hé ycxib shecài 7 (zuòwèi ‘seat’) diànyhngyuàn yiu san bf dud gè zuòwèi 8 shangdiàn li yiu yc dà qún rén 9 ta yíngháng li yiu yc xifo bh qián 10 shìchfng shang yiu pínggui | chéngzi | lí hé xiangjiao mài 11 chúfáng li yiu yc zhang dà zhudzi hé liù bf yhzi 12 (xíngrén ‘pedestrians’) jib shang yiu láilái wfngwfng de chbliàng hé xíngrén 13 bàngdngshì li yiu sì gè shejià 14 ta shbn shang méi yiu qián 15 chí li yiu shí yc tiáo yú 16 wfn li yiu ycxib fàn 17 chuáng shang yiu lifng zhang bèizi 18 wfnguì li yiu shí dud zhc wfn 19 shù shang yiu jh zhc nifor 20 shan shang yiu yc qún láng 21 (chéngkè ‘passenger’) chb shang yiu èr shí dud gè chéngkè 22 chuán shang yiu san bfi wj shí liù gè chéngkè /
Drill 6.2 1 ( ) yc zhang zhang (de) zhudzi 2 ( ) yc chuàn chuàn (de) xiangjiao 3 ( ) yc zuò zuò (de) dà shan 4 ( ) yc qún qún (de) yáng 5 ( ) yc shuang shuang (de) xiézi 6 ( ) yc shuang shuang (de) wàzi 7 ( ) yc dui dui (de) yún 8 ( ) yc jià
275
Key to exercises
jià (de) fbijc 9 ( ) yc zhc zhc (de) xifo nifo
yc fbng fbng (de) xìn
10
( )
Unit 7 Exercise 7.1 1 correct 2 bù shfo háizi 3 bù shfo péngyou 4 correct 5 hgn dud miànbao 6 correct 7 correct 8 correct 9 hgn dud rén 10 ycxib gdngchéngshc 11 correct 12 correct 13 correct 14 correct 15 jia li lián yc lì mh yg méi yiu 16 correct
Exercise 7.2 1
hgn dud/ bù shfo 2 bù shfo 4 yc gè 5 hgn dud/ bù shfo 7 ( ) hgn dud/ bù shfo ycdifnr 9
( ) ycdifnr 3 hgn dud/ hgn dud/ bù shfo 6 ycxib 8 ( ) ycdifnr/ 10 bù shfo
Exercise 7.3 1 ( ) wi shbn shang (lián) yc fbn qián yg méi yiu 2 ( ) wi jia li (lián) yc bgn cídifn yg méi yiu 3 bcngxiang li ycdifnr shuhgui yg méi yiu 4 ( ) ta shénme yg méi(yiu) shud 5 ( ) ta shénme (ddngxi) yg méi(yiu) chc 6 ( ) ( ) mama shénme ròu yg méi(yiu) mfi 7 ( ) wimen nfr yg méi(yiu) qù 8 ( ) wi zuótian shéi/shuí yg méi(yiu) pèngjiàn
Exercise 7.4 1 / 7
( ) ycdifn(r) 2 ( ) ycxib/ycdifnr ( ) ycdifn(r) 8
5
( ) ycdifn(r) 3 ( ) ycdifn(r) ( ) ycdifn(r)
( ) ycdifn(r) 4 6 ( ) ycdifn(r)
Drill 7.1
276
1 (very) many books nh yiu hgn dud she ma 2 many/quite a few children nh yiu bù shfo háizi ma 3 a little petrol nh yiu ycdifnr qìyóu ma 4 some rice nh yiu ycxib mh ma 5 many dishes
nh yiu xjdud cài ma 6 a few chairs nh yiu jh bf yhzi ma 7 a few yuán nh yiu jh kuài qián ma 8 some paper nh yiu ycxib zhh ma 9 a little salt nh yiu ycdifnr yán ma 10 a little time nh yiu ycdifnr shíjian ma
Key to exercises
Drill 7.2 1
chb shang yc gè chéngkè yg méi yiu 2 ( ) wi (de) qiánbao li yc fbn qián yg méi yiu 3 píngzi li ycdifn jij yg méi yiu 4 shejià shang yc bgn she yg méi yiu 5 hé shang yc tiáo chuán yg méi yiu 6 ta de huà ycdifn dàoli yg méi yiu 7 ycguì li yc tiáo qúnzi yg méi yiu 8 wfnguì li yc zhc wfn yg méi yiu 9 nèi gè rén yc gè péngyou yg méi yiu 10 zhèi jiàn shì ycdifnr xcwàng yg méi yiu
Unit 8 Exercise 8.1 1 three o’clock 2 twelve o’clock 3 twenty past two 4 five to eight/seven fifty-five 5 ten to eight 6 a quarter past eleven 7 half past nine 8 one minute past ten 9 five past twelve 10 a quarter to seven/six forty-five
Exercise 8.2 1
wi shàngwj ba difn bàn qù xuéxiào 2 / wi shàngwj ba difn wj shí wj fbn/jij difn chà wj fbn qù yóuying 3 / wi péngyou xiàwj wj difn san kè/wj difn sì shí wj fbn xiàban 4 ( ) wimen dàyub jij difn (zhdng) chc wfnfàn 5 wi liù hào pèngjiàn nh sheshu 6 wi bàba shí yc hào qù zhdngguó 7 wi mèimei wfnshang shí èr difn zuiyòu shuìjiào 8 wi xià gè yuè ér shí yc hào ggi ta xig xìn 9 wi xià xcngqc sì lái zhèr kai zuòtánhuì 10 wi yc jij jij jij nián bìyè 11 / wi míngnián/jcnnián jijyuè dào duzhdu qù 12 wi tóngxué míngnián shí’èryuè huí guó
277
Key to exercises
Note: dàyub, zuiyòu and changeably in this exercise.
shàngxià may be used inter-
Exercise 8.3 1
( )
ta jh difn (zhing) chc wfnfàn 2 nh lhbài wj wfnshang jh difn (zhdng) lái wi jia 3 nhmen bayuè jh hào qù dùjià 4 nh ngi nián dì yc cì jiàn dào ta 5 ( ) nh mama jh difn (zhdng) huí jia 6 xcn jcnglh xià xcngqc jh lái zhèr shàngban 7 nhmen shénme shíhou lái zhfo wi 8 / tamen shénme shíhou/ngi nián bìyè 9 nh jigjie shàng xcngqc jh xiàwj zài xué kàichb 10 / nh qùnián jh yuè/shénme shíhou mfi zhèi fú huà 11 ( ) zudtánhuì shàngwj jh difn (zhdng) kaishh 12 nh míngtian shénme shíhou zài jia li xiexi ( )
Exercise 8.4 1 ( ) nh míngtian shénme shíhou qù xuéxiào (shàngkè) 2 wi xià gè yuè lái zhèr kai zuòtánhuì 3 nh shénme shíhou qù duzhdu lsxíng 4 ( ) nh míngtian jh difn (zhdng) shàngban 5 ( ) nh xiàwj jh difn (zhdng) qù yóuyingchí yóuying 6 nh ngi tian dào nàr qù tc zúqiú 7 / nh jh yuè/ngi gè yuè qù hfi bian dùjià 8 nh shénme shíhou qù huichbzhàn mfi piào 9 ( ) ( ) nh shàngwj jh difn (zhdng) qù shìchfng (mfi ddngxi) 10 / nh jh shí/shénme shíhou qù túshegufn jiè she
Drill 8.1
278
1 nh zhèi gè xcngqc tian qù kàn qiúsài ma 2 ( ) nh xià (gè) lhbài qù jiàn nh (de) dfoshc ma 3 nh míngtian shàngwj qù kàn ycshbng ma 4 nh xià xcngqc’èr xué tàijíquán ma 5 nh jcntian xiàwj wèi mao ma 6 nh jcntian wfnshang shàng wfng ma 7 nh míngtian fàngxué hòu qù diàoyú ma 8 nh míngtian xiàban hòu qù xué kai chb ma 9
nh jcnwfn kàn diànshì ma 10 hòu qù lsxíng ma 11 tànwàng nh fùmj ma 12 (fèn) qù dùjià ma
( )
nh míngnián bìyè nh xià gè yuè qù nh jcnnián liùyuè
Key to exercises
Drill 8.2 1 ( ) nh wfnshang jh difn zhdng (shàng chuáng) shuìjiào 2 nh zfoshang jh difn zhdng shàngban 3 nh jh hào dòngshbn dào zhdngguó qù 4 nh dàyub jh difn zhdng xiàban 5 / ní ngi yc tian ziu/nh xcngqc jh ziu 6 nh shénme shíhou lái zhfo wi 7 nh ngi yc tian qhng wi lái nh jia 8 / nh ngi yc tian/ shénme shíhou zài jia 9 nh ngi yc nián zhù zài bgijcng 10 nh ngi yc nián rènshi ta
Unit 9 Exercise 9.1 1 nh zài lù shang hua le dud cháng shíjian 2 / nh zài jiàoshì li kàn le dud jij/dud cháng shíjian de she 3 / zúqiú bhsài kaishh dud jij/dud cháng shíjian le 4 / nh hé jigjie zài huayuán li zuò le dud jij/dud cháng shíjian 5 / mama zài chúfáng li máng le dud jij/dud cháng shíjian 6 / / mèimei bang le nh jh tian/dudshao tian/dud cháng shíjian de máng 7 / / nh kai le jh nián/dudshao nián chb | qí le jh nián/dudshao nián zìxíngchb 8 / zúqiúchfng yiu dud cháng/dudshao mh cháng 9 nh gbge yiu dud gao 10 balí lí lúnden yiu dud yufn
Exercise 9.2 1 Shall we go to his place to visit him next Monday? 2 How do you get to the bus station? 3 What is the traffic like in London? 4 How can I get to the cinema (from here)? 5 How about going to the pub for a beer tomorrow evening? 6 What is the weather like in Beijing? 7 What are the goods like in that shop? 8 Let’s go on holiday next month./Why don’t we go on holiday next month?
279
Key to exercises
Exercise 9.3 1 nh chc le dudshao 2 ( ) / nh zgn(me) yàng/zgnme qù lúnden 3 ta wèi shénme líkai 4 ( ) / nh zhjnbèi dai dud jij/dud cháng shíjian 5 nh zgnme zuò zhèi gè dàngao 6 ( ) ( ) nh de xcn fángzi (shì) zgnme yàng (de) 7 nh yiu dudshao qián 8 ( ) (nèi gè) diànyhng zgnme yàng 9 ( ) ( ) zánmen (qù) hb (yc) bbi jij | zgnme yàng 10 nh wèi shénme xué zhdngwén 11 wi zgnme rènshi xifo lh 12 nh rènwéi nèi wèi zhdngwén lfoshc zgnme yàng 13 nh zgnme yàng qù shàngban 14 / nh dgng le ta dud jij/dud cháng shíjian le 15 ( ) ta shuì le jh (gè) / xifoshí/jh gè zhdngtóu 16 / ( ) nhmen kai le / nhmen jh tian/dudshao tian (de) chb kaichb kai le jh tian/dudshao tian 17 / nh ( ) dgng le dud jij/dud cháng shíjian (de) chb / nh dgng chb dgng le dud jij/dud cháng shíjian 18 ( )( )/ nh ziu le dud yufn (de) (lù)/dudshao lù
Exercise 9.4 1 dud yufn 2 dud gao 3 dudshao 4 dud yufn 5 dud zhòng 6 dud dà 7 dudshao 8 dud dà 9 dudshao 10 / dud jij/dud cháng shíjian 11 / dud jij/dud cháng shíjian 12 / dudshao/dud cháng 13 / dud jij/dud cháng shíjian 14 dudshao
Drill 9.1
280
1 ( ) ( ) ( ) wimen jcn(tian) wfn(shang) qù hb (yc) bbi píjij | zgnme yàng 2 wimen míngtian qù tiàowj | zgnme yang 3 wimen míngnián qù dùjià | zgnme yàng 4 wimen xiànzài jifng zhdngwén | zgnme yàng 5 ( ) wimen xiàwj qù mfi (yc)xib xiangjao | zgnme yàng 6 ( ) wimen chá li jia (yc)difnr táng | zgnme yàng 7 wimen jcntian qù yóuying | zgnme yang 8 / ( ) ( ) wimen xcngqc liù/lhbài liù qù kàn (yc) chfng zúqiú (bh)sài | zgnme yàng 9 wimen xià gè yuè qù xué tàijíquán | zgnme yang 10
wimen san difn zhdng wánchéng zhèi jiàn gdngzuò | zgnme yàng 11 / wimen xcngqc èr/lhbài èr qù zhfo jcnglh | zgnme yàng 12 wimen yhhòu qù tànwàng ta | zgnme yàng 13 wimen jcntian xiàwj zài jia li xiexi | zgnme yàng 14 / wimen xià xcngqc wj/lhbài wj qù df qiú | zgnme yang 15 wimen míngtian xiàwj qù tc qiú | zgnme yang
Key to exercises
Drill 9.2 1 / 2 3 4 5 6 / shíjian 7 shíjian 8 9 / cháng shíjian 10
nh zài nàr dai/dai le dud cháng shíjian nh zài nàr zhù le dud cháng shíjian nh zài nàr dgng le dud cháng shíjian nh zài nàr gdngzuò le dud cháng shíjian nh zài nàr xuéxí le dud cháng shíjian nh zài jijbajian dai/dai le dud cháng nh zài jia li xiexi le dud cháng ( ) nh kai le dud cháng shíjian (de) chb nh zài duzhdu lsyóu/lsxíng le dud nh rènshi ta dud cháng shíjian
1 / kai chb qù lúnden/dào lúnden qù yào dud cháng shíjian 2 / zuò fbijc qù bgijcng/dào bgijcng qù yào dud cháng shíjian 3 / zuò díshì qù huichbzhàn/dào huichb zhàn yào dud cháng shíjian 4 / ziulù qù dàxué/dào dàxué qù yào dud cháng shíjian 5 / zuò bashì jìn chéng qù/dào chéng li qù yào dud cháng shíjian 6 / qí zìxíngchb qù nh jia/dào nh jia qù yào dud cháng shíjian 7 / ziulù qù yínháng/dào yínháng qù yào dud cháng shíjian 8 ( zuò díshì qù ) / ( ) (chángtú) qìchbzhàn/dào (chángtú) qìchbzhàn yào dud cháng shíjian 9 / qí zìxíngchb qù zúqiú chfng/dào zúqiúchfng qù yào dud cháng shíjian 10 / ziulù qù yóujú/dào yóujú qù yào dud cháng shíjian
Unit 10 Exercise 10.1 1 lóufáng 3
yc gè hgn dà de yóuyingchí 2 bái mao 4 / yc zhc/gè dà wfn 5
xcn 281
Key to exercises
yc gè mgilì de huayuán 6 ( ) yc gè xifo hái(zi) 7 yc gè yiuqù de diànyhng 8 yc chfng jcngcfi de bhsài 9 ( ) xcnxian (de) shecài 10 hgn dud qián 11 yc liàng jiù chb 12 shífbn zhòng de xíngli 13 ganjìng de ycfu 14 / yc jian zhgngqí de wùzi/fángjian 15 hgn xiázhfi de jibdào 16 gjlfo de chéngshì 17 yc gè fbicháng hfo de ycnyuèhuì 18 zang xiézi
Exercise 10.2 1 3
jcntian tianqì hgn hfo 2 ta hgn yiu qián zhèi gè shafa bù hgn shefu 4 nèi gè jiàoshì fbicháng ganjìng 5 wi dìdi bù tài gao 6 zhèi chfng bhsài bù shífbn jcngcfi 7 dì shang ddu shì hónghonglqlq de wánjù 8 wáng xiansheng shì gè fbicháng yiuqù de rén
Exercise 10.3 1 ( ) / bgijcng shì (yc) gè shífbn/fbicháng gjlfo de chéngshì 2 nèi bgn jiù she bù tài guì 3 ( ) (zhèi gè) túshegufn fbicháng dà 4 / ( ) wi méi yiu xcn ycfu/wi (lián) yc jiàn xcn ycfu yg méi yiu 5 / nèi xib xian hua hgn mgilì/piàoliang ( xianhua has become a set expression for ‘fresh flowers’, not: xcnxian de huar) 6 ( ) nèi shuang xié(zi) tài dà 7 zhèr de tianqì zhbn hfo 8 ( ) nèi tiáo jib(dào) bù gòu ganjìng 9 wi bù xhhuan bù xcnxian de niúnfi 10 nèi bbi kafbi tài tián
Exercise 10.4 D 1 gaodàdà de xifohuizi
lù páng zuò zhe yc gè gao2
D xifo wáng zhfng zhe wanwan de méimao | gaogao de bízi | xifoxifo de zuhba hé yc shuang dàdà de yfnjing | liú zhe yc tóu zhgngzhengqíqí de dufn fà 3
282
zhè shì yc jian ganganjìngjìng de fángjian | báibái de chuángdan | lánlán de chuanglián | hónghóng de lúhui | ggi nh yc D zhing sheshushìshì de gfnjué 4
ta nèi pjpusùsù de yczhuó | dàdafangfang de jjzhh | tiántianmgimgi de shbngycn géi rén liú xià le hgn shbnkè de yìnxiàng
Key to exercises
Exercise 10.5 1 3 4
nèi xib shì shéi de 2 zhèi xib shì wi de bái qúnzi shì nh de | hóng de shì wi de ( ) wimen méi yiu (rènhé) xcn de 5 dà de nèi xib hgn guì | xifo de nèi xib yg bù piányi 6 ( ) zhèi xib gùshi tài cháng | nà lifng gè (gùshi) bù cháng 7 zhèi gè bbizi hgn zang | wi yào yc gè ganjìng de 8 zhèi san gè xuésheng qù rìbgn | nf lifng gè qù zhdngguó 9 wi xhhuan zhè lifng bgn she | nh xhhuan nf lifng bgn 10 ngi xib shì nh de
Drill 10.1 1 a / zhèi píng jij guì shì guì | kgshì/bùguò hgn hfohb b / zhèi píng jij guì shì bù guì | kgshì/bùguò bù hfohb 2 a / nèi gè pínggui xifo shì xifo | kgshì/bùguò hgn hfochc b / nèi gè pínggui xifo shì bù xifo | kgshì/bùguò bù hfochc 3 a / nèi bf yhzi fi shì fi | kgshì/bùguò hgn hfozuò b / nèi bf yhzi fi shì bù fi | kgshì/bùguò bù hfozuò 4 a / zhèi shiu gb nán chàng shì nán chàng | kgshì/bùguò hgn hfotcng b ( ) / zhèi shiu gb nán (chàng) shì bù nán chàng | kgshì/bùguò bù hfotcng 5 a / nèi gè huapíng piányi shì piányi | kgshì/bùguò bù hfokàn b / nèi gè huapíng piányi shì bù piányi | kgshì/bùguò hgn hfokàn 6 a / nèi zhc bh jiù shì jiù | kgshì/bùguò hgn hfoxig b / nèi zhc bh jiù shì bù jiù | kgshì/bùguò bù hfoxig 7 a / zhèi bbi niúnfi lgng shì lgng | kgshì/bùguò hgn xcnxian b / zhèi bbi niúnfi lgng shì bù lgng | kgshì/bùguò bù xcnxian 8 a / zhèi tiáo jibdào ganjìng shì ganjìng | kgshì/bùguò bù zhgngqí b / zhèi tiáo jibdào ganjìng shì bù ganjìng | kgshì/bùguò hgn zhgngqí 9 a / nèi gè rén cdngming shì
283
Key to exercises
cdngming | kgshì/bùguò bù lfoshi b / nèi gè rén cdngming shì bù cdngming | kgshì/bùguò hgn lfoshi 10 a / nèi zuò lóufáng gjlfo shì gjlfo | kgshì/bùguò bù piàoliang b / nèi zuò lóufáng gjlfo shì bù gjlfo | kgshì/bùguò hgn piàoliang
Drill 10.2 1 / zhèi píng jij / ycdifnr yg/ddu bù guì | zhèi píng jij ycdifnr yg/ddu bù hfohb 2 / / nèi gè pínggui ycdifnr yg/ddu bù xifo | nèi gè pínggui yidifnr yg/ddu bù hfochc 3 / / nèi bf yhzi ycdifnr yg/ddu bù fi | nèi bf yhzi ycdifnr yg/ddu bù hfozuò 4 / / zhèi shiu gb ycdifnr yg/ddu bù nán chàng | zhèi shiu gb ycdifnr yg/ddu bù hfotcng 5 / nèi gè / huapíng ycdifnr yg/ddu bù piányi | nèi gè huapíng ycdifnr yg/ddu bù hfokàn 6 / nèi / zhc bh ycdifnr yg/ddu bù jiù | nèi zhc bh ycdifnr yg/ddu bù hfoxig 7 / / zhèi bbi niúnfi ycdifnr yg/ddu bù lgng | zhèi bbi niúnfi ycdifnr yg/ddu bù xcnxian 8 / / zhèi tiáo jibdào ycdifnr yg/ddu bù ganjìng | zhèi tiáo jibdào ycdifnr yg/ddu bù zhgngqí 9 / / nèi gè rén ycdifnr yg/ddu bù cdngming | nèi gè rén ycdifnr yg/ddu bù lfoshi 10 / / nèi zuò lóufáng ycdifnr yg/ddu bù gjlfo | nèi zuò lóufáng ycdifnr yg/ddu bù piàoliang
Unit 11 Exercise 11.1
284
1 ta shì wi de línje 2 wi de mèimei hgn piàoliang 3 ( ) zuótian (shì) xcngqc èr 4 wi de chb shì hóng de 5 zhèi tiáo yú shì huó de 6 wimen de fángjian hgn ganjìng 7 nèi gè gùshi hgn yiuqù 8 zhèi xib shecài hgn xcnxian 9 zhèi tiáo qúnzi bù tài zang 10 ycnyuèhuì fbicháng jcngcfi 11 zhèi xib ycfu ddu shì jiù de 12 nèi fù yfnjìng shì shéi/shuí de
Exercise 11.2 1 xifo wáng méi yiu giu 2 huayuán li méi yiu hgn dud huar 3 tamen ddu bù shì ycngguó rén 4 zhèi zhuàng fángzi bù shì ta de 5 nèi bbi kafbi bù shì wi péngyou de 6 lóuxià méi yiu rén 7 ta bù shì jcnglh 8 ta méi yiu lifng jiàn xíngli 9 wi de tóngxué bù ddu shì zhdngguó rén 10 túshegufn hòumian bù shì diànyhngyuàn
Key to exercises
Exercise 11.3 1 chduti li yiu xìnzhh 2 nèi fú huàr hgn mgi 3 zhèi tiáo shé shì huó de 4 wi méi yiu shiutào 5 ta bù shì jcnglh 6 shù xià méi yiu tùzi 7 nèi tiáo kùzi bù shì wi de 8 shejià shang ddu shì she
Exercise 11.4 1 2
/
guìzi/ycguì li yiu lifng jiàn hóng máoyc chúfáng li yiu yc gè dà lúzi 3 shejià shang yiu hgn dud she 4 jiàoshì li yiu hgn dud xuésheng 5 yóuyingchí li ddu shì rén 6 / fángjian/wùzi li yc bf yhzi yg méi yiu 7 chduti li shénme yg méi yiu 8 huayuán li méi yiu huar 9 bàngdngshì li méi yiu diànhuà 10 shanjifo xià yiu yc qún yáng 11 fàndiàn duìmiàn shì diànyhngyuàn 12 gud li yiu hgn dud fàn 13 píngzi li zhh yiu ycdifnr niúnfi 14 dìbfn shang ddu shì wánjù 15 ( (nèi dòng) fángzi li méi yiu rén )
Exercise 11.5 1 zhè shì (yc zhang) chbpiào | bù ( ) ( ) shì (yc zhang) diànyhngpiào 2 nà shì yc duì yuanyang | bù shì yc duì pjtdng de yazi 3 / nèi xib shì tjdòu/mflíngshj | bù shì fanshj 4 zhèi xib shì mìfbng | bù shì cangying 5 zhè shì qìyóu | bù shì càiyóu 6 nà shì zhang jcnglh | bù shì lh gdngchéngshc 7 wàimian zhh yiu yc liàng zìxíngchb | méi
285
Key to exercises
yiu qìchb 8 hézi li yiu zhezi | dànshì méi yiu grhuán 9 qiáng shang zhh yiu yc fú dìtú | méi yiu huàr 10 ( ) wi yiu yc bao (xiang)yan | dànshì méi yiu huichái 11 chúfáng li yiu yc gè lúzi | méi yiu bcngxiang 12 wi zhh yiu yc bf dao | méi yiu jifndao 13 zhèi xib ddu bù shì ta de 14 nèi xib bù ddu hfo 15 nèi xib ddu bù hfo
Drill 11.1 1 / wi shì míngnián qietian qù zhdng guó/dào zhdngguó qù 2 ( ) wi shì hòunián huí (lái) ycngguó 3 wi bù shì zuò chuán qù 4 wi shì zuò fbijc qù 5 / nh shì shénme shíhou qù zhdngguó/dào zhdngguó qù 6 / nh míngnián shì qù nfr/shénme dìfang 7 / shì nh míngtian qù zhdngguó/dào zhdngguó qù ma 8 ( / ) ( / ) shì wi péngyou (míngtian qù zhdngguó/dào zhdngguó qù) | bù shì wi (míngtian qù zhdngguó/dào zhdngguó qù) 9 nh péngyou shì zuótian ziu de ma 10 ( ) bù (shì) | ta shì qiántian ziu de 11 ta shì zuò fbijc ziu de 12 / ( ) ta shì xcngqc liù / lhbài liù huí (lái) ycngguó 13 ( ) (zhè) shì shéi zuò de 14 ( ) (zhè) shì ta zuò de ma 15 ( ) (zhè) bù shì ta zuò de | shì ta zuò de
Drill 11.2
286
1 nh mfi de nèi píng niúnfi hgn xcnxian | wi mfi de nèi píng bù xcnxian 2 zhèi zhang zhudzi shì fang de | nèi zhang shì yuán de 3 ta de she hgn yiu yìsi | wi de ycdifn yìsi ddu méi yiu 4 bàba de chb shì lán de | mama de shì hóng de 5 ( ) zhèi jiàn chènshan shì wi de | nèi jiàn shì shéi de (ne) 6 nèi tiáo kùzi gòu cháng | zhèi tiáo bù gòu cháng 7 / ta de péngyou ddu hgn yiu qián | wi de péngyou ddu méi qián/hgn qióng 8 nh de fángjian hgn ganjìng | ta de bù gòu ganjìng 9 zhang xiansheng de mf shì hbi de | lh tàitai de shì bái de 10 zhèi xib pínggui hgn guì | nèi xib hgn piányi
Unit 12
Key to exercises
Exercise 12.1 1
fbijc bh huichb kuài Planes are faster than trains. 2 ffguó gbn mgiguó bù ycyàng dà France and America are not the same size. 3 chentian bh ddngtian nufnhuo Spring is warmer than winter. 4 mao bh lfohj xifo de dud Cats are much smaller than tigers. 5 a’grbbisc shan méiyiu xcmflayf shan nàme gao The Alps aren’t as high as the Himalayas. 6 zhdngguó de rénkiu bh éguó de rénkiu dud China’s population is bigger than Russia’s. 7 jcnzìtf hé chángchéng ycyàng yiumíng The Pyramids and the Great Wall are equally famous. 8 xifo lh méiyiu lfo zhang nàme qínfèn Xiao Li is not as diligent as Lao Zhang. 9 chfofàn bh chfomiàn hfochc de dud Fried rice is much nicer than fried noodles. 10 nh de xíngli bh wi de xíngli zhòng lifng gdngjcn Your luggage is 2 kilos heavier than mine.
Exercise 12.2 1 jcngyú bh shayú dà Whales are bigger than sharks. 2 shèxiàngjc bh zhàoxiàngjc guì Video cameras are more expensive than cameras. 3 pínggui bh táozi yìng Apples are harder than peaches. 4 nèi gè chéngshì bh zhèi gè chéngshì mgilì That city is more beautiful than this one. 5 ycngguó de xiàtian bh chentian rè Summer in Britain is hotter than spring. 6 déyj bh ffyj nán German is more difficult than French. 7 wi bh nh zhòng I am heavier than you. 8 chángjiang bh huánghé cháng The Yangtze River is longer than the Yellow River. 9 nh de jianbfng bh ta de kuan Your shoulders are broader than his. 10 nèi shiu gb bh zhèi shiu gb hfotcng That song is nicer than this one.
Exercise 12.3 1 pàng de dud 2 cháng de dud 3 / piányi ycdifnr/ycxib 4 / shòu ycdifnr/ycxib 5 xifo lifng suì 6 guì lifng bàng 7 yiuqù de dud 8 / piàoliang ycdifnr/ycxib 9 xcnxian de dud 10 / ganjìng ycdifnr/ycxib
287
Key to exercises
Exercise 12.4 1 7
zuì 2 gèng 3 gèng 8 gèng 9
hái (yào) 4 zuì hái (yào) 10
5 zuì 6 hái (yào)
zuì
Exercise 12.5 1 ta bh qíta rén lái de zfo ta lái de bh qíta rén zfo 2 ta ziu de bh ta màn ta bh ta ziu de màn 3 zuótian ta shuì de bh wi wfn zuótian ta bh wi shuì de wfn 4 wi qczi kaichb kai de bh wi hfo wi qczi kaichb bh wi kai de hfo 5 wi de yc gè tóngxué chànggb chàng de bh wi hfo wi de yc gè tóngxué chànggb bh wi chàng de hfo 6 wi zhàngfu df wfngqiú df de bh wi hfo wi zhàngfu df wfngqiú bh wi df de hfo 7 wi gbge bh wi gao yc ycngcùn 8 mèimei bh jigjie qcng bàn gdngjcn 9 sdngshj yiu lfoshj nàme dà ma 10 zhèi zhuàng fángzi méiyiu nèi zhuàng nàme piàoliang
Exercise 12.6 1 wi yuè lái yuè è 2 chúshc yuè lái yuè pàng 3 / nèi ph mf zài bhsài zhdng yuè pfo yuè màn/pfo de yuè lái yuè màn 4 zúqiú bhsài yuè lái yuè jcngcfi 5 lù yuè lái yuè kuan 6 zjfù de bìng yuè lái yuè yánzhòng 7 ta yuè hb yuè zuì 8 yuè kuài yuè hfo 9 ta yuè chàng wi yuè bù gaoxìng 10 ( ) (cài) yuè là wi yuè xhhuan
Drill 12.1
288
1 a zhèi zhang zhudzi bù bh nèi zhang ( ) nèi zhang zhudzi (zhudzi) ganjìng b ( ) méiyiu zhèi zhang (zhudzi) ganjìng 2 a ( ) zhèi gè fángjian bù bh nèi gè (fángjian) zhgngqí b ( nèi gè fángjian méiyiu zhèi gè (fángjian) zhgngqí ) 3 a zhèi gè rén bù bh nèi gè rén lfoshi b nèi gè rén méiyiu zhèi gè rén lfoshi 4 a ( zhèi gè gùshi bù bh nèi gè (gùshi) yiuqù )
b ( ) nèi gè gùshi méiyiu zhèi gè (gùshi) yiuqù 5 a ( ) zhèi chfng bhsài bù bh nèi chfng (bhsài) jcngcfi b ( ) nèi chfng bhsài méiyiu zhèi chfng (bhsài) jcngcfi 6 a ( ) zhèi tiáo qúnzi bù bh nèi tiáo (qúnzi) cháng b ( ) nèi tiáo qúnzi méiyiu zhèi tiáo (qúnzi) cháng 7 a ( ) zhèi shuang xiézi bù bh nèi shuang (xiézi) xifo b ( ) nèi shuang xiézi méiyiu zhèi shuang (xiézi) xifo 8 a ( ) zhèi jiàn ycfu bù bh nèi jiàn (ycfu) zang b ( ) nèi jiàn ycfu méiyiu zhèi jiàn (ycfu) zang 9 a ( ) zhèi liàng chb bù bh nèi liàng (chb) piàoliang b ( ) nèi liàng chb méiyiu zhèi liàng (chb) piàoliang 10 a ( ) zhèi zuò lóufáng bù bh nèi zuò (lóufáng) gjlfo b ( ) zhèi zuò lóufáng méiyiu zhèi zuò (lóufáng) gjlfo 11 a ( ) zhèi xib shecài bù bh nèi xib (shecài) xcnxian b ( ) nèi xib shecài méiyiu zhèi xib (shecài) xcnxian 12 a ( ) zhèi jia shangdiàn bù bh nèi jia (shangdiàn) dà b ( ) nèi jia shangdiàn méiyiu zhèi jia (shangdiàn) dà 13 a ( ) zhèi bbi kafbi bù bh nèi bbi (kafbi) tián b ( ) nèi bbi kafbi méiyiu zhèi bbi (kafbi) tián 14 a zhèi gè háizi bù bh nèi gè (háizi) cdngming b nèi gè háizi méiyiu zhèi gè (háizi) cdngming 15 a ( ) zhèi jiàn xíngli bù bh nèi jiàn (xíngli) zhòng b ( ) nèi jiàn xíngli méiyiu zhèi jiàn (xíngli) zhòng 16 a ( ) zhèr de tianqì bù bh nàr de (tianqì) hfo b ( ) nàr de tianqì méiyiu zhèr de (tianqì) hfo 17 a ( ) zhèi kuài jiang bù bh nèi kuài (jiang) là b ( ) nèi kuài jiang méiyiu zhèi kuài (jiang) là 18 a zhèi gè yùndòngyuán bù bh nèi gè yùndòngyuán gao b nèi gè yùndòngyuán méiyiu zhèi gè yùndòngyuán gao 19 a ( ) zhèi zhing huar bù bh nèi zhing (huar) xiang b ( ) nèi zhing huar méiyiu zhèi zhing (huar) xiang 20 a qùnián ddngtian bù bh jcnnián ddngtian lgng b jcnnián ddngtian méiyiu qùnián ddngtian lgng
Key to exercises
Drill 12.2 1
wi bh dìdi zhòng wj gdngjcn 2 wi de péngyou bh wi fi san cùn 3 nh de xíngli bh wi de zhòng sì gdngjcn 4
jcntian
289
Key to exercises
bh zuótian nufn lifng dù 5 qùnián ddngtian bh jcnnián lgng lifng | san dù 6 zhèi tiáo lù bh nèi tiáo kuan lifng gdngchh 7 ta de kùzi bh nh de cháng yc | lifng cùn 8 nh de zhàoxiàngjc bh wi de guì yc bfi kuài qián 9 nh de bifo bh wi de kuài shí fbn zhdng 10 zhèi gè lùchéng bh nèi gè yufn èr shí gdnglh zuiyòu 11 wi bh ta zfo yc gè zhdngtóu qhchuáng 12 ta bh wi wfn yc nián bìyè 13 tamen bh wimen zfo lifng tian dòngshbn 14 ( ) ta bh wi wfn lái bàn (gè) xifoshí 15 huichb bh qìchb zfo dào wj fbn zhdng
Unit 13 Exercise 13.1 1 shang 2 li 3 ( ) páng(bian) 4 wài (dh)xia 6 fùjìn 7 nàr 8 sìzhdu ddngmiàn/ ddngbian 10 / zuibian/miàn, yòubian/miàn 11 pángbian 12 zhdngjian /( )/( ) lh(mian)/(bian)/(tou) 14 / zuimiàn/bian zhdngjian 16 / yòumiàn/bian 17 / / bian/tou 18 zhduwéi
5 ( 9
)
/ 13 15 hòumian/
Exercise 13.2 1 ( ) zài dàxué (li) 2 zài chbzhàn 3 ( )/( )/( ) zài guìzi lh(mian)/(bian)/(tou) 4 / / zài chéngshì bgimiàn/bgibian/bgibù 5 / zài hézi/xiangzi li 6 ( )/( ) zài chuáng shàng(mian)/(bian) 7 zài wezi zhdngjian 8 zài shanjifo xià 9 zài chb shang 10 zài shù (dh)xia 11 zài mama pángbian ( ) 12 / / zài yóuyingchí shàngbian/mian/tou 13 / / zài túshegufn qiánmian/bian/tou 14 / / zài fángzi hòumian/bian/tou 15 / / zài hé bian/páng/ pángbian 16 ( ) ( )/( ) zài zhud(zi) shàng(mian)/(bian) 17 zài gdngyuán fùjìn 18 zài háizi zhduwéi 19 / zài zjfù jia li/nàr 20 / zài xcmiàn/bian
Exercise 13.3 1 290
( )/( ) bàozhh zài zhudzi shàng(mian)/(bian) 2 tamen zài wezi li kaihuì 3
tàiwùshì hé shì ycngguó yiumíng de hé 4 / ycshbng zài bìngrén de chuáng bian/ pángbian zhàn le ychuìr | méiyiu shud huà 5 correct 6 correct 7 nh de yàoshi zài mén shang 8 D ta zài mén qián zhàn sheshu zài lúnden gdngzuò 9 D jcnyú zài shuhchí li yóu zhe zhe 10 correct 11 12 / diànyhngyuàn zài xiédiàn zuimiàn/ zuibian 13 bàozhh shang yiu bù shfo gufnggào 14 tian shang méi yiu yún
Key to exercises
Exercise 13.4 1
lóushàng; zhdngjian 2 lóuxià; xiàmian
ddngmiàn;
zuibian 3
Exercise 13.5 D niúròu zài gud li zhj zhe 2 wi de yc gè péngyou zài yc jia ycyuàn gdngzuò wi de yc gè péngyou zài yc jia ycyuàn li gdngzuò 3 wimen zhù zài balí D wimen zài balí zhù zhe) wimen zài balí zhù (not: * 4 ta zài bówùgufn dgng nh ta zài bówùgufn li dgng nh 5 yiu yc qún yáng zài shanjifo xià chc cfo 6 wi sheshu zài hfi bian shài tàiyang 1
Drill 13.1 1 a dìdi zài shafa shang shuìjiào Younger brother is sleeping on the sofa. b dìdi dào shafa shang qù shuìjiào Younger brother went to have a sleep on the sofa. 2 a yéye zài gdngyuán li df tàijíqián Grandpa is practising T’ai Chi in the park. b yéye dào gdngyuán li qù df tàijíqián Grandpa went to practise T’ai Chi in the park. 3 a bàba zài hé bian diàoyú Father is fishing by the river. b bàba dào hé bian qù diàoyú Father has gone fishing by the river. 4 a mama zài chéng li mfi cài Mother is buying food in town. b mama dào chéng li qù mfi cài Mother has gone to buy food in town. 5 a nfinai zài péngyou jia df májiàng Grandma is playing mah-jong at a friend’s place. b nfinai dào péngyou jia qù df májiàng Grandma has gone to play mah-jong at a friend’s place. 6 a
291
Key to exercises
292
mèimei zài xuéxiào li xué chànggb Younger sister is taking singing lessons at school. b mèimei dào xuéxiào li qù xué chànggb Younger sister has gone to take singing lessons at school. 7 a gbge zài túshegufn kàn she Elder brother is doing some reading in the library. b gbge dào túshegufn qù kàn she Elder brother has gone to the library to do some reading. 8 a bóbo zài bówùgufn gdngzuò Uncle (father’s elder brother) works in the museum. b bóbo dào bówùgufn qù gdngzuò Uncle (father’s elder brother) has gone to work at the museum. 9 a sheshu zài càiyuán li zhòng cài Uncle (father’s younger brother) is planting vegetables in the vegetable garden. b sheshu dào càiyuán li qù zhòng cài Uncle (father’s younger brother) has gone to the vegetable garden to plant vegetables. 10 a gemj zài huayuán li zhòng hua Aunt (father’s elder sister) is planting flowers in the garden. b gemj dào huayuán li qù zhòng hua Aunt (father’s elder sister) has gone to plant flowers in the garden. 11 a ( ) yímj zài ycyuàn (li) kànbìng Aunt (mother’s sister) is seeing a doctor in the hospital. b ( ) yímj dào ycyuàn (li) qù kànbìng Aunt (mother’s sister) has gone to see a doctor in the hospital. 12 a jiùjiu zài caochfng shang pfobù Uncle (mother’s brother) is jogging on the sports ground. b jiùjiu dào caochfng shang qù pfobù Uncle (mother’s brother) has gone jogging on the sports ground. 13 a bóbo hé bómj zài balí dùjià Uncle and Aunt (father’s elder brother and his wife) are spending their holidays in Paris. b bóbo hé bómj dào balí qù dùjià Uncle and Aunt (father’s elder brother and his wife) have gone to spend their holidays in Paris. 14 a gemj hé gezhàng zài bgijcng lsxíng Uncle and Aunt (father’s elder sister and her husband) are on a tour in Beijing. b gemj hé gezhàng dào bgijcng qù lsxíng Uncle and Aunt (father’s elder sister and her husband) have gone to Beijing on a tour. 15 a yímj hé yízhàng zài lúnden kàn qiúsài Aunt and Uncle (mother’s sister and her husband) are watching a match in London. b yímj hé yízhàng dào lúnden qù kàn qiúsài Aunt and Uncle (mother’s sister and her husband) have gone to London to watch a match. 16 a gbge hé wi zài diànyhngyuàn kàn diànyhng My elder brother and I are seeing a film at the cinema. b gbge hé wi dào diànyhngyuàn qù kàn diànyhng My elder brother and I are going to the cinema to see a film. 17 a ( ) wi hé dìdi zài jia (li) kàn diànshì My younger brother and I are watching
television at home. b wi hé dìdi huí jia qù kàn diànshì My younger brother and I are going home to watch television. 18 a gbge hé ta de ns péngyou zài kafbigufn hb kafbi Elder brother and his girlfriend are drinking coffee in a coffee bar. b gbge hé ta de ns péngyou dào kafbigufn qù hb kafbi Elder brother and his girlfriend are going to a coffee bar to have a coffee. 19 a jigjie hé ta de nán péngyou zài yc jia shangdiàn li mfi ycfu Elder sister and her boyfriend are buying clothes in a shop. b ( ) jigjie hé ta de nán péngyou dào yc jia shangdiàn li qù mfi ycfu Elder sister and her boyfriend have gone to a shop to buy clothes. 20 a (D) jiùmu dài (zhe) wi zài wàimàidiàn mfi wàimài Aunt (maternal brother’s wife) is taking me with her to buy take-away food at a Chinese take-away. b (D) jiùmu dài (zhe) wi dào wàimàidiàn qù mfi wàimài Aunt (maternal brother’s wife) is taking me with her to a Chinese take-away to buy take-away food. 21 a ( ) jiùjiu dài (zhe) wi dìdi zài shatan shang qí mf Uncle (mother’s brother) is taking my younger brother with him to go horse riding on the beach. b (D) jiùjiu dài (zhe) wi dìdi dào shatan shang qù qí mf Uncle (mother’s brother) is taking my younger brother with him to the beach to go horse riding. 22 a (D) sheshu dài (zhe) gbge zài jib shang qí zìxíngchb Uncle (father’s younger brother) is taking my elder brother cycling with him on the street. b (D) sheshu dài (zhe) gbge dào jib shang qù qí zìxíngchb Uncle (father’s younger brother) is taking my elder brother with him to go cycling on the street.
Key to exercises
Drill 13.2 1 lhmian bh wàimian hfo 2 wi zài diànyhngyuàn lhmian dgng nh 3 lóushàng méi yiu rén 4 nh hòumian yiu yc gè rén 5 zhèr lhmian yiu gdngcè ma 6 ( ) (zài) zàopiàn li | wi bàba zuò zài zuibian | wi mama zuò zài yòubian | wi zhàn zài tamen zhdngjian 7 / nh zhù zài zhdngguó shénme dìfang/nfr 8 nh de chb qhng tíng zài túshegufn qiánmian de mflù shang 9 / big zuò zài nèi bf/zhang yhzi shang 10 / ta de qián fàng zài chuáng dhxià de yc gè xiangzi/hézi li 293
Key to exercises
Unit 14 Exercise 14.1 1 wi míngtian qù bgijcng míngtian wi qù bgijcng 2 wi qù bgijcng lifng tian 3 wi qùnián qù le bgijcng qùnián wi qù le bgijcng 4 wi lifng tian hòu qù bgijcng lifng tian hòu wi qù bgijcng 5 wi jiéhen qián qù bgijcng jiéhen qián wi qù bgijcng 6 míngnián wi yào qù bgijcng lifng cì wi míngnián yào qù bgijcng lifng cì míngnián wi yào qù lifng cì bgijcng wi míngnián yào qù lifng cì bgijcng 7 wi bàn nián méi qù bgijcng le wi méi qù bgijcng bàn nián le 8 wi mgi nián xiàtian qù bgijcng bàn gè yuè mgi nián xiàtian wi qù bgijcng bàn gè yuè
Exercise 14.2 1 ta qiánnián qù le shànghfi qiánnián ta qù le shànghfi 2 ( ) mama shàng gè yuè líkai (le) ycngguó ( ) shàng gè yuè mama líkai (le) ycngguó 3 gbge xcngqc èr qù yóuying le xcngqc èr gbge qù yóuying le 4 ( ) ( ) yéye mgi tian (ddu) kàn lifng | san gè xifoshí (de) xifoshud ( ) ( ) mgi tian yéye (ddu) kàn lifng | san gè xifoshí (de) xifoshud 5 wi xiànzài zài xuéxí hànyj xiànzài wi zài xuéxí hànyj 6 wimen quán jia xià gè zhdumò qù hfibcn xià gè zhdumò wimen quán jia qù hfibcn 7 ( ) wimen mgi gè xcngqc sì wfnshang (ddu) qù tiàowj ( ) mgi gè xcngqc sì wfnshang wimen (ddu) qù tiàowj 8 ( ) xifo zhang xià (gè) xcngqc yc qù yínháng ( ) xià (gè) xcngqc yc xifo zhang qù yínháng 9 qhng zài zhèr dgng wi wj fbn zhdng 10 wi qùnián qù tànwàng wi fùmj lifng cì qùnián wi qù tànwàng wi fùmj lifng cì ( ) ( ) wi qùnián qù tànwàng (le) lifng cì wi (de) fùmj ( ) ( ) qùnián wi qù tànwàng (le) lifng cì wi (de) fùmj 294
Exercise 14.3 1 correct 2 ta zài hfi li yóu le ychuìr ying 3 wi mfshàng shàngban 4 correct 5 wimen yingyufn jìde ta 6 correct 7 wi yhjcng xig le xìn le 8 duìzhfng ganggang kànjiàn xifo lh 9 correct 10 correct 11 ta lái le zhèr lifng cì 12 yéye hé nfinai jcntian sàn le bàn gè zhdngtóu bù/ yéye hé nfinai jcntian sànbù sàn le bàn gè zhdngtóu
Key to exercises
Exercise 14.4 1 I swam for two hours this morning. 2 My English friend stayed in China for two months. 3 They have been learning Chinese for two years now. 4 The meeting has been going on for 40 minutes./The meeting started 40 minutes ago. 5 My coursemates and I are going to play football tomorrow afternoon. 6 (My) younger sister was writing letters the whole evening. 7 Mr Wang and his wife are going to China on holiday next year. 8 He graduated last June. 9 My younger brother bought a pair of beautiful sports shoes. 10 My father often goes to work by bicycle. 11 I stayed at his place for half an hour on three occasions. 12 She danced for three hours that evening.
Exercise 14.5 1 / nh zài zhdngguó de shíhou cháng/chc guo mántou méiyiu 2 nh néng zài wàimian dgng ychuìr ma 3 zánmen zài gdngyuán li zuò ychuìr ba 4 / ( ) nh néng bang/tì wi kan(gufn) ychuìr háizi ma 5 ( ) wimen qù cfi le yc (gè) xifoshí cfoméi 6 ta kàn le ycxià nèi zhang zhàopiàn/ ta kàn le kàn nèi zhang zhàopiàn 7 ( ) qhng (nh) xian kàn ycxià jcntian de bàozhh/ ( ) qhng (nh) xian kàn yc kàn jcntian de bàozhh 8 ta zhgngzhgng yc nián méi hb guo jij le 9 wi rènshi ta san nián le 10 / wi yhjcng xh guo/ le zfo le
Drill 14.1 1 wi de línje xià gè yuè zài jia qhngkè wi de yc gè zhdng 2 xué tóngxué xià xcngqc zài yc jian jiàotáng jjxíng henlh 3 295
Key to exercises
wi xià xcngqc dào jiàotáng qù canjia henlh 4 jiùjiu qùnián zài zhdngguó canjia àolínphkè yùndònghuì 5 jigjie hé ta de nán péngyou shàng gè yuè dào duzhdu qù dùjià 6 yéye hé nfinai míngnián dào bgijcng qù tànwàng tamen de zhdngguó péngyou 7 wi de zhdngwén lfoshc liù gè yuè qián dào ycngguó lái kàn wi 8 gezhàng míngtian shàngwj dào ycyuàn qù dfzhbn 9 wi de lifng gè tóngxué xià xcngqc liù zài lúnden kàn zúqiúsài 10 / ( ) wi hé dìdi shàng xcngqc tian/rì zài dàxué fùjìn de yc gè gdngyuán li xué (df) tàijíquán
Drill 14.2 1 yiu yc gè ycngguó yùndòngyuán qùnián xiàtian zài xùnliàn zhdng san cì dfpò le zìjh de jìlù 2 ( ) ( ) / / yiu (yc) gè yínháng jcnglh qùnián sanyuè (fèn) zài zhdngguó dai/dai le lifng gè xcngqc/lhbài 3 wi de yc gè péngyou san nián qián zài ycngguó xué le lifng gè yuè de diànnfo 4 ( ) dìdi míngnián qietian dào zhdngguó qù xué lifng gè bàn yuè (de) zhdngwén 5 ( ) / ( ) wi qiántian zài jib shang qí le bàn (gè) xifoshí/bàn gè zhdngtóu (de) zìxíngchb 6 ( ) / yiu (yc) gè zhdngguó chúshc yc nián bàn qián zài diànshì shang bifoyfn le/yfnshì le hgn dud cì 7 ( ) ( ) wi fùmj zuó(tian) wfn(shang) zài huichbzhàn dgng le wi èr shí fbn zhdng 8 ( ) ( ) (wi) sheshu jcntian shàngwj zài hfitan shang shài le yc gè bàn xifoshí (de) tàiyang 9 / ( ) zánmen míngtian fàngxué hòu/xiàkè hòu dào gdngyuán qù sàn yc gè xifoshí (de) bù 10 ( ) / (wi) gbge mgi gè xcngqc/lhbài ddu zài yóujú gdngzuò lifng tian
Drill 14.3
296
1 ( ) bìngrén san tian lái ddu méi(yiu) chc shénme ddngxi 2 ( ) / lifng nián lái wi méi(yiu) kàn guo yc cì ycshbng/bìng 3 / zhgnggè xiàtian wi ddu dai/dai zài fùmj jia 4 zhgnggè yuè ta ddu zài jia li zhàogu háizi 5
( ) /
ta yc nián lái méi(yiu) chdu guo yan le 6 wi zhgnggè lhbài/xcngqc méi hb guo píjij le 7 ( ) ta mgi cì (lái) ddu dài yc píng jij lái 8 ( ) ( ) (jìn) jh nián lái wi (ddu) méi pèngjiàn guo ta le 9 / / ta yc nián/ mgi nián qù bgijcng yc cì/yc cì bgijcng 10 ( ) / tamen mgi (gè) xcngqc/yc xcngqc jiàn lifng cì miàn
Key to exercises
Unit 15 Exercise 15.1 1 8
zài 2 D zhe 3 zài 9 le 10 / le/guo 15 le
guo 4 D zhe 5 D zhe 6 guo 11 zài 12 zài
le 7 guo 13 zài 14
Exercise 15.2 1
( ) / ( ) ta (zhèng)zài ca chuang(hu) 2 tamen dào/lái guo zhèr 3 ( ) wi (zhèng)zài jiao hua 4 ( ) wi de péngyou (zhèng)zài hb píjij 5 ( D ) (nèi wèi) jiàoshc zhàn zhe jifngkè 6 ta tiào qh wj lái 7 ( ) ta (zhèng)zài kaichb 8 ta mfi le yc shuang xié 9 ( ) yéye D (zhèng)zài kàn diànshì 10 mama dài zhe yc dhng piàoliang de màozi
Exercise 15.3 1 qhlái xiàlái 6 xiàlái
2 xiàqù
xiàlái 7
3 qhlái
xiàqù 8
4 qhlái
qhlái 9
5 qhlái
10
Exercise 15.4 1 4
jifng xiàqù 2 xuéxí qhlái 3 xig qh xìn lái xué xiàqù 5 correct 6 chfo qh jià lái 7 yóu qh ying lái 8 correct 9 cóngming qhlái 10 correct
Drill 15.1 1
mèimei ke qhlái le Younger sister began to cry. 2 dìdi xiào qhlái le Younger brother began to laugh. 3 tóngxuémen chàng qh gb lái le The classmates
297
Key to exercises
began to sing. 4 bàba hé mama tiào qh wj lái le Mum and Dad began to dance. 5 tian lgng qh lái le It began to get cold. 6 tian xià qh yj lái le It began to rain. 7 gbge xué qh zhdngwén lái le Elder brother began to study Chinese. 8 jigjie chuan qh hóng qúnzi lái le Elder sister began wearing a red skirt. 9 tianqì rè qhlái le The weather began to get hotter. 10 báitian cháng qhlái le The days began to lengthen. 11 lfo lh hé xifo lh chfo qhlái le Old Li and Little Li began to quarrel. 12 nèi gè háizi chdu qh yan lái le That child began to smoke.
Drill 15.2 1 Uncle (mother’s brother) is wearing (a pair of) sunglasses. [description] [resultant state] 2 Younger sister walked in crying. [description] [manner of execution] 3 Father and uncle (his younger brother) are just having a chat. [narrative] 4 Younger brother is/was lying on the sofa. [description] [resultant state] 5 Mother is cooking in the kitchen. [narrative] 6 Aunt (mother’s brother’s wife) is wearing (a pair of) black shoes. [description] [resultant state] 7 It is raining outside. [narrative] 8 Grandpa is/was sitting in the garden. [description] [resultant state] 9 Elder sister is in the room writing a letter. [narrative] 10 Father as he spoke began to laugh/smile. [description] [manner of execution]
Drill 15.3 1 The children all stood up. [space] 2 The ladies all sat down. [space] 3 As they sat they began to chat. [time] 4 At this moment it began to snow outside. [time] 5 I can’t recall this matter. [time] 6 Younger sister as she spoke began to cry and she could not go on/say any more. [time] 7 We settled down there. [time] 8 At this moment the teacher walked in and the students/classmates went quiet. [time] 9 When the bus/train arrived at the stop/station it came to a halt [time] and the passengers all got off [space]. 10 Elder brother picked up a book [space], and, as he read it, he began to laugh/smile [time], and he could not go on reading any more [time].
Unit 16 Exercise 16.1 298
1 wi xifng xiexi ychuìr 2 nh yào zfo difnr qhchuáng 3 ta xifng qù zhdngguó lsyóu 4 nh xifng hb difnr shénme 5
nh yào hfohaor xuéxí wàitào
6
mama xifng mfi yc jiàn
Key to exercises
Exercise 16.2 1
néng kgn 7
2
huì 3 bìxe 8
gai 4 bì
néng
5
kgyh 6
huì;
Exercise 16.3 1 bù yuànyi 2 bù gfn 3 kgyh 4 bù kgn 5 bù xifng 6 yào/ xifng 7 gfn 8 dgi 9 bù bì 10 gai 11 bìxe 12 bù gai 13 kgyh 14 huì 15 néng 16 kgyh 17 bù néng 18 huì 19 huì 20 huì; bù néng 21 huì; néng 22 bù néng 23 néng 24 néng 25 huì 26 huì 27 néng 28 bù ycnggai
Exercise 16.4 1 nh huì kaichb ma 2 zhdumò huì xià yj ma 3 / nh xifng qù tànwàng/ kànwàng nh fùmj ma 4 / nh bìxe/gai qù fùxí gdngkè le 5 zhèi gè xcngqc wimen néng qù hfitan ma 6 / wi bìxe/dgi jìzhu ycnyuèhuì de shíjian 7 nhmen bù ycnggai dfjià 8 / / wi sanyuè(fèn)/míngnián sanyuè néng/kgyh xiejià ma 9 nh yuànyi bangzhù ta ma 10 / ta bù gfn chéng/zuò fbijc
Drill 16.1 1 Is he willing? 2 Do you want to go to town tomorrow? 3 You must persuade him. 4 Can you do shadow-boxing/T’ai Chi? 5 Don’t cheat! 6 Who can give me a hand? 7 Is there anyone here who can speak English? 8 Can you help me translate this sentence? 9 I must be off. 10 You ought to rest. (It’s time for you to have a rest.) 11 Who is willing to stay behind? 12 We must go back tomorrow. 13 Don’t you dare tell lies again! 14 Is it likely to be foggy tomorrow? 15 You must go and see a doctor.
Drill 16.2 1 a nh míngtian huí jia ma b nh míngtian bìxe huí jia ma c / nh míngtian xifng/yào
299
Key to exercises
huí jia ma d
nh míngtian néng huí jia ma e nh míngtian kgyh huí jia ma 2 a wi bù gfn gàosu ta b wi bù néng gàosu ta c wi bù huì gàosu ta de d wi bù yuànyi gàosu ta e / wi bù yòng/bùbì gàosu ta f wi bù gai gàosu ta 3 a nh yào xià yc zhàn xià chb ma b nh dgi xià yc zhàn xià chb ma c nh xià yc zhàn xià chb ma d / nh néng/kgyh xià yc zhàn xià chb ma e nh yuànyi xià yc zhàn xià chb ma 4 a / nh néng/kgyh bang wi yc gè máng ma b nh huì bang wi de máng ba c nh yuànyi bang wi yc gè máng ma d nh dgi bang wi yc gè máng e yào wi bang nh de máng ma f wi hgn xifng bang nh de máng | kgshì wi bù néng 5 a nh huì shud zhdngwén ma b nh néng shud zhdngwén ma c wi kgyh shud zhdngwén ma d yào wi shud zhdngwén ma e / wi bìxe/dgi shud zhdngwén ma f / wi gai shud zhdngwén | duì/shì ma g / wi huì shud ycngwén | nh bù bì/bù yòng shud zhdngwén h . . . wi hgn xifng shud ycngwén | kgshì . . .
Unit 17 Exercise 17.1 1 bù 2 ( ) méi(yiu) 3 ( ) méi(yiu) 4 ( ) méi(yiu) 5 ( ) méi(yiu) 6 bù 7 bù 8 bù 9 ( ) méi(yiu) 10 ( ) méi(yiu) 11 ( ) méi(yiu) 12 bù 13 bù 14 ( ) méi(yiu) 15 bù
Exercise 17.2
300
1 háizimen ddu bù xhhuan chc shecài None of the children like eating vegetables. 2 tamen yg méiyiu qù kàn jcngjù They didn’t go to watch the Beijing Opera either. 3 tf chcfàn qián chángcháng bù xh shiu He doesn’t often wash his hands before meals. 4 wi cónglái bù chduyan I have never smoked. 5 ta gangcái méi hb chá She didn’t drink any tea just now. 6 ta jcntian méi kàn diànshì He didn’t watch TV today. 7 ta nèi tian méi chc dàngao She didn’t touch the cake that day. 8 mèimei cónglái méi zuò guo fbijc (My) younger sister has never flown in a plane before.
Exercise 17.3 1
wi rènwéi nèi gè dá’àn bù duì wi rènwéi zhè bù zhíde dud xhang 3 wi cónglái méiyiu xhhuan guo ta 4 chuan dàyc
Key to exercises
2 ta méi
Exercise 17.4 1 ta bù kgyh zài nèi zhuàng fángzi de qiáng shang xig biaoyj 2 nh bù huì bao jifozi ma 3 jcnglh bù yuànyi jia chén xiansheng de gdngzc 4 / wi zhèi gè xcngqc/lhbài néng bù lái ma 5 ( ) ta lái ycngguó qián (cónglái) méi jiàn guo sdngshj 6 mèimei bù gfn qù línje nàr jiè yhzi 7 / kùzi tài dufn | dìdi bù kgn/yuànyi chuan 8 / shuhgui ycdifnr yg bù xcnxian | shuí/shéi yg/dàjia ddu bù xifng chc 9 ( ) zuótian xià dà yj | wimen méi(yiu) qù caochfng tc zúqiú 10 nh bù gai gàosu tamen zhèi jiàn shì 11 zhèi xib huar bù xiang | mìfbng bù lái cfi mì 12 cfoméi méiyiu táozi hfochc
Drill 17.1 1 Don’t you want to go to see a film? You don’t want to go and see a film? 2 Who doesn’t want to have meat? Who would like not to have meat (i.e. to have something other than meat)? 3 Are the children unwilling to have soft drinks? Are the children willing to go without soft drinks? 4 Are the girls unwilling to wear skirts? Are the girls willing not to wear skirts (i.e. to wear something else)? 5 Don’t you want to have coffee? Would you like not to have coffee (i.e. have something else)? 6 Some people don’t want to get up very early. Some people want not to get up very early (i.e. stay in bed). 7 Doesn’t she dare to go home? Does she dare not to go home (i.e. go somewhere else)? 8 Who is unwilling to learn Chinese? Who is willing to forgo learning Chinese? 9 There isn’t anyone who is unwilling to learn Chinese. There isn’t anyone willing not to learn Chinese (i.e. to learn something/anything else). 10 Who cannot drink wine? Who can give up drinking wine?
Drill 17.2 1 a wi bàba bù zài zài cèsui li chduyan le My father is not smoking in the lavatory anymore. b
301
Key to exercises
wi bàba zài yg bù zài cèsui li chduyan le My father will never smoke in the lavatory again. 2 wi línje bù zài yfng giu le My neighbour doesn’t keep a dog anymore. wi línje zài yg bù yfng giu le My neighbour will never keep a dog again. 3 ta de ns péngyou bù zài hb jij le His girlfriend is not drinking (wine) anymore. ta de ns péngyou zài yg bù hb jij le His girlfriend will never drink (wine) again. 4 ta jiùjiu bù zài djbó le Her uncle (mother’s brother) is not gambling anymore. ta jiùjiu zài yg bù djbó le Her uncle (mother’s brother) will never gamble again. 5 ta hb kafbi bù zài jia táng le She isn’t having sugar in her coffee anymore. ta hb kafbi zài yg bù jia táng le She will never have sugar in her coffee again. 6 háizimen bù zài zài jib shang tc zúqiú le The children are not playing football on the street anymore. háizimen zài yg bù zài jib shang tc zúqiú le The children will never play football on the street again. 7 wi mèimei bù zài sahufng le My younger sister is not telling lies anymore. wi mèimei zài yg bù sahufng le My younger sister will never tell lies again. 8 wi de yc gè tóngxué bù zài df rén hé mà rén le A classmate of mine is not fighting and cursing people anymore. wi de yc gè tóngxué zài yg bù df rén hé mà rén le A classmate of mine will never fight and curse people again. 9 wi gbge bù zài kaichb le My elder brother is not driving anymore. wi gbge zài yg bù kaichb le My elder brother will never drive again. 10 wi mama bù zài chc ròu le My mother is not eating meat anymore. wi mama zài yg bù chc ròu le My mother will never eat meat again.
Unit 18 Exercise 18.1
302
1 tamen shì nóngmín ma tamen shì bù shì nóngmín shì bù shì 2 ta xifng df pcngpangqiú ma ta xifng bù xifng df pcngpangqiú xifng bù xifng 3 ta qù guo dòngwùyuán ma ta qù guo dòngwùyuán méiyiu qù guo / ( ) méiyiu/méi(yiu) qù guo 4 nèi tiáo jib ganjìng ma/ ( ) nèi tiáo jib gan(jìng) bù ganjìng ganjìng bù ganjìng 5
ta míngtian huì lái ma/ ta míngtian huì bù huì lái huì bù huì 6 ta yiu túshezhèng ma/ ta yiu méi yiu túshezhèng yiu méiyiu 7 ta dài le yàoshi ma / ta dài le yàoshi méiyiu/ ta dài méi dài yàoshi/ ta yiu méiyiu dài yàoshi dài le / ( ) méiyiu/méi(yiu) dài 8 hui wàng ma/ hui wàng bù wàng hgn wàng bù wàng 9 nh de péngyou huì hbng nèi gè qjzi ma/ nh de péngyou huì bù huì hbng nèi gè qjzi huì bù huì 10 ta de dìdi xhhuan chuan niúzfikù ma/ ( ) ta de dìdi xh(huan) bù xhhuan chuan niúzfikù xhhuan bù xhhuan
Key to exercises
Exercise 18.2 1 nh xh le chènshan méiyiu Did you wash the shirt? 2 nh zuótian dú le bào méiyiu Did you read the newspaper yesterday? 3 shàng gè yuè nh kàn le diànyhng méiyiu Did you watch a film last month? 4 zuó wfn nh xig le xìn méiyiu Did you write letters last night? 5 nh mfi le piào méiyiu Have you bought the ticket? 6 ta pèngjiàn le zhang xiansheng méiyiu Did she bump into Mr Zhang? 7 nhmen qiántian shàng le jijbajian méiyiu Did you go to the pub the day before yesterday? 8 nhmen nàr shàng xcngqc xià le xug méiyiu Did you have any snow in your area last week? 9 ta jia qùnián xiàtian qù le hfi bian dùjià méiyiu Did his family go to the seaside on holiday last summer? 10 zhèi jiàn shì xifo huáng gàosu le nh méiyiu Did Xiao Huang tell you about this?/Has Xiao Huang told you about this?
Exercise 18.3 1
/ nh pá guo shan ma/méiyiu 2 nh pèngjiàn guo nh de línje ma/méiyiu 3 nh zébèi guo nh zìjh ma/méiyiu 4 / nh kàn guo zúqiú bhsài ma/méiyiu 5 / nh qí guo mf ma/méiyiu 6 / nh qù guo hfi bian ma/méiyiu 7 / / nh cháng/chc guo jifozi ma/méiyiu 8 / nh jiàn guo jcngyú ma/méiyiu 9 / nh yfng guo giu ma/méiyiu 10 / / nh qù/jìn guo jijbajian ma/méiyiu / /
303
Key to exercises
All the sentences may also be translated as: yiu méiyiu pá guo shan 2 méiyiu pèngjiàn guo nh de línje etc.
1
nh nh yiu
Exercise 18.4 1 / ( ) túshegufn anjìng ma/an(jìng) bù anjìng 2 / bgijcng rè ma/rè bù rè 3 / ( ) nh de péngyou gaoxìng ma/gao(xìng) bù gaoxìng 4 / ( ) cài hfochc ma/hfo(chc) bù hfochc 5 / nà gè diànshì jiémù yiuqù ma/yiu méiyiu qù 6 / ( ) zúqiú bhsài jcngcfi ma/jcng(cfi) bù jcngcfi 7 / ( ) zhèi bf yhzi shefu ma/she(fu) bù shefu 8 / huar xiang ma/xiang bù xiang 9 / dàngao tián ma/tián bù tián 10 / ( ) zhudzi ganjìng ma/gan(jìng) bù ganjìng 11 / ( ) fángjian zhgngqí ma/zhgng(qí) bù zhgngqí 12 / jcnglh kangkfi ma/kangkfi bù kangkfi
Exercise 18.5 1 ta hb zuì le ne 2 kùzi xh le | chènshan ne 3 míngtian wfnshang xià yj ne 4 ( ) wi méi(yiu) shíjian ne 5 / kafbi hgn hfohb/bù cuò | dàngao ne 6 wi hgn máng | nh ne 7 ta qù le nfr ne 8 zhè shì shuí/shéi de diànnfo ne 9 wi de yàoshi ne 10 ( ) xifo mao (zài nfr) ne
Drill 18.1 1
304
chb wi xie hfo le chb xie hfo le 2 yjsfn wi dài le yjsfn dài le 3 yàoshi nh dài le ma yàoshi dài le ma 4 bgijcng kfoya nh chc guo ma bgijcng kfoya chc guo ma 5 zuòyè nh jiao le méiyiu zuòyè jiao le méiyiu 6 xìn ta jì le méiyiu xìn jì le méiyiu 7 lqchá nh hb guo méiyiu lqchá hb guo méiyiu 8 ycfu wi xh le ycfu xh le 9 bgijcng nh qù guo méiyiu bgijcng qù guo méiyiu 10 chángchéng nh dào guo méiyiu chángchéng dào guo méiyiu 11 qín nh dài le méiyiu
qín dài le méiyiu 12 le ma
jcntian de bàozhh nh kàn jcntian de bàozhh kàn le ma
Key to exercises
Drill 18.2 1 2
zhè jh tian nh qù bù qù xué tàijíquán zhè jh tian huì bù huì xià yj 3 nh néng bù néng zài zhèr dgng ycxià 4 nh mfi le chb méiyiu 5 ( ) nh xh(huan) bù xhhuan chuan niúzfikù 6 nh dài le túshezhèng méiyiu 7 ( ) nh tóng(yì) bù tóngyì wi de jiànyì 8 nh de péngyou huì bù huì df pcngpangqiú 9 nh míngtian zfoshang yiu méi yiu kòng 10 nh xifng bù xifng chc bgijcng kfoya 11 ( ) nh yuàn(yi) bù yuànyi bang ta de máng 12 nh jia li yiu méi yiu diànnfo 13 nh wánchéng le nèi jiàn gdngzuò méiyiu 14 nh dang guo lfoshc méiyiu 15 nh jiàn le jcnglh méiyiu
Unit 19 Exercise 19.1 1 2 ma 3 ma 4
( )
qhng nh guan shàng chuang(hù) | hfo ma qhng nhmen shud zhdngwén | xíng/kgyh / wi yòng ycxià diànhuà | xíng/kgyh zánmen qù kàn diànyhng | hfo ma 5 / wi jiè yc zhc bh | kgyh/xíng ma 6 wi míngtian shuì lfn jiào | kgyh/xíng ma 7 wi zuò zài zhèr | xíng/kgyh ma 8 wi tí gè jiànyì | hfo/xíng/kgyh ma 9 nh ggi wimen jifng gè gùshi | hfo ma 10 wimen jcn wfn qù tiàowj | hfo/xíng ma /
/ / / / /
Exercise 19.2 1(i) shì bù shì xifo lh qí zìxíngchb qù yùndòngchfng (ii) xifo lh shì bù shì qù yùndòngchfng (iii) xifo lh shì bù shì qí zìxíngchb qù yùndòngchfng 2(i) shì bù shì wáng xifojie qù de yóujú (ii) wáng xifojie shì bù shì gangcái qù de yóujú (iii) wáng xifojie shì bù shì qù de yóujú
305
Key to exercises
Exercise 19.3 1
nh shì lfoshc háishi xuésheng 2 ( ) ta xhhuan kàn xifoshud háishi (xhhuan) kàn diànshì 3 ta shì zuótian háishi qiántian qù de zhdngguó 4 nh shì zuò huichb háishi zuò qìchb qù shàngban 5 nh shì qù diànyhngyuàn háishi qù fàngufn 6 zhè shì ycyuàn háishi dàxué 7 ( ) ta nèi tian shì chuan de qúnzi háishi (chuan de) kùzi 8 nh qiántian shì pèngjiàn de lfo wáng háishi xifo zhang
Exercise 19.4 1 zhèi bgn she shì nh xig de ba This book was written by you, wasn’t it?/You wrote this book, didn’t you? shì de bù shì de 2 lúnden lí bgijcng hgn yufn ba London is a long way from Beijing, isn’t it? shì de 3 huichb yhjcng kai ziu le ba The train has already gone, hasn’t it? shì de hái méiyiu Not yet. 4 nèi tiáo qúnzi tài cháng le ba That skirt is too long, isn’t it? / duì/shì de / bù duì/bù shì de 5 / nh mgi tian ddu tì/gua húzi ba You shave every day, don’t you? shì de bù shì de 6 nh bàba | mama xià gè yuè qù dùjià ba Your parents are going away on holiday next month, aren’t they? / duì/shì de / bù duì/bù shì de 7 nh bù xhhuan hb zhdngguó chá ba You don’t like Chinese tea, do you? / duì/shì de / bù duì/bù shì de 8 nh qczi bù chc niúròu ba Your wife doesn’t eat beef, does she? / duì/shì de / bù duì/bù shì de
Note: shì de is interchangeable with shì or duì and bù shì de with bù shì or bù duì in all answers.
Exercise 19.5 1
306
qù de 5
nh shì bù shì xià gè yuè qù zhdngguó 2 nh shì bù shì qùnián qù de zhdngguó 3 nh shì zuò fbijc qù háishi zuò chuán qù 4 nh shì kaichb qù de háishi qí zìxíngchb nh shì zài nfr xué de zhdngwén 6 nh shì zài nfr xué zhdngwén 7
zuó wfn shì shéi/shuí xh de wfn 8 shéi/shuí xh wfn
jcn wfn shì
Key to exercises
Drill 19.1 1
wi hgn xhhuan df pcngpangqiú / wi ycdifnr yg/ddu bù xhhuan df pcngpangqiú 2 wi hgn xhhuan kàn diànyhng / wi ycdifnr yg/ddu bù xhhuan kàn diànyhng 3 dàngao hgn hfochc / dàngao ycdifnr yg/ddu bù hfochc 4 nèi bgn xifoshud hgn yiu yìsi / nèi bgn xifoshud ycdifnr yìsi yg/ddu méi yiu 5 nèi tiáo kùzi hgn cháng / nèi tiáo kùzi ycdifnr yg/ddu bù cháng 6 wi sheshu de háizi hgn kg’ài / wi sheshu de háizi ycdifnr yg/ddu bù kg’ài 7 wi jia de xifo mao hgn kg’ài / wi jia de xifo mao ycdifnr yg/ddu bù kg’ài 8 zuò huichb qù bh zuò qìchb qù kuài de dud / zuò huichb qù ycdifnr yg/ddu bù bh zuò qìchb qù kuài 9 wi hgn xifng qù zhdngguó wánr / wi ycdifnr yg/ddu bù xifng qù zhdngguó wánr 10 nàr de xiàtian hgn rè / nàr de xiàtian ycdifnr yg/ddu bù rè
Drill 19.2 1
nh shì bù shì xifng xué zhdngwén 2 yùndòngchfng shang shì bù shì yiu hgn dud yùndòngyuán 3 jib shang shì bù shì ddu shì rén 4 / nh fùmj shì bù shì guò jh tian lái kàn/tànwàng nh 5 nh shì bù shì chángcháng qù yóuying 6 nh de péngyou shì bù shì zài wàimian dgng nh 7 / nh shì bù shì qù guò bgijcng hgn dud cì/tàng 8 ta shì bù shì zhgng wfn zài xig xìn 9 nh jcnwfn shì bù shì hb le hgn dud píjij 10 zhèi gè cài shì bù shì méiyiu nèi gè cài hfochc
Unit 20 Exercise 20.1 1 zuò xià
jìn lái 2 5 qh lái
6
zhàn qhlái 3 kuài 7
che qù 4 zfo difn huí lái
307
Key to exercises
8
guan mén 9 ( bù yào/bié guan dbng
)
yánsù (yc)difnr
10
/
Exercise 20.2 1 ( ) dud chc (yc)difnr ba 2 zánmen zhèr xià chb ba 3 ràng ta qù ba 4 ( ) kuài (yc)difnr ba 5 qhng zài zhèr páiduì 6 qhng kai dbng 7 ( ) qhng jìn (lái) 8 zánmen xiexi ychuìr ba 9 qhng tcng | shì shéi/shuí 10 qhng kai mén
Exercise 20.3 1 / bù yào/bié guan chuang 2 / bù yào/bié guan dbng 3 / bù yào/bié liàng ycfu 4 / bù yào/bié shàng chb 5 / bù yào/bié guò lái 6 / bù yào/bié chuan zhèi shuang xié 7 / bù yào/bié kaichb 8 / bù yào/ bié ràng ta ziu 9 / bù yào/bié jiào ta huí lái 10 / qhng dàjia bù yào/bié dài sfn
Exercise 20.4 1(i) zánmen jìn qù ba (ii) hfo ba | nh jìn qù ba 2(i) nh qù gb cfo | hfo ma (ii) qhng xiànzài jiù qù gb cfo 3(i) zánmen xià chb ba (ii) kuài | zánmen zài zhèr xià chb 4(i) ( ) zánmen (qù) hb yc bbi ba (ii) ( ) hfo ba | nh (qù) hb yc bbi ba
Exercise 20.5 1 8
a 2 na 9
wa 3 a 4 la 5 ya 10 a 11 ya
wa 6 / ya/a 12 / wa/a
7
wa
Drill 20.1 1 4 ( 6
308
11
)
bié gufn ta 2 bié jìn lái 3 bié che qù / (xian) bié ziu/líkai 5 ( ) bié pèng (ta) bié shud xiàqù le 7 bié mà rén 8 bié zài shafa shang shuì 9 bié zhfo jièkiu 10 / bié gbn rén jiè qián/bié jiè biéren de qián bié dgng wi 12 bié zài zhèr chduyan
13 xiào wi
bié dòu ta
14
bié zhàn qhlái
15
bié
Key to exercises
1
bù bì gufn ta 2 bù yào jìn lái 3 bù xj che qù 4 hái bù néng ziu 5 ( ) bù zhjn pèng (ta) 6 ( ) bù yào shud xiàqù (le) 7 bù xj mà rén 8 ( ) bù kgyh zài shafa shang shuì(jiào) 9 bù yào zhfo jièkiu 10 bù yào gbn rén jiè qián 11 bù bì dgng wi 12 bù zhjn zài zhèr chduyan 13 bù yào dòu ta 14 bù yòng zhàn qhlái 15 bù néng xiào wi
Drill 20.2 1
qhng bù yào xiào wi Please don’t laugh at me. qhng bù yào xiào wi le Please stop laughing at me. 2 qhng bié kai wánxiào Please don’t joke. qhng bié kai wánxiào le Please stop making jokes. 3 bù yào dfjià Don’t fight! bù yào dfjià le Stop fighting! 4 bié chfojià Don’t quarrel! bié chfojià le Stop quarrelling! 5 bié chfo Don’t make such a terrible noise! bié chfo le Stop making such a racket/din! 6 bié chfo wi Don’t disturb me! bié chfo wi le Stop disturbing me! 7 bié mà ta Don’t scold him! bié mà ta le Stop scolding him! 8 bù yào dgng ta Don’t wait for him. bù yào dgng ta le Don’t wait for him any longer. 9 bié chduyan Don’t smoke! bié chduyan le Stop smoking! 10 bié hb jij Don’t drink! bié hb jij le Stop drinking! 11 bié kèqi Don’t stand on ceremony. bié kèqi le Don’t stand on ceremony anymore. 12 zài jiàn! Goodbye. zài jiàn le It’s time to say goodbye.
Unit 21 Exercise 21.1 1
huí qù 2 guò lái 3 shàng qù 4 xià lái 5 ná lái 6 che qù 7 huí lái 8 ná qù 9 qh lái 10 jìn qù 11 guò qù 12 che lái 13 huí jia lái 14 kai guò qiáo qù 15 pá shàng shù qù 16 xià shan lái 17 dài dào jiàoshì lái 18 ziu che fángzi qù 19 pfo huí bàngdngshì qù 20 dài huí ycyuàn qù 21 tiào jìn yóuyingchí
309
Key to exercises
qù 22 qù 24
/
ziu jìn yóujú qù 23 ziu che fángjian/wezi lái
chuan guò mflù
Exercise 21.2 1 cheqù 2 xiàlái 3 guòqù 6 ... che . . . qù 7 huí . . . qù 9 ... shàng . . . lái ... jìn . . . qù 12 ... jìn . . .
xiàlái 4 jìnlái 5 ... huí . . . qù 8 ... 10 ... guò . . . qù 11 qù
Exercise 21.3 1 lfoshc ziu jìn túshegufn qù le The teacher has gone into the library. 2 fbijc fbi guò shan qù le The plane has flown over the hill. 3 wi pá shàng shanpd qù I climbed up the hillside. 4 háizimen pfo guò mflù qù le The children went across the road. 5 tamen ziu che jiàotáng qù le They went out of the church. 6 ycshbng huí ycyuàn qù le The doctor has gone back to the hospital. 7 qcngwa tiào xià shuh qù le The frog jumped into the water. 8 chb kac guò qiáo lái le The car came over the bridge. 9 xifo jc zuan che dànké lái le The chicken broke out of the shell. 10 xifo mao pá shàng shù qù le The kitten climbed up the tree. 11 nifor fbi che lóngzi qù le The bird flew out of the cage. 12 xuésheng ziu jìn jiàoshì lái le The students came into the classroom. 13 lfoshj zuan huí dòng qù le The rat scurried back to its hole. 14 dùchuán kai guò hé qù le The ferry went across the river (to the other side).
Exercise 21.4 1
310
ycfu ddu zhuang jìn xiangzi li qù le 2 qián ddu cún zài yínháng li le 3 lajc ddu dào jìn lajcting li qù le 4 nh de xíngli ddu fàng zài xínglijià shang le 5 ( ) xh hfo de ycfu ddu liàng zài liàngycshéng shang(bian) le 6 zhj hfo de cài ddu gb zài bcngxiang li le 7 shiushi ddu fàng zài bfoxifnxiang li 8 ( ) tamen ban jìn chéng (li) lái le 9 qìchb yczhí kai dào hfi bian 10 qìqiú yczhí shbng dào tian shang qù le 11 weya fbi dào wedhng shang qù le 12 wi de màozi ràng fbng ggi chuc dào hú li qù le
Drill 21.1 1 ( ) gdngchéngshcmen (ddu) jìn qù le 2 ( ) dàrenmen (ddu) che qù le 3 ( ) nán háizimen (ddu) che qù le 4 ( ) ns háizimen (ddu) huí lái le 5 ( ) zhdngguó péngyoumen (ddu) jìn lái le 6 ( ) kèrenmen (ddu) huí qù le 7 ( ) zhdngguó kèrenmen (ddu) huí lái le 8 ( ) línjemen (ddu) che lái le 9 ( ) bìngrén ziu jìn bìngfáng li lái (le) 10 ( ) nfinai dài dìdi mèimei dào dòngwùyuán qù (le) 11 yùndòngyuánmen pá shàng shan qù 12 bàba xiàban hòu huí jia lái le 13 xifo mao dui zài shafa xiàmian 14 ( ) ( ) yiu (yc) zhc giu pfo guò qiáo lái (le) 15 ( ) ( ) yiu (yc) qún rén ziu jìn shangdiàn lái (le) 16 ( ) gbge pfo dào lóushàng lái le 17 ( ) xifo nshái yóu guò hé qù (le) 18 / gbzi fbi shàng shù qù/gbzi fbi dào shù shang qù le 19 yuèliang che lái le 20 ( ) nèi gè nán háizi tiào jìn shuh li qù (le) 21 ( ) sdngshj pá xià shù lái (le) 22 mama gfn dào hjochbzhàn qù le 23 yiu yc qún nán háizi pfo dào jib shang lái le 24 ( ) yc gè gè (de) qìqiú shbng qhlái le 25 bh diào jìn hé li qù le 26 tamen ban dào cenzi li qù le 27 jcnglh ziu che bàngdngshì lái le 28 / xuéshengmen zhàn le qhlái/xuéshengmen zhàn qhlái le 29 / dàjia ddu zuò le xiàlái/dàjia ddu zuò xiàlái le 30 jiùshbngyuán yóu huí àn bian lái le
Key to exercises
Note: The inclusion or exclusion or le depends first on whether the emphasis is on the result achieved or on the action itself, and second, on the regularity of a disyllabic rhythm.
Drill 21.2 1 ta jìn wùzi li qù le ta pfo jìn wùzi li qù le 2 ta che jiàoshì qù le ta ziu che jiàoshì qù le 3 ta huí jia qù le ta gfn huí jia qù le 4 ta xià lóu lái le ta pfo xià lóu lái le 5 ta guò qiáo qù le ta kai guò qiáo qù le 6 ta shàng shù qù le
311
Key to exercises
ta pá shàng shù qù le 7 ta guò hé lái le ta yóu guò hé lái le 8 ta che fángzi lái le ta chdng che fángzi lái le 9 * *ta guò zhàlan qù le ta tiào guò zhàlan qù le 10 ta shàng tái lái le ta pfo shàng tái lái le
Unit 22 Exercise 22.1 1 de hgn kuài 2 hfo 5 shú/shóu 6 dào 10 gan 11 de zhbn gao 14 duì 16 zhù
ganjìng 3 ding 4 de zuì de hgn liúlì 7 hfo 8 huì 9 de hgn wfn 12 / dào/jiàn 13 de hgn qcngchj 15 de hgn
Exercise 22.2 1 wi sfngzi téng de fàn yg chc bu xià le My throat was so sore I could not eat. 2 ta yóuying yóu de qì yg chufn bu guòlái le He swam so much he could not get his breath. 3 ta pfo lù pfo de tuh ddu suan le She ran so much/fast that her legs ached. 4 lfoshc shudhuà shud de sfngzi ddu yf le The teacher spoke so much his/her throat became sore/hoarse. 5 wi yfnjing hua de shénme yg kàn bu qcngchu le My eyes were so blurred I could not see anything. 6 wi gaoxìng de huà yg shud bu chelái le I was so happy I was speechless. 7 gbge zuì de shuí yg bù rènshi le (My) elder brother was so drunk he couldn’t recognize anyone. 8 xuésheng xig zì xig de shiu yg suan le The students wrote so much their hands ached. 9 mèimei ke de yfnjing ddu hóng le (My) younger sister cried so much her eyes were red. 10 ta kai wánxiào kai de dàjia ddu xiào qhlái le Her jokes made everyone begin to laugh. (lit. She joked so that everyone began to laugh.)
Exercise 22.3 1 312
duì 2 bfo 6 míngbai 11
dào 3 zuì le 4 hfo 7 dfo 8 pò de hgn zfo 12
9
de hgn piàoliang ganjìng 10 de hgn wfn
5
Exercise 22.4 1
/ tamen tiào de hgn mgi/hgn hfo 2 jiùshbngyuán yóu de fbicháng kuài 3 / xuésheng niàn/dú de hgn màn 4 háizi chc le hgn dud 5 dàjia ddu shuì de hgn shú/shóu 6 yfnyuán chàng de hgn zaogao 7 wimen pfo de tài lèi le 8 yùndòngyuán tiào de zhbn gao 9 gbge hb de bù dud 10 wi de tóngxué shud de bù liúlì
Key to exercises
Drill 22.1 1 2
mèimei tiào shéng tiào de jifo ddu téng le dìdi pfobù pfo de tuh ddu rufn le 3 lfoshc jifngkè jifng de hóulóng ddu téng le 4 péngyoumen liáotian liáo de sfngzi ddu yf le 5 nèi gè háizi ke de yfnjing ddu hóng le 6 wimen bbi xíngli bbi de bèi ddu téng le 7 mama xig xìn xig de shiu ddu ruán le 8 jigjie la xifotíqín la de shóuzhh ddu chexuè le 9 gbge tán gangqín tán de shiuzhh ddu suanténg le 10 bàba shudhuà shud de kiu ddu gan le 11 yéye kàn bàozhh kàn de yfnjing ddu hua le 12 nfinai chc pínggui chc de yáchh ddu téng le
Drill 22.2 1 b ycfu méi xh ganjìng c ycfu xh de bù gòu ganjìng d ycfu xh de bù tài ganjìng 2 b wénzhang méi xig hfo c wénzhang xig de bù gòu hfo d wénzhang xig de bù tài hfo 3 b wèntí méi shud qcngchu c wèntí shud de bù gòu qcngchu d wèntí shud de bù tài qcngchu 4 b fàn méi zhj shóu c fàn zhj de bù gòu shóu d fàn zhj de bù tài shóu 5 b chb méi xie hfo c chb xie de bù gòu hfo d chb xie de bù tài hfo 6 b wèntí méi yánjie qcngchu c wèntí yánjie de bù gòu qcngchu d wèntí yánjie de bù tài qcngchu 7 b tóufa méi jifn dufn c tóufa jifn de bù gòu dufn d tóufa jifn de bù tài dufn 8 b gbcí méi bèi shóu c gbcí
313
Key to exercises
bèi de bù gòu shóu d gbcí bèi de bù tài shóu 9 b zhudzi méi ma ganjìng c zhudzi ma de bù gòu ganjìng d zhudzi ma de bù tài ganjìng 10 b qíngkuàng méi lifojig qcngchu c qíngkuàng lifojig de bù gòu qcngchu d qíngkuàng lifojig de bù tài qcngchu 11 b ddngxi méi fàng zhgngqí c ddngxi fàng de bù gòu zhgngqí d ddngxi fàng de bù tài zhgngqí 12 b fángjian méi shdushi ganjìng c fángjian shdushi de bù gòu ganjìng d fángjian shdushi de bù tài ganjìng
Unit 23 Exercise 23.1 1 /
dòng 2 lifo/diào 7
guòqù 3 qhlái 4 D zháo 5 xià 6 qh 8 /D dào/zháo 9 jí 10 / wán/lifo
Exercise 23.2 1 chc de bfo 2 zhàn bu qhlái 3 / hb bu xià/lifo 4 xh bu ganjìng 5 zuò de shefu 6 D gòu bu zháo 7 kàn bu qcngchu 8 jì de zhù 9 hé de lái 10 huó de xiàqù
Exercise 23.3 1 4 7 bu zhù
guan bu shàng 2 shài de gan 3 zuò de xià ziu bu dòng 5 gfn de shàng 6 xíng bu tdng hé de lái hé bu lái 8 jì de qh 9 jcn 10 tcng de ding
Exercise 23.4
314
D wi shuì bu zháo 1 wi hái shuì bu lifo 2 3 wi jcntian mfi bu lifo le 4 wi mfi bu qh 5 wi bù néng gàosu nh 6 wi gàosu bu lifo nh 7 zhèi jiàn shìr wi zuò bu dào 8 zhèi jiàn shìr wi bù néng zuò 9 wi shud bu xiàqù le 10 wi bù néng shud xiàqù le
Drill 23.1 1 nh kàn de jiàn nèi xib zì ma | duìbuqh | wi kàn bu jiàn zuibian nà jh gè zì 2 / / / nh néng/kgyh bang wi ycxià/yc gè máng ma | dangrán néng/kgyh 3 ta mfi de qh nà lifng tiáo niúzfikù ma | dangrán mfi de qh | ta bàba hgn yiu qián 4 ( ) ( ) / / ( ) / nh jcn(tian) wfn(shang) néng xig wán/xig de wán nèi pian lùnwén ma | duìbuqh | xig bu wán | wi dgi canjia yc gè huìyì/wi yiu (yc) gè huì yào kai/wi yiu yc gè huìyì yào canjia 5 / / bìngrén néng zhàn qhlái ma/bìngrén zhàn de qhlái ma | kingpà zhàn bu qhlái/ta kingpà zhàn bu qhlái 6 / / nh chc de wán/xià zhèi kuài dàngao ma | wi zhbn de chc bu xià le/wi zhbn de ycdifnr yg chc bu xià le 7 nh de chb xie de hfo ma | kingpà xie bu hfo le 8 / / / / wimen jìn de qù ma/wimen jh de jìnqù ma | kingpà jìn bu qù le/kingpà jh bu jìnqù le | lhmiàn tài dud rén le/lhmiàn yiu nàme dud rén 9 nh tcng de ding wi de huà ma | duìbuqh | tcng bu ding | wi zhh tcng de ding ycngwén 10 / ( ) nh gfn de shàng nèi liàng gdnggòng qìchb/bashì ma | dangrán gfn de shàng | wi (néng) pfo de hgn kuài
Key to exercises
Drill 23.2 1
nh míngtian ziu de lifo ziu bu lifo nh míngtian ziu bu ziu de lifo 2 hbibfn shang de zì nh kàn de qcngchu kàn bu qcngchu hbibfn shang de zì nh kàn bu kàn de qcngchu 3 ta shud de huà nh tcng de ding tcng bu ding ta shud de huà nh tcng bu tcng de ding 4 zhème guì de ycfu nh mfi de qh mfi bu qh zhème guì de ycfu nh mfi bu mfi de qh 5 zhème dud rén zuò de xià zuò bu xià zhème dud rén zuò bu zuò de xià 6 nh hái chc de xià chc bu xià nh hái chc bu chc de xià 7 zhè gè diànnfo hái xie de hfo xie bu hfo zhè gè diànnfo hái xie bu xie de hfo 8 nh shud nèi zhang
315
Key to exercises
xìnyòngkf hái zhfo de dào zhfo bu dào nh shud nèi zhang xìnyòngkf hái zhfo bu zhfo de dào 9 nh shud nh míngtian gfn de huílái gfn bu huílái nh shud nh míngtian gfn bu gfn de huílái 10 nh shud zhdngwén wi xué de huì xué bu huì nh shud zhdngwén wi xué bu xué de huì
Unit 24 Exercise 24.1 1 duì 2 / hé/gbn 3 / hé/gbn 4 / / wàng 5 duì 6 / / xiàng/cháo/wàng 7 / 8 / hé/gbn
xiàng/cháo/ xiàng/cháo
Exercise 24.2 1 7
wèi 2 tì; tì 8 wèi
ggi 3
ggi 4
tì
5
wèi
6
wèi
Exercise 24.3 1
wimen cháo ngi gè fangxiàng ziu 2 ta duì gdngzuò hgn fùzé 3 zhèi bgn she duì wi xuéxí hgn yiu yòng 4 xhao lh zhèngzài gbn shí lfoshc tánhuà 5 ta cháo wi difn difn tóu 6 wimen ycnggai xiàng ta xuéxí 7 wi tì nh xig xìn 8 wi jcn wfn ggi nh df diànhuà 9 wi ggi nh xig xìn 10 zhèi gè xifo zhèn yj nèi gè xifo zhèn ycyàng gjlfo
Exercise 24.4 1
lí 2 dào 7
cóng 3 cóng 4 lí 8 cóng
cóng;
dào 5
lí 6
cóng;
Exercise 24.5 1 yóu 2 cóng 3 yóu 4 cóng 7 cóng 8 yóu
316
yóu/
cóng 5
cóng 6
Exercise 24.6 1 xiàng 2 cóng 8 yú
yán 3 yú 4 yú 5 9 cóng 10 cóng
wàng
6
lí
7
Key to exercises
Exercise 24.7 1 qhng gbn wi lái 2 wi míngtian ggi nh df diànhuà 3 tamen duì wimen hgn yiuhfo 4 zhèr lí chbzhàn bù hgn yufn 5 wi mgi tian cóng jij difn gdngzuò dào wj difn 6 yán jib ddu shì qìchb 7 zhèi jiàn shìr quán yóu wi fùzé ma 8 nh wèi shénme bù ggi tamen xig xìn
Drill 24.1 1 cóng ycyuè dào shí’èryuè 2 / cóng xifohái/háizi dào dàren 3 cóng zhèr dào dàxué 4 cóng tóu dào jifo 5 cóng shàngwj jij difn dào xiàwj liù difn 6 cóng chc de dào chuan de 7 cóng xifoxué dào zhdngxué 8 cóng yc dào yc bfi 9 / A Z cóng tóu dào wgi/cóng cóng yc jij jij wj nián dào A dào Z 10 èr líng líng wj nián
Drill 24.2 1 I want to have a talk with you about this. 2 Please don’t worry about me. 3 That driver is very friendly to the passengers. 4 Up to now I have never eaten lychees. 5 If you go ahead for a hundred metres you will get there. 6 Look! There’s a bus coming (towards us). What number is it? Can you see? 7 Who did you borrow this book from? 8 My home is a long way from the airport and it takes an hour on the bus/train (to get there). 9 Go ahead along this road for about two hundred metres, and at the second crossing turn left. Go about another five hundred metres and you will be able to see a shopping mall. Opposite the shopping mall there is a laundry, and behind the laundry is the pharmacy you are looking for. 10 At the crossing ahead, you will be able to see a church. Go south down the road on the right of the church, and in about five minutes you will see a square. To the left of the square is a small road, and the bookshop you are looking for is on that small road. 317
Key to exercises
Unit 25 Exercise 25.1 1 wèile bù wù huichb | ta juédìng ziu jìn lù 2 wèile kàn nèi chfng zúqiúsài | xifo lh kai le lifng xifoshí de chb dào lúnden qù 3 wèile qìngzhù ns’ér dàxué bìyè ta jjxíng le yc gè wjhuì 4 wèile kàn zhèi gè diànyhng ta tèyì cóng ffguó lái 5 wèile zhàogu nèi gè bcngrén | hùshi yc yè méi shuì 6 wèile canjia yc gè zhòngyào huìyì jcnglh dào bgijcng qù
Exercise 25.2 1
duì 2 guanyú
Exercise
7
guanyú 3 zhìyú 4 duì guanyú 8 ( ) duì(yú)
5
zhìyú 6
25.3
1 / dòngwùyuán li chúle lfohj | shczi zhc wài/yh wài | hái yiu xióngmao 2 / ban li chúle zhdngguó rén zhc wài/yh wài | hái yiu ycngguó rén hé ffguó rén 3 / wi chúle yángròu zhc wài/yh wài | shénme ddu chc 4 / chén xifojie chúle huì tán jíta zhc wài/yh wài | hái huì tán gangqín
Exercise 25.4 1 6
gbnjù 2 D píng zhe
píng 3
gbnjù
4
píng 5
ànzhào
Exercise 25.5 1 ( ) guanxcn 2 4 yj 5 correct
lfoshc duì(yú) wi de xuéxí hgn wi jìn chéng qù mfi ddngxi 3 correct gbnjù qìxiàng yùbào | míngtian xià dà 6 ( ) / duì(yú) háizi tiáopí de wèntí | chúle jiazhfng zhc wài/yh wài | xuéxiào lfoshc yg ycnggai gufn
318
Exercise 25.6 1 zhìyú zhèi gè wèntí | wi méi yiu yìjian 2 duìyú zhèi gè wèntí | wi shífbn danxcn 3 / chúle xcngqc san zhc wài/yh wài | wi mgi tian ddu néng lái 4 / zhìyú wimen néng bù néng lái | qhng nh wèn wi tàitai/feren 5 / chúle ta zhc wài/yh wài | dàjia ddu xhhuan chc zhdngguó cài 6 wi jìn chéng qù kàn yc gè péngyou 7 / wèile xià jiélùn | zhèi gè wèntí tamen tfolùn le wj gè xifoshí/zhdngtóu 8 zhèngfj gbnjù shénme zhíxíng zhèi zhing zhèngcè
Key to exercises
Drill 25.1 1 yóuyú tianqì bù hfo | wimen ddu dai zài jia li 2 ( ) ta chúle xué ffyj (zhc wài) | hái xué zhdngwén 3 wèile ràng háizi dédào hgn hfo de jiàoyù | ta njlì de gdngzuò 4 ta ànzhào fùmj de jiànyì | bù zài chc ròu le 5 nh gbnjù shénme shud wi cuò le 6 zhìyú zhèi jiàn shìqing | ta shud ta bù yuànyi gufn 7 guanyú nàr de qíngkuàng | ta shífbn lifojig 8 duìyú ta de gdngzuò | wi méiyiu shénme yìjian
Drill 25.2 A. A.
xifo lh | nh hfo B. lfo wáng | nh hfo // / nh qù nfr/nh dào/shàng nfr qù B. ( ) wi dào yóujú qù jì (yc) fbng xìn A. / ggi shéi de xìn a/na B. ggi wi bàba mama de | tamen duì wi hgn hfo A. tamen zhù zài nfr B. tamen zhù zài bgijcng | lí zhèr hgn yuán A. nh cháng(cháng) ( ) huí jia qù tànwàng nh fùmj ma B. / méiyiu | wi méiyiu shíjian a/na A. / nh kgyh qhngjià ya/a B. / / wi yiu hgn dud/zhème dud shìr yào zuò/bàn | zhbn de ziu bu kai A. / qhng nh tì/dài wi wènhòu tamen | zhù tamen shbnth jiànkang B. / xièxie nh | wi míngtian zuò fbijc dào lúnden qù/qù lúnden | wi zài nàr ggi tamen df diànhuà A. zàijiàn B. zàijiàn
319
VOCABULARY LIST
Chinese to English Note: mw = measure word; cv = coverb A a ah (exclamation) a’grbbisc shan The Alps fi low; short (opposite of tall) anjìng quiet, to quieten down anxcn to feel at ease àn shore ànzhào according to/in accordance with àolínphkè yùndònghuì the Olympic Games
320
B ba (imperative or question particle) ba eight bayuè August babudé to long to balí Paris bashì bus bf mw handful (rice, etc.); mw (knife, umbrella, etc.); cv bàba father bái white báicài cabbage báitian day, daytime bfi hundred bfi fbn zhc percentage bfiwàn million ban class ban mw (for scheduled trains, buses, etc.)
ban move (home) to bàn to handle/deal with bàndào to manage, accomplish bànff method bàngdngshì office bàn half bànyè midnight bang(zhù) ( ) to help bàng mw pound (weight) bàng mw pound (currency) bao mw packet bao to make (dumplings) baogui parcel bfo full (of food) bfomj nanny bfoxifnguì strongbox/safe bào(zhh) ( ) newspaper bbi mw cup, mug, glass bbi(zi) ( ) n. cup, glass bbi to carry (on back) bbibao rucksack bgibian north (side) bgijcng Beijing bgijcng dàxué Peking University bgijcng kfoya Peking duck bgimiàn north (side) bèi to learn by heart bèi shú/shóu to learn by heart, commit to memory bèihòu behind someone’s back bèizi quilt
bgn mw (for books, magazines, etc.) bgn(zi) ( ) notebook, booklet bízi nose bh cv (compared with) bhsài match bh pen; mw sum of (money) bìxe must; have to bìyè to graduate bian side; by, beside biànhuà change; to change biàn mw (frequency) biaoyj slogan bifo (wrist)watch bifoshì to show, express bifoyfn to perform; performance bié don’t biéren others, another person, other people bcngjilíng ice cream bcngxiang fridge bìng illness, disease bìngfáng (hospital) ward bìngjià sick leave bìngtòng illness bóbo uncle (father’s elder brother) bómj aunt (wife of father’s elder brother) bówùgufn museum bù not, no bù bh not –er than, no(t) more . . . than [necessarily better, taller, etc. than] bù bì no need bù dé must not bù gai ought not to bù guai disobedient, naughty bù shfo many; quite a few bù shì no bù xj not permit(ted) bù yào don’t bù yòng no need bù zhjn not allow(ed) bù zài never again, no more/longer bùguò but; only
bù cloth bùlagé Prague bù mw (for film, computer, etc.) bùduì army
Vocabulary list: Chinese to English
C ca to wipe cai to guess cái only then, not . . . until . . . cfi mì to collect honey cài vegetable; dish (of food) càiyóu vegetable oil càiyuán vegetable garden canguan to visit, look round canjia to attend; take part in cangufn restaurant cangying (insect) fly caochfng sports ground caoxcn to be worried about cfo grass cfodì grass lawn, meadow cfoméi strawberry cèsui toilet chá tea cháhuì tea party cháyè tea leaves chà to lack chàbudud almost cháng long chángchéng the Great Wall chángjiang the Yangtze River cháng mw a fall of (snow), a shower of (rain) chángcháng frequently, often chfng mw (for games) chàng to sing chànggb to sing (a song) cháo cv towards; at, to chfo( jià) ( ) to quarrel; to make a noise chfofàn fried rice chfomiàn fried noodles chb(zi) ( ) car chbkù garage chbliàng vehicle chbzhàn (train, bus) station chén (surname) Chen chènshan shirt
321
Vocabulary list: Chinese to English
322
chénggdng to succeed chéng town, city chéng wài out-of-town (areas), outside the city chéngshì city chéngkè passenger chéngzi orange chc to eat chc bu xià to be unable to eat (anything/any more) chcfàn to eat, have a meal chcsù to be a vegetarian chí pond, pool chí late chídào to arrive late, be late chdng to dash chduti drawer chduyan to smoke (cigarettes) che out; mw (for films, etc.) che lái to come out; rise (of the sun) che qù to go out; get out chefa to set off/out cheguó to go abroad chelái (to come) out (of) chemén to be away (from home) cheqù (to go) out (of) chexuè to bleed chú(le) . . . (zhc wài/yh wài) ( ) . . . ( / ) apart from; as well as chúfáng kitchen chúshc cook; chef chuan to wear (clothes) chuán lái to come from a distance (of sound) chuán ship chuánzhc shipping chufnqì to breathe chuàn mw a bunch of chuang(hu) ( ) window chuanglián curtain (for window) chuangtái window sill chuáng bed chuángdan (bed) sheet chuc to blow chentian spring
cídifn dictionary cì mw (of frequency, occurrence) cdngming intelligent cóng from; since cóng bù never cóng . . . qh ... since, beginning from cónglái all along cún to deposit (money) cùn inch cud a pinch of (salt) cuò wrong D da to travel by dá mw dozen dá’àn answer; solution df to fight; to hit; to play; to practice; to make (a phone call) dfjià to fight dfpái to play mah-jong dfpò to break df rén to hit out at people dfsfo to clean, sweep dfzhbn to have an injection dfzì to type dà big, large; (age) old; (wind) strong dà shangchfng shopping mall dà xug heavy snow dà yj heavy rain dàbulifo at the worst dàfang generous dà hòutian in three days’ time dàjia everybody dàlóu multi-storied building dàlù main road dà qiánnián three years ago dà qiántian three days ago dàren adult dàshhgufn embassy dàxué university dàyc overcoat dàyub about, around, approximately dai / to stay dài to bring; take
dài to wear danxcn to worry (about) dànshì but dàngao cake dànké eggshell dang when; to work as, serve as, be dangrán of course dao knife dfoshc supervisor, tutor dfo to collapse dào to arrive; go to; until dào xiànzài up till now dàodá to get to, reach, arrive dào to pour out (tea); to tip (rubbish) dào mw (for examination questions) dàoli reason dé dud much more (complement) déche to arrive at, come to (a conclusion) dédào to get, obtain de de (complement marker) de de (attributive marker) déwén/yj / German (language) dgi have to dbng light, lamp dgng to wait (for) dc mw a drop of (water/rain) dhxia under, below dì ground dìbfn floor dìtú map dìxià underground; on the ground dìdi younger brother dìshì taxi dì (ordinal number marker) difn mw (for small amounts); (decimal) point difn zhdng o’clock difnr mw (for small amounts) difntóu to nod (the head) diànhuà telephone diànnfo computer
diànshì television diànshìjc television set diàntc lift diànyhng film; movie diànyhngyuàn cinema diàn shop diàoyú to go fishing/angling diào to drop, fall; to throw away; finished (complement) dhng mw (for hats) dìng to decide (upon) die to lose, misplace ddngbian east ddngmiàn east ddngxi thing ddngtian winter ding to understand dòng to touch; to move dòngshbn to set out (for) dòngwùyuán zoo dòng hole ddu all dòu funny, witty; to tease dú to read dj to gamble djbó to gamble dù degree (of temperature) dùjià to go on holiday dùchuán ferryboat duan to carry with both hands dufn short dufn fà short hair duì team duìyuán team member duìzhfng team captain duì mw a pair, couple; cv towards, to, at; yes, right, correct duìbuqh (I’m) sorry duìmiàn opposite duìyú cv as to; about dud many, much, more dud cháng (shíjian) ( ) how long (of time) dud dà how big, what size (shoes, etc.) dud jij how long (of time) dud yufn how far dud(me) ( ) how
Vocabulary list: Chinese to English
323
Vocabulary list: Chinese to English
dudshao how many; how much dui mw (for flowers) dui to hide E Russia éguó éyj Russian (language) è to be hungry è sh le to be starving/famished érzi son grduo ear grhuán earrings èr two èr lóu the first floor èryuè February
324
F fache to issue (forth) fashao to have a fever ffguó France ffguó rén French (person) ffwén/yj / French (language) fanshj sweet potato fanyì to translate; translation fánmáng busy fàn (cooked) rice fàngufn restaurant fang square fangff method fangxiàng direction fángjian room fángzi house/building ffngwèn to visit fàng to put, keep fàng huí put back fàngxué to finish school/class fbi to fly fbcjb plane fbijcchfng airport fbicháng extremely, exceptionally féizào soap fbn mw minute fbn zhc (numerator) fgnbh chalk fèn mw (for newspapers etc.) fbng wind fbngjhng scenery
fbng mw (for letters) fefù husband and wife fúzhuang dress; clothes feren wife fú mw (for paintings etc.) fùmo parents fùqin father fùzé to be responsible for fùjìn near(by); vicinity fùxí to revise (lessons) fù deputy, vicefù mw a pair of (spectacles, etc.) G gai ought to, should gfi to change; to correct gfiqc to postpone, change the time for gài to build, put up (a house) gan dry ganjìng clean ganganjìngjìng spotlessly clean gfn to run after; rush for gfnlù to hurry ahead/along gfnshàng to catch up with gfn to dare gfnjué to feel, be aware of gfnmào to catch a cold gfnxiè to thank gang (only) just gangcái just now ganggang just, only; just now gangqín piano gfngkiu harbour gao high; tall gao cake gaoxìng to be happy, pleased gàosu to tell, inform gbge elder brother gbzi pigeon gb cfo to mow the grass gb to place, put gb(r) ( ) song gbcí lyrics, words (of a song) gébì next door gè mw (for animate and inanimate nouns in general) gègè each and every one; all
gèrén individual, -self ggi cv for/to sb gbn cv a blade of (grass); a piece of (thread) gbnjù cv on the basis of gbn and; cv with sb; to sb gèng even more gdngchéngshc engineer gdngchh metre gdngfbn centimetre gdng(gòng qì)chb ( ) bus gdngjcn kilogram gdnglh kilometre gdngyuán park gdngzc wages gdngzuò work; to work gdu ditch giu dog gòu enough gegu aunt (father’s sister) gemo aunt (father’s married sister) geniang girl gezhàng uncle (husband of father’s sister) gjlfo ancient gùshi story gua fbng to be windy gua húzi to shave guà to hang up guai obedient gufi to turn guàibude no wonder guan(shang) ( ) to close; to turn off guanxcn to be concerned about guanyú cv as regards, regarding gufn to bother about; to look after guàn mw a bottle of guàntou can, tin (of food) gufngchfng a (public) square gufnggào advertisement gucdìng to stipulate; regulations guìzi cupboard; cabinet guì expensive guì xìng what is your name (polite form)
gud wok guójia country guò to cross; to pass (time); (marker of experiential aspect) guò lái to come here/over guò qù to go over; in the past H hái still; yet háishi or (in questions) hái yiu there is/are still (some left) hái (yào) ( ) still –er, even (more) . . . háizi child/children hfi sea hfi bian beach; seaside hfibào seal hfibcn seaside hfimiàn surface of the sea hfi’du seagull hàn sweat hànyj Chinese (language) hànzì Chinese character hfo good; to recover (from illness); (indicating successful completion) hfochc delicious hfohfor earnestly, on one’s best behaviour hfohb to be tasty; nice/good to drink hfokàn pretty, good-looking hfotcng nice/pleasant to the ear hfowánr amusing, enjoyable hfoxiào laughable, ridiculous hào mw number (in sequence); date of month hb to drink hébulái cannot get along with héchéng to be composed of hédelái can get along with hé river hé bian riverside hé and; with hézi box hbi black
Vocabulary list: Chinese to English
325
Vocabulary list: Chinese to English
326
hbibfn blackboard hbi yfnjìng sunglasses hbiyè night (opposite of daytime) hln very hbng to hum (a tune) hóng red; (of eyes) bloodshot hóngchá black tea hónghóng lqlq brightly coloured; multi-coloured hóulóng throat hóu(zi) ( ) monkey hòu after; behind hòubian behind; rear hòumian behind; rear hòunián the year after next hòutian the day after tomorrow hòutou behind; rear hú lake hj tiger (sign of the zodiac) hùshi nurse hua to spend; blurred (of vision) hua dui flowers hua(r) ( ) flower huapíng (flower)vase huayuán garden huá slippery huà words, talk huà v. to paint huàjia artist, painter huàr picture, painting huài bad huanyíng to welcome huán to return, give back huáng (surname) Huang; yellow huángdòu soya bean huánghé the Yellow River huí to return; to reply; mw (for matter, affair) huí guó to return to one’s country huí jia to go home huí lái to come back huí qù to go back huì to remit huì to be likely to, be sure to; can, to be able to; be good at, be skilful in
huì(yì) ( ) meeting henlh wedding ceremony huó alive, living hui fire huichái match huichb train hunchbzhàn railway station huòzhg or J jcchfng airport jchuì opportunity jc chicken jcdàn egg jíta guitar jí to be anxious jí mw (of writing) volume, collection, etc. jíhé to assemble, gather jh how many; a few; about, a few (in approximations) jh difn zhdng ( ) what time? jhshí when? jìhuà plan jì to recall, remember jìde to remember jìlù record jì to send jia to add; to increase jianádà Canada jia home; family; mw (for shops, restaurants etc.) jià mw (for planes) jian mw (for rooms) jianbfng shoulder jifn to cut, clip jifndao scissors jifnféi to lose weight jifnshfo to reduce jiàn to see, to have an appointment with jiànmiàn to meet jiàn mw piece of (luggage) jiànyì to suggest; suggestion jiànkang healthy jianglái the future; in the future jiang ginger
jifng to speak, say jifngjig to explain jifngkè to teach jifng dàoli to stand to reason jifng prize; prize money jiao to hand in; to make (friends) jiaotdng traffic, communications jiao to water jiao shuh to water (plants) jiao to teach jiaoshe to teach jifozi Chinese dumplings jifo foot jiào to order, tell; to call (the doctor, a taxi); to make sb do sth jiàoliàn coach; to coach jiàoshì classroom jiàotáng church jiàoyù education jibba to stammer jibjiebaba stammering jib to meet (sb) (at an airport, etc.) jib street jibdào street jiémù programme jiégui result, outcome jiéhen to marry jiélùn conclusion jiéshù to end, conclude jigjie elder sister jigjué to solve, resolve jiè to borrow; to lend jièkiu excuse jcntian today jcn wfn this evening jcn zfo this morning jcnyú goldfish jcnzìtf The Pyramids jcnbuzhù cannot help jhnzhang tension; nervous jìn enter jìn qiú to score (a goal) jìn chéng to go into town jìn lái to come in jìn qù to go in jìn near, close to
jìn lù short cut jcngjù Beijing opera jcngjì economy; economic jcnglh manager jcngcfi brilliant jcngyú whale jìng quiet, calm jiejìng after all jij nine jijyuè September jij wine jijbajian bar, pub jiùhuì (drinks) party jiù old, out-of-date jiùshbngyuán life-guard jiù then; at once; adv used for emphasis jiùjiu uncle (mother’s brother) jiùmj aunt (mother’s sister; mother’s brother’s wife) jú mw a game of (chess, tabletennis, etc.) jjxíng to hold (a meeting etc.) jjzhh bearing, manner jù mw (for sentence) jùchfng theatre juédìng to decide K coffee kafbi kafbigufn coffee bar kai to open; to drive; to hold, attend (a meeting) kaichb to drive (a car) kai wánxiào to joke kaidao to have an operation kaimén to open (a/the door) kaishh to start kaiwfng to leave for kan to look after, to attend to kangufn to look after kàn to see, watch, look at; to read; to visit kànbuqh to look down upon kàndeqh to think highly of kànff a view, opinion; ideas kànjian to see kangkfi generous
Vocabulary list: Chinese to English
327
Vocabulary list: Chinese to English
328
kfo to test, take a test kfo to roast, bake kfoxiang oven kb mw (for plants) kb mw (for pearls, beans etc.) késou to cough kg(yh) ( ) can; may kg’ài lovely, likeable kglè cola kgshì but kèfú to overcome kè quarter of an hour kèqi polite kèren guest; visitor kè mw a lesson kèwén text kgn be willing (to) knngpà (I’m) afraid knu mouth kiu mw (for mouthful) kiudài pocket ke to cry kj bitter, awful kù(zi) ( ) trousers kuàijì accountant kuài quick kuàilè happy kuài mw piece of; mw (for Chinese currency – a yuan) kuàizi chopsticks kuan broad; wide kufndài to entertain, be hospitable kùnnan difficulty L la to pull; to play (the violin) lajc litter, garbage lajcting litter/garbage bin lfba horn (of a car) là hot, peppery la (particle for exclamation) lái to come; about, around (in approximate numbers); to help oneself; to manage by oneself lái zì to be/come from láibují be too late for láidejí be in time for
láilái wfngwfng coming to and fro láirén bearer; messenger láixìn a letter (received) lán blue láng wolf lfo old lfohu tiger lfoshi honest lfolaoshíshí very honest/earnest lfoshj mouse/ rat le (marker of completed action); (sentence particle) léi thunder lèi tired lgng cold lí cv distant from (a place) líkai to leave lí pear lhbài week lhbài èr Tuesday lhbài liù Saturday lhbài rì/tian / Sunday lhbài san Wednesday lhbài sì Thursday lhbài wj Friday lhbài yc Monday lhwù present lh (surname) Li lh in, inside lhbian inside lhmiàn inside lhtou inside lhlùn theory lhxifng ideal lìshh history lìzhc litchi/lychee lìzc Leeds lì mw a grain of lìji dysentery lián even lifng two liàng mw (for vehicles) liàng to (hang out to) dry liàngycshéng clothes-line liáotian(r) ( ) to chat lifo (used in potential
complements to indicate ‘achievability’) lifojil to understand línje neighbour lín shc to be/get soaked líng zero língqián (small) change (in money) liú to flow; (of tears, sweat) to fall liú xià to leave/stay behind liù six liùyuè June lóng dragon lóngzi cage lóu floor, storey (of a building) lóufáng building lóushàng upstairs lóuxià downstairs lúhui stove fire lúzi cooker lù road, street lù bian by the side of the road lù páng roadside lùchéng journey lùknu crossing, intersection lsxíng/yóu / to go travelling, to tour lqchá green tea luàn in disorder/chaos lúnden London lùnwén essay, dissertation luómf Rome luòtuo camel M mama mother, mum ma to wipe májiàng mah-jong mf horse mflíngshj potatoes mflù road mfph horses mfshàng immediately, at once mflì Mary mà to swear (at) mà rén to swear (at people) ma (question particle)
mfi to buy mài to sell mántou steamed bun mànchéng Manchester màn slow, slowly mànmàn lái take your time máng busy mao cat máobh writing brush máojcn towel máoyc sweater màozi hat méi not méi(yiu) ( ) there is not; not have méigui (hua) ( ) rose méimao eyebrow mgi every mgi beautiful mgiguó America, USA mgilì beautiful mèimei younger sister mén door, gate mén qián in front of the door men (plural suffix) mh rice; mw metre mìfbng bee mifnbulifo can do nothing but, cannot avoid miànbao bread miànbaochb minibus, van míng wfn tomorrow evening míngbai to understand; clear míngnián next year míngtian tomorrow mótudchb motorbike mùdìdì destination N ná to hold in hand, to take nf/ngi which? how? nfr where? nfxib which? (plural) nà/nèi that nà shíhou at that moment nàme so, like that nàr there nàxib/nèixib those
Vocabulary list: Chinese to English
329
Vocabulary list: Chinese to English
nfinai (paternal) grandmother nán háizi boy nán péngyou boyfriend nán south nánbian the south nánmiàn the south nán difficult nántcng unpleasant to hear néng can; may; be able to; be capable of nh you nh bié gufn none of your business nh de your, yours nh gfn Dare you (do it)? How dare you? nh hfo hello nhmen you (plural) nhmen de your, yours (plural) nián year niánjí grade, year (at school) nifo bird nín you (polite form) niú cow; ox niúnfi milk niúròu beef niúzfikù jeans nóngmín farmer, peasant nòng to do, make, (mis)handle njlì try/work hard, strive; industrious/hard-working ns háizi girl ns péngyou girlfriend ns’ér daughter nsshì Miss, Ms nufn warm nufnhuo warm O duzhdu
330
Europe
P pá to climb pá shan to climb a mountain pai to take (a photograph), shoot (a film) páiduì to queue
páng side pángbian at/by the side of, next to pàng fat pfo to run pfobù to go jogging péngyou friend pèng to touch, knock pèngjiàn to bump/run into (someone) píxié leather shoes píjij beer ph mw (for horses, rolls of cloth) pian mw (for essays, articles etc.) piányi cheap piàn mw a slice of (bread, cake, etc.) piàn to deceive piào ticket piàoliang pretty, beautiful, handsome pcngpangqiú table-tennis píng’an safe and sound pínggui apple píng on the basis of; according to píngpiào by ticket only píng mw bottle of píngzi bottle pò broken pútao grape pjsù simple, plain pjtdng ordinary Q qc seven qczi wife qc mw issue (of a journal etc.) qcpiàn to cheat qíta others, the rest qí to ride qí chess qh up qhchéng to set out, depart qhchuáng to get up (out of bed) qhlái to rise, get up; up qì to be angry qìqiú balloon qìxiàng meteorological
qìxiàng yùbào weather forecast qìchb car qìchbzhàn bus stop qìshuh fizzy drink qìyóu petrol qian thousand qianbh pencil qián before, in front of; former, previous; in the past qiánbian front; in front qiánmian front; in front qíannián the year before last qiántian the day before yesterday qiántou front; in front qián money qián (surname) Qián qiánbao purse qiang gun, rifle qiáng wall qiao to strike, knock qiáo bridge qiáo to look (at) qínfèn industrious qcngnián young man qcngwa frog qcng light (opposite of heavy) qcng hydrogen qcngchu clear; clearly qíngkuàng conditions qhng please; to invite qhngkè to invite (guests), to host qìngzhù to celebrate qietian autumn qiú ball qiúmén (football) goal qiúsài match, game qiúxié sports shoes qjzi tune qù to go qùnián last year quán complete, whole quán jia whole family quàn to urge, persuade qubxí to be absent (from a meeting etc.)
quèshí really; definitely qúnzi skirt qún mw crowd of; flock of; pack of
Vocabulary list: Chinese to English
R to let; to allow; to permit ràng rè hot rèqíng warmhearted; kind rén person; people; anybody, somebody rén shù number of people rénjia someone else rénkiu population rénqún crowd (of people) rénrén everyone rèncuò to admit a mistake rènshi to know, recognise rènwéi to think that rènwu task rbng to throw rì sun; date (of the month) rìbgn Japan rìbgn rén Japanese (people) rìyj Japanese (language) ròu meat rúhé how, how about rùchfng to enter a gathering; to be admitted to (a theatre, etc.) rufn soft; weak S sahufng to lie, tell a lie san three sanyuè March sanmíngzhì sandwich sfn umbrella sfngzi throat, voice sànbù to go for a walk sfosao sister-in-law (elder brother’s wife) sha sand shafa sofa shatan beach shayú shark shài to expose to the sun; to dry in the sun shài gan to leave sth in the sun till it is dry
331
Vocabulary list: Chinese to English
332
shài tàiyang to sunbathe shan hill; mountain shanjifo foot of the mountain shanpd hillside shanshuhhuà (Chinese) landscape painting shangchfng shopping mall, market shangdiàn shop shàng last, previous shàng to get on, board (a bus, car, train, etc.); to go up, ascend; to go to shàng chb get on a bus, get into a car shàngban go to work shàngbian above shàngchuáng go to bed shànghfi Shanghai shàngkè go to class shànglai (to come) upward shàngmian above shàngqu (to go) upward shàngtái to go on the stage shàngtou above shàngwfng to go on the internet shàngwj morning shàngxià approximately shàngxué to go to school shang on, above, over, up shé snake shèhuì society shèxiàngjc video camera, camcorder shèyhngshc photographer shéi/shuí who/whom shéi de whose shbn shang on one’s person shbnth body shbnkè profound, deep shénme shíhou when? shénme what; everything shbng mw litre shbng to rise, ascend shbng to give birth to shbngbìng to fall ill shbnghuó life; to live
shbngqì to get angry shbngri birthday shbng sound shbngycn sound shéngzi rope, piece of string shèngdàn Christmas shèngdànkf Christmas card(s) shèngshcban choir shèngqíng great kindness shcwàng to be disappointed, lose hope shcyè to be unemployed, out of work shczi lion shc wet, damp shí ten shí’èryuè December shífbn extremely shíycyuè November shí (surname) Shi shítou stone shíhou time shíjian time shíhuà truth shíyàn experiment shìzhdngxcn city centre shìchfng market shìjì century shìjiè world shì(r) ( ) incident; matter shìqing affair, business, matter shì to be shì de yes shìshì to die, to pass away shdushi to tidy up shóu/shú to ripen shnu hand shiubifo watch shiutào gloves shnuzhh finger shnu mw shiushi jewellery shòushang to be injured shòu thin she book shebao school bag shebgn book
shediàn bookshop shejià bookshelf sheshu uncle (father’s younger brother) shefu comfortable sheshì comfortable she to lose (a bet) shecài vegetables shú/shóu ripe; ripen shú/shóuxc to know very well sho to have (a particular sign of the zodiac) shù mw bouquet of shù tree shùlí hedge shùmù tree shuang mw pair of shuí who? shuí de whose? shuh water shuhchí pool, pond shuhgui fruit shuì to sleep shuì lfn jiào to sleep in, to get up late shuìjiào to go to bed; to sleep shud to say, speak, tell shud bu guòqù cannot be justified shud de guòqù be justifiable shudhuà to talk; speak scjc driver sì four sìzhdu on all sides, around sdngshj squirrel sòng to deliver (letters) sdu mw (for ships) sùshè dormitory suan sour; to ache suanténg to ache; aching suì years of age sui mw (for houses) T ta ta ta
it he/him she/her
ta de his ta de her, hers tamen they/them (neuter) tamen they/them (masculine) tamen they/them (feminine) tamen de their, theirs (masculine) tamen de their, theirs (feminine) tái mw (for engines, machines) tài too; extremely tàijíquán t’ai chi ch’uan, shadow boxing tàitai Mrs; wife tàiyáng the sun tàiyángjìng sunglasses tàiwùshì hé the Thames tán to talk, chat tánbushàng out of the question tándào to talk about tándeshàng can go so far as to say tánhuà/tian / to talk, chat tán to play (piano, organ, harp, etc.) tànwàng to visit táng sugar; sweets tfng to lie, recline tàng mw (for times, occurrence) tao(che) ( ) to take out táozi peach téng to ache; to hurt; pain tèyì specially tc to kick tí to put forward tí che to put forward, raise tímù topic, question tì húzi to shave tì cv for, on behalf of tian day tian na Heavens! tianhuabfn ceiling tiankdng sky, heaven tianqì weather tianshàng the sky tianwén astronomy tián sweet (to the taste)
Vocabulary list: Chinese to English
333
Vocabulary list: Chinese to English
334
tiánmgi sweet (voice, etc.) tiáo mw piece of tiáolì regulations, rules tiáopí naughty tiào to jump tiàoshéng to skip with a rope, play with a skipping rope tiàowj to dance tcng to listen tcng dnng to (listen and) understand tíng to stop; to park tíngbó to anchor tíngchb to park (a car) tdng to lead to tdngzhc to notify; notice, circular tóng and; cv with tóngxué classmate tóngyì to agree tnng mw a pail/bucket of tóu mw (for cattle) tóufa hair túshegufn library túshezhèng library card tù(zi) ( ) hare; rabbit tucjiànxìn letter of recommendation tuh leg W wàzi sock wa wa (particle for exclamation) wài outside wàibian outside wàidì other places wàimài take-away food wàimàidiàn take-away (shop), carry-out wàimian outside wàitào jacket wàitou outside wan curved wán to the finish (complement) wánchéng to finish, accomplish wánjù toy wánr to play, amuse oneself wfn evening; late
wfnfàn dinner, supper wfnhuì (evening) party wfnshang evening wfn bowl wfnguì cupboard wàn ten thousand wáng (surname) Wang wfngqiú tennis wfng/wàng towards wàng prosperous, vigorous wàng to gaze at wéijcn scarf wgiba tail wèi cv for wèile cv in order to, so that wèishénme why wèi mw (polite for persons) wèi to feed; hello, hey wénhuà culture wénxué literature wénzhang essay, article, composition wèn to ask wèntí problem, question wi I, me wi de my, mine wimen we, us wimen de our, ours weya crow wedhng roof wezi room wúgù without reason wú (surname) Wu wj five wjyuè May wocanròu (canned) luncheon meat wo to dance wjhuì dance (party) wù to miss (because late) wù mist, fog X xcbian xcgua xcmian xcchén xcyan
west, west side watermelon west, west side to vacuum-clean to smoke (cigarettes)
xcwàng hope; to hope xíguàn habit; to be accustomed to xh to wash xhycdiàn laundry xhycjc washing-machine xhzfo to have a bath xhhuan to like xhmflayfshan The Himalayas xhshì happy occasion xì play, drama xìpiào theatre ticket xiázhfi narrow xià come/go down, descend; to fall (rain, snow); next; under, below, beneath xià chb to get off/out of a vehicle xià lóu to go/come downstairs xiàban to finish work xiàbian below, under, beneath xiàmian below, under, beneath xiàtou below, under xiàwj afternoon xià xug to snow xià yj to rain xiàlìng summer time xiàtian summer xian first, before xiansheng Mr; gentleman xianhua fresh flowers xiánrén idler; unconcerned person xiàndài modern xiànzài now xiàn thread xiangcen village, countryside xiang fragrant; sweet-smelling xiangjiao banana xiangzi box, trunk xifng to think; want, would like to xifngff idea xiàng cv at, to, towards, in the direction of xiàng . . . xuéxí ... to learn from
xiàng mw piece of (work) xiaoxi news xifo little; small xifo shíhou in one’s childhood xifoba minibus xifohái baby xifohuizi youngster, lad xifojc chick xifojie Miss; young lady xifolù path xifomao kitten xifoshí hour xifoshud novel xifotíqín violin xifotdu petty thief xifoxcn take care xiào to smile; to laugh xib a little; a few xié(zi) ( ) shoe xig to write xièxie thank you xcnzhdng in one’s heart xcn new xcnnián New Year xcnwén news xcnxian fresh xìn letter xìnfbng envelope xìnjiàn correspondence xìnxc information xìnyòngkf credit card xìnzhh writing paper xcngqc week xcngqc èr Tuesday xcngqc liù Saturday xcngqc rì/tian / Sunday xcngqc san Wednesday xcngqc sì Thursday xcngqc wj Friday xcngqc yc Monday xíng to be all right xíngbutdng won’t do/work xíngdetdng will do/work xíngli luggage xínglijià luggage rack xíngrén pedestrian xìng surname
Vocabulary list: Chinese to English
335
Vocabulary list: Chinese to English
336
xióngmao panda xiexi to rest xie to repair xie(lh) ( ) to repair xjdud many, a lot of, much xufn to choose; to elect xué(xí) ( ) to study, learn xuénián academic/school year xuésheng student xuéxiào school xul snow xùnliàn to train, drill; training session Y ya (exclamation) yazi duck yáchh teeth yáshua toothbrush yf to be hoarse, to lose one’s voice ya (particle for exclamation) yan cigarette yángé strict yánsù (of composure) to be serious yánzhòng serious, grave (matter) yán cv along yán’àn along the bank/coast yán jib along the street yánjie to consider, research, study, look into yán salt yfn eye yfnjìng glasses, spectacles yfnjing eye yfnche to perform; performance, show yfnshì to demonstrate yáng sheep/goat yángròu lamb yáng the sun yfng to keep/rear yfng oxygen yao 7 one yaoqiú to request, demand; demand
yào medicine yàofáng pharmacy yào to want; must, need to; to be about to yàoshi key yéye (paternal) grandfather yg also, too yè page yè night, evening yc one yc yfn at a glance yc yè all night ycdifnr a little ycdìng certainly ycguàn all along, consistent ychuìr (for) a while ycknuqì in one breath yclù all the way ycqh together ycxià one time, once; briefly, a while ycxib a little, some ycyàng the same ycyuè January yczhí straight ycfu clothes ycguì wardrobe ycjià coat-hanger, clothes stand yczhuó D clothing doctor ycshbng ycyuàn hospital yímo (maternal) aunt yízhàng uncle (husband of mother’s sister) yímín immigrant/emigrant; to emigrate yh already yhjcng already yhhòu later; after; afterwards yhqián ago; before, previously yhzi chair yì one hundred million yìdàlì Italy yìjiàn view, opinion yìlì willpower, perseverance ycn cloudy, overcast ycnxifng hi-fi ycnyuè music
ycnyuèhuì concert yínháng bank yìnxiàng impression ycnggai ought to, should ycngguó England, Britain ycngguó rén British/English (people) ycngjílì hfixiá the English Channel ycnglh mile ycngwén English (language) ycngwj parrot yíngyè open (for business) yìng hard yingyufn for ever yòng to use; cv using, with yóu by, up to; out of; from (place/time) yóuyú cv because of, owing to yóudìyuán postman yóujú post office yóuting pillar-box yóu to swim yóuying to swim yóuyingchí swimming pool yiuhfo friendly yiu to have; there is/are; verb used in comparisons yiu kòng to be free yiu méiyiu did/have (you) . . . or not? yiu yìsi interesting yiumíng to be famous/well known yiuqián to be rich yiuqù interesting yiuxiào effective yiuyòng useful yòu again yòubian (to) the right (of); right-hand side yòumiàn (to) the right (of); right-hand side yú in; on; at yú fish yj cv with; and yj rain yjsfn umbrella
yùbào forecast yuanyang mandarin ducks; an affectionate couple yuán round (in shape) yufn distant, far yuàn(yi) ( ) be willing (to) yubhàn John yuè month; moon yuèche (at the) beginning of the month yuèdh (at the) end of the month yuèliang moon yuèqj music, musical composition yuèlfnshì reading room yuè . . . yuè . . . . . . . . . the more . . . the more . . . yuè lái yuè . . . . . . more and more . . . yún cloud yùndòngchfng sports field yùndònghuì sports meeting yùndòngxié trainers/sneakers yùndòngyuán athlete yùnhé canal Z zài again zàijiàn goodbye zài in, at; to be in, at; (continuous action aspect marker) zài ch here zàijia to be at home zánmen we/us (including the listener) zàntóng to agree to, approve of zang dirty zfo early zfodifn(r) ( ) a bit earlier zfoshang morning zgnme how zgnme yàng how, in what way zgnyàng how zhàlan fence zhànshèng to defeat, overcome zhàn station, stop; to stand
Vocabulary list: Chinese to English
337
Vocabulary list: Chinese to English
338
zhàntái (station) platform zhang mw (piece of paper, table) zhang (surname) Zhang zhfng to grow; head, chief zhàngfu husband zhaoshiu to beckon, wave zhfo to look for zhfo dào to find zhào to take (a photograph) zhàogu to look after zhàopiàn photograph zhàoxiàngjc camera zhémo to persecute, torment zhè/zhèi this zhème so, like this zhèr here zhèxib these zhèyàng so, like this zhe D (aspect marker) zhbn true, real; really, truly zhbn de honestly zhbnshí true zhbnxiàng real/true situation zhèn mw a gust of (wind), a peal of (thunder), mw (for laughter) zhèn small town zhbngyuè the first month of the lunar year zhgng whole, entire zhgngnián all the year round, the whole year zhlngqí tidy, in good order zhgngtian all day, the whole day zhgng wfn the whole evening/ night zhèng just; precisely zhèngquè accurate, correct (zhèng)zài ( ) just/in the process of . . . ing zhèngfj government zhc (Classical Chinese attributive) zhc zhdng during, in, among, between zhchòu later; after; afterwards zhcqián ago; before zhc mw (for pen, toothpaste, etc.) zhc mw (for animals, birds; utensils)
zhc mw (for rifle, etc.) zhcdao to know zhcshi knowledge zhí straight zhíban to be on duty zhíde to be worth, merit zhíwùyuán botanical garden zhh only zhh yiu only; only if zhhshì to just/only be; but then zhh paper zhhzhang paper zhìyú as for; as far as . . . is concerned zhdng during; in, among zhdngguó China zhdngguóhuà Chinese paintings zhdngguó rén Chinese (people) zhdngjian the middle zhdngwén Chinese (language) zhdngwj midday, noon zhdngxué secondary school zhdng clock zhdngtóu hour zhing mw kind of zhingzhing all kinds of zhòng to win (a prize) zhòng to plant zhòng heavy zhòngyào important zhdu mw week zhdu (surname) Zhou zhdumò weekend zhduwéi all around; vicinity zhezi pearl zhe pig zhe nián the year of the pig zhj to cook, boil zhù to live, reside zhùdexià to house, accommodate zhù to wish, express good wishes to zhua to grab, grasp zhuang to pack zhuàng mw (for buildings) zhjn accurate
zhudzi table zì word; character zì from zìjh oneself zìjh lái to help oneself zìxíngchb bicycle zing shì always ziu to walk; to leave; off (as a complement) ziubudòng cannot walk (any more) ziulù to walk, go on foot ze to rent, lease zú(zú) ( ) fully, no less than zúqiú soccer zúqiúchfng football ground, soccer field zúqiúduì football team zúqiúsài football/soccer match zjchéng to consist of, be made up of zuan to come out of or go into (a hole, burrow, etc.) zuhba mouth
most zuì zuìhfo the best; had better zuì drunk zuìxenxen drunk, tipsy zuó wfn last night, yesterday evening zuótian yesterday zui left zuibian left side zuimiàn left side zunyòu (suffix) about, or so zuò to sit; to travel by (boat, plane, train, bus) zuò xià to sit down zuòbuxià do not have enough room for zuòyè coursework zuò mw (for mountains, bridges) zuòtánhuì discussion, seminar, symposium zuòwèi seat zuò to do; to be, act as zuòff method, way of doing something zuòfàn cook a meal
Vocabulary list: Chinese to English
339
VOCABULARY LIST
English to Chinese A able to huì , néng about: (regarding) duìyú ; (approximately) jh , lái , dàyub , zuiyòu about to yào above shang , shàngbian , shàngmian , shàngtou absent (from a meeting etc.) qubxí academic/school year xuénián accommodate zhù de xià accomplish (get done) bàndào , (complete) wánchéng according to ànzhào , píng accountant kuàijì accurate zhèngquè , zhjn accustomed to xíguàn ache suan , suanténg , téng aching suanténg act as zuò add jia admit a mistake rèncuò admitted to (a theatre, etc.) rùchfng
340
adult dàren advertisement gufnggào affair shìqing afraid kingpà after hòu , yhhòu , zhchòu ; after all jiejìng afternoon xiàwj afterwards yhhòu , zhchòu again yòu , zài
ago yhqián agree tóngyì
, zhcqián ; agree to zàntóng
ah (exclamation) a airport fbijcchfng
, jcchfng
alive huó all ddu , gègè ; all along (always) cónglái , (consistent) ycguàn ; all around zhduwéi ; all kinds of zhingzhing ; all right xíng ; all the way yclù allow ràng almost chàbudud along yán , along the coast/bank yán’àn , along the street yán jib Alps a’grbbisc shan already yh , yhjcng also yg always zing shì America mgiguó among zhc zhdng , zhdng amuse oneself wánr amusing hfowánr affectionate couple yuanyang anchor (v) tíngbó ancient gjlfo and gbn , hé , tóng , yj angry qì ; get angry shbngqì another person biéren answer (solution) dá’àn anxious jí anybody rén
apart from chú(le) . . . (zhcwài /yhwài) ( )...( / ) apple pínggui approve of zàntóng approximately dàyub , shàngxià , zuiyòu army bùduì around (approximately) dàyub , lái ; (on all sides) sìzhdu arrive dào , dàodá ; arrive late chídào ; arrive at (a decision, conclusion) déche article wénzhang artist huàjia as far as . . . is concerned, as for zhìyú ; as regards guanyú ; as to duìyú ; as well as chú(le) . . . (zhc wài/yh wài) ( ) ...( / ) ascend shàng , shbng ask wèn assemble jíhé astronomy tianwén at cháo , duì , xiàng ; yú ; zài ; at a glance yc yfn ; at home zàijia ; at once jiù , mfshàng ; at that moment nà shíhou ; at the worst dàbulifo athlete yùndòngyuán attend canjia , (a meeting) kai ; attend to kan August bayuè aunt (father’s sister) gegu ; (father’s married sister) gemj ; (maternal) yímj ; (mother’s sister; mother’s brother’s wife) jiùmj ; (wife of father’s elder brother) bómj autumn qietian aware of gfnjué away: be away (from home) chemén awful kj B baby xifohái bad huài
bake kfo ball qiú balloon qìqiú banana xiangjiao bank yínháng bar jijbajian be shì ; (become, act as), dang zuò be/come from lái zì beach hfi bian , shatan bearer láirén bearing jjzhh beautiful mgi , mgilì , piàoliang because of yóuyú beckon zhaoshiu bed chuáng bee mìfbng beef niúròu beer píjij before qián , xian , yhqián zhcqián beginning from cóng . . . qh ... behind hòu , hòubian , hòumian , hòutou ; behind someone’s back bèihòu
Vocabulary list: English to Chinese ,
,
Beijing bgijcng ; Beijing opera jcngjù below, beneath dhxia , xià , xiàbian , xiàmian , xiàtou beside bian best, the best zuìhfo between zhc zhdng bicycle zìxíngchb big dà bird nifo birthday shbngri bitter kj graduate (v) bìyè black hbi ; black tea hóngchá blackboard hbibfn bleed chexuè bloodshot (of eyes) hóng blow (v) chuc blue lán blurred (of vision) hua
341
Vocabulary list: English to Chinese
board (a bus, car, train, etc.) shàng body shbnth boil zhj book she , shebgn booklet bgn(zi) ( ) bookshelf shejià bookshop shediàn borrow jiè botanical garden zhíwùyuán bother about gufn bottle píngzi bowl wfn box hézi , xiangzi boy nán háizi boyfriend nán péngyou bread miànbao break dfpò breathe/pant chufnqì bridge qiáo briefly ycxià brightly coloured hónghóng lqlq brilliant jcngcfi bring dài Britain ycngguó British/English (people) Ycngguó rén broad kuan broken pò build gài building lóufáng bump/run into (someone) pèngjiàn bus bashì , gdng(gòng qì)chb ( ) bus stop qìchbzhàn business shìqing busy fánmáng , máng but bùguò , dànshì , kgshì ; but then zhhshì buy mfi by (passive agent) bèi , ràng , jiào , yóu ; by the side of bian ; by ticket only píngpiào
342
C cabbage báicài cabinet guìzi cage lóngzi cake dàngao call (the doctor, a taxi) jiào calm jìng camcorder shèxiàngjc camel luòtuo camera zhàoxiàngjc can huì , kg(yh) ( ), néng ; can do nothing but mifn bu lifo ; can get along with hé de lái ; can go so far as to say tán de shàng can (tin) guàntou Canada jianádà canal yùnhé cannot avoid mifn bu lifo ; cannot be justified shud bu guòqù ; cannot get along with hé bu lái ; cannot help jcnbuzhù ; cannot walk (any more) ziu bu dòng capable of néng car chb(zi) ( ), qìchb carry (on back) bbi , (with both hands) duan carry-out wàimàidiàn cat mao catch a cold gfnmào catch up with gfnshàng ceiling tianhuabfn celebrate qìngzhù centimetre gdngfbn century shìjì certainly ycdìng chair yhzi chalk fgnbh change, small change língqián change biànhuà , gfi ; change the time for gfiqc chaos/in chaos luàn chat liáotian(r) ( ), tán , tánhuà/tian / cheap piányi cheat (v) qcpiàn chef chúshc
chess qí chick xifo jc chicken jc chief zhfng child/children háizi childhood/in one’s childhood xifo shíhou China zhdngguó Chinese (language) hànyj , zhdngwén ; (people) zhdngguó rén ; Chinese character hànzì , zì ; Chinese dumplings jifozi ; Chinese paintings zhdngguóhuà choir shèngshcban choose xufn chopsticks kuàizi Christmas shèngdàn ; Christmas cards shèngdànkf church jiàotáng cigarette yan cinema diànyhngyuàn circular tdngzhc city chéng , chéngshì ; city centre shìzhdngxcn class (school) ban classmate tóngxué classroom jiàoshì clean ganjìng , (v) dfsfo clear míngbai , qcngchu clearly qcngchu climb pá ; climb a mountain pá shan clip (v) jifn clock zhdng close (near) jìn ; (turn off) guan(shang) ( ) cloth bù clothes ycfu , fúzhuang ; clothes stand ycjià ; clothesline liàngycshéng clothing yczhuó D cloud yún cloudy ycn coach (n) jiàoliàn coat-hanger ycjià
coffee kafbi ; coffee bar kafbigufn cola kglè cold léng collapse dfo collect honey cfi mì come lái ; come/be from lái zì ; come back huí lái ; come down xià ; come from a distance (of sound) chuán lái ; come here/over guò lái ; come in jìn lái ; come out che lái ; come out of (a hole, burrow, etc.) zuan ; come to (a conclusion) déche ; come/go downstairs xià lóu comfortable shefu , sheshì commit to memory bèi shú/shóu communications jiaotdng complete quán composed of héchéng composition wénzhang computer diànnfo concerned about guanxcn concert ycnyuèhuì conclude jiéshù conclusion jiélùn conditions qíngkuàng consider yánjie consist of zjchéng consistent ycguàn cook chúshc ; (v) zhj ; cook a meal zuòfàn cooker lúzi correct (right) duì , zhèngquè , (v) gfi correspondence xìnjiàn cough késou country guójia countryside xiangcen coursework zuòyè cow niú credit card xìnyòngkf cross guò crossing lùkiu crow weya crowd (of people) rénqún
Vocabulary list: English to Chinese
343
Vocabulary list: English to Chinese
cry ke culture wénhuà cup bbi(zi) ( ) cupboard guìzi , wfnguì curtain (for window) chuanglián curved wan cut (v) jifn D damp shc dance (v) tiàowj , (n) wj ; (party) wjhuì dare gfn ; dare you (do it)? nh gfn
344
dash chdng date (of the month) rì daughter ns’ér day tian , báitian ; all day zhgngtian ; day after tomorrow hòutian ; day before yesterday qiántian daytime báitian deal with bàn deceive piàn December shí’èryuè decide juédìng ; (fix) dìng decimal point difn deep shbnkè defeat zhànshèng definitely quèshí degree (of temperature) dù delicious hfochc deliver (letters) sòng demand yaoqiú demonstrate yfnshì depart, set out qhchéng deposit (money) cún deputy fù descend xià destination mùdìdì dictionary cídifn die shìshì difficult nán difficulty kùnnan dinner wfnfàn direction fangxiàng ; in the direction of xiàng
dirty zang disappointed shcwàng disease bìng dish (of food) cài disobedient bù guai disorder/in disorder luàn dissertation lùnwén distant yufn ; distant from (a place) lí ditch (n) gdu do nòng , zuò doctor ycshbng dog giu don’t bié , bù yào door mén dormitory sùshè downstairs lóuxià dragon lóng drama xì drawer chduti dress fúzhuang drill xùnliàn drink (v) hb drive kai ; (a car) kaichb driver scjc drop (v) diào drunk zuì , zuìxenxen dry gan ; dry in the sun shài (gan) ( ); dry/hang out to dry liàng duck yazi during zhc zhdng dysentery lìji
, zhdng
E each and every one gègè ear grduo early zfo ; a bit earlier zfodifn(r) ( ) earnest, honest lfolaoshíshí earnestly hfohfor earrings grhuán east ddngbian , ddngmiàn eat chc , chcfàn ; unable to eat (anything/any more) chc bu xià economic, economy jcngjì
education jiàoyù effective yiuxiào egg jcdàn eggshell dànké eight ba elder brother gbge ; elder sister jigjie elect xufn embassy dàshhgufn emigrant/immigrant yímín emigrate yímín end (v) jiéshù ; end of the month yuèdh engineer gdngchéngshc England ycngguó English (language) ycngwén ; English/British (people) Ycngguó rén ; English Channel ycngjílì hfixiá enjoyable hfowánr enough gòu enter jìn ; enter a gathering rùchfng entertain kufndài entire zhgng envelope xìnfbng essay lùnwén , wénzhang Europe duzhdu even lián ; even (more) hái (yào) ( ) . . . ; even more gèng evening wfn , wfnshang , yè every mgi everybody, everyone dàjia , rénrén everything shénme exceptionally fbicháng excuse (n) jièkiu expensive guì experiment (n) shíyàn explain jifngjig expose to the sun shài express bifoshì ; express good wishes to zhù extremely fbicháng , shífbn , tài eye yfn , yfnjing eyebrow méimao
F fall diào ; (of rain, snow) xià ; (of tears, sweat) liú ; fall ill shbngbìng family jia famished è sh le famous yiumíng far yufn farmer nóngmín fat pàng father bàba , fùqin February èryuè feed (give food to) wèi feel gfnjué ; feel at ease anxcn
Vocabulary list: English to Chinese
fence zhàlan ferryboat dùchuán few, a few: jh . xib ; (in approximations) jh fight df , dfjià film diànyhng find zhfo dào finger shiuzhh finish (v) wánchéng ; (successfully – suffix) hfo ; finish school/class fàngxué ; finish work xiàban finished (complement) diào , wán fire hui first xian ; the first dìyc ; the first floor èr lóu ; the first month of the lunar year zhbngyuè fish yú five wj fizzy drink qìshuh floor dìbfn ; (storey) lóu flow liú flower hua(r) ( ), hua dui fly (insect) cangying fly (v) fbi fog wù foot jifo ; foot of the mountain shanjifo football ground zúqiúchfng ; football match zúqiúsài ; football team zúqiúduì
345
Vocabulary list: English to Chinese
for tì , wèi ; for/to ggi ; for ever yingyufn forecast yùbào former qián four sì fragrant xiang France ffguó free (not busy) yiu kòng French (language) ffwén/yj / ; (person) ffguó rén frequently chángcháng fresh xcnxian ; fresh flowers xianhua Friday lhbài wj , xcngqc wj fridge bcngxiang fried noodles chfomiàn ; fried rice chfofàn friend péngyou friendly yiuhfo frog qcngwa from (place/time) cóng , yóu , zì front, in front qián , qiánbian , qiánmian , qiántou ; in front of the door mén qián fruit shuhgui full (of food) bfo fully zú(zú) ( ) funny dòu future, the future jianglái G gamble dj , djbó game qiúsài garage chbkù garbage lajc ; garbage/litter bin lajcting garden huayuán gate mén gather jíhé gaze at wàng generous dàfang , kangkfi
346
gentleman xiansheng German (language) déwén/yj /
get dédào get off/out of (a vehicle) xià (chb) ( ); get on/into (a vehicle) shàng (chb) ( ); get out che qù ; get to dàodá get up qhlái ; (out of bed) qhchuáng ; get up late shuì lfn jiào ginger jiang girl ns háizi , geniang ; girlfriend ns péngyou give back huán ; give birth to shbng glass bbi(zi) ( ) glasses (spectacles) yfnjìng gloves shiutào go qù ; go to dào , shàng ; go abroad cheguó ; go angling/fishing diàoyú ; go back huí (qù) ( ); go down xià (qù) ( ); go for a walk sànbù ; go home huí jia ; go in jìn qù ; go into (a hole, burrow, etc.) zuan ; go into town jìn chéng ; go jogging pfobù ; go on foot ziulù ; go on holiday dùjià ; go on the internet shàngwfng ; go on the stage shàngtái ; go out che qù ; go over guò qù ; go to bed shàngchuáng , shuìjiào ; go to class shàngkè ; go to school shàngxué ; go to work shàngban ; go travelling lsxíng/yóu / ; go up shàng ( ); go/come downstairs xià lóu goal (goalposts) qiúmén goat/sheep yáng goldfish jcnyú good hfo ; good/nice to drink hfohb good at huì goodbye zàijiàn good-looking hfokàn government zhèngfj grab zhua
grade (in school) niánjí graduate (v) bìyè grandfather (paternal) yéye grandmother (paternal) nfinai grape pútao grasp zhua grass cfo ; (lawn) cfodì grave (matter) yánzhòng great kindness shèngqíng Great Wall chángchéng green tea lq chá ground dì grow zhfng guess (v) cai guest kèren guitar jíta gun qiang H habit xíguàn had better zuìhfo hair tóufa half bàn hand shiu ; hand in jiao handle bàn , nòng handsome piàoliang hang (up) guà happy gaoxìng , kuàilè ; happy occasion xh shì harbour gfngkiu hard yìng hard-working njlì hare tù(zi) ( ) hat màozi have yiu ; have a bath xhzfo ; have a fever fashao ; have a meal chcfàn ; have an appointment with jiàn ; have an injection dfzhbn ; have an operation kaidao have to bìxe , dgi he/him ta head (chief) zhfng healthy jiànkang heaven tiankdng ; Heavens tian na ! heavy zhòng ; heavy rain dà yj ; heavy snow dà xug
hedge shùlí hello nh hfo ; (on telephone) wèi help bang(zhù) ( ); help oneself zìjh lái her/hers ta de here zhèr , zài ch hey wèi hide dui hi-fi ycnxifng high gao hill shan , hillside shanpd Himalayas xh mflayf shan his ta de history lìshh hit df ; hit out at people df rén
Vocabulary list: English to Chinese
hoarse yf hold (in hand) ná ; (a meeting etc.) kai , jj xíng hole dòng home jia ; at home zài jia honest lfoshi honestly zhbn de hope (n/v) xcwàng horn (of a car) lfba horse mf ; horses mfph hospitable kufndài hospital ycyuàn ; hospital ward bìngfáng host (v) qhngkè hot rè ; (peppery) là hour xifoshí , zhdngtóu house fángzi ; (v) zhù de xià how (extent) dud(me) ( ); how big dud dà ; how far dud yufn ; how long (of time) dud jij , dud cháng (shíjian) ( ); how many dudshao , jh ; how much dudshao how (in what way) zgnme yàng , zgnme , zgnyàng , rúhé how about rúhé , zgnme yàng hum (a tune) hbng hundred bfi
347
Vocabulary list: English to Chinese
hungry è hurry ahead/along gfnlù hurt téng husband zhàngfu ; husband and wife fefù hydrogen qcng I I wi ice cream bcngjilíng idea xifngff , kànff ideal lh xifng idler xiánrén illness bìng , bìngtòng immediately mfshàng immigrant/emigrant yímín important zhòngyào impression yìnxiàng in zài , yú , . . . lh , . . . (zhc zhdng ); in accordance with ànzhào ; in good order zhgngqí ; in one breath yckiuqì ; in one’s heart xcnzhdng ; in order to wèile ; in the future jianglái ; in the past guò qù , qián ; in three days’ time dà hòutian ; in what way zgnme yàng
K keep fàng ; (rear) yfng key yàoshi kick tc kilogram gdngjcn kilometre gdnglh kind rèqíng kitchen chúfáng kitten xifo mao knife dao knock pèng , qiao know zhcdao ; (recognise) rènshi ; know (very) well shú/shóuxc knowledge zhcshi
inch cùn incident shì(r) ( ) increase (v) jia individual gèrén industrious njlì , qínfèn inform gàosu information xìnxc injured shòushang inside lh , lhbian lhtou intelligent cdngming interesting yiu yìsi
348
, lhmiàn
, yiuqù
intersection lùkiu invite qhng ; (guests) qhngkè issue (forth) fache it ta Italy yìdàlì
J jacket wàitào January ycyuè Japan rìbgn Japanese (language) rìyj ; (people) rìbgn rén jeans niúzfikù jewellery shiushi John yubhàn joke (v) kai wánxiào journey lùchéng jump tiào June liùyuè just zhèng , zhh shì ; just/in the process of . . . ing (zhèng)zài ( ) just (now) gangcái , ganggang , gang justifiable, be justifiable shud de guòqù
,
L lack chà lad xifo huizi lake hú lamb yángròu lamp dbng landscape painting shanshuhhuà large dà last shàng ; last night zuó wfn ; last year qùnián
late wfn , chí ; arrive late chídào later yhhòu , zhchòu laugh xiào laughable hfoxiào laundry xhycdifn lead to tdng learn xué(xí) ( ); learn by heart bèi ; learn from xiàng . . . xuéxí ... lease ze leather shoes píxié leave líkai , ziu ; leave for kaiwfng ; leave behind liú xià Leeds lìzc left (side) zui , zuibian , zuimiàn leg tuh lend jiè let, allow ràng letter xìn ; (incoming) láixìn ; (of recommendation) tucjiànxìn library túshegufn ; library card túshezhèng lie tfng ; (tell a lie) sahufng life shbnghuó life-guard jiùshbngyuán lift diàntc light (opposite of heavy) qcng light, lamp dbng like, be fond of xhhuan like that nàme , nàyàng like this zhème , zhèyàng likeable kg’ài likely to huì lion shczi listen tcng ; (understand) tcng ding litchi/lychee lìzhc literature wénxué litter lajc ; litter bin/garbage bin lajcting little xifo ; a little xib , ycdifnr , ycxib live shbnghuó ; live (reside) zhù
living huó London lúnden long cháng long to babudé look (at) kàn , qiáo ; look after gufn , kan , kangufn , zhàogu ; look down on kànbuqh ; look for zhfo ; look into yánjie ; look round canguan lose die ; (a bet) she ; lose hope shcwàng ; lose one’s voice yf ; lose weight jifnféi lot of, a lot of xjdud lovely kg’ài low fi luggage xíngli ; luggage rack xínglijià luncheon meat wjcanròu lychee/litchi lìzhc lyrics gbcí
Vocabulary list: English to Chinese
M made up of zjchéng mah-jong májiàng main road dàlù make nòng ; (a phone call) df ; (dumplings) bao ; (friends) jiao ; make a noise chfo ; make sb do sth jiào manage bàndào ; manage by oneself lái manager jcnglh Manchester mànchéng mandarin ducks yuanyang manner, bearing jjzhh many dud , bù shfo , xjdud map dìtú March sanyuè market shangchfng
, shìchfng
marry jiéhen Mary mflì match (contest) bhsài , qiúsài ; (safety) huichái matter shì(r) ( ), shìqing may kg(yh) ( ), néng
349
Vocabulary list: English to Chinese
May wjyuè me wi meadow cfodì meat ròu medicine yào meet (sb) (at an airport, etc.) jib meet jiànmiàn ; (sb at an airport, etc.) meeting huì(yì) ( ) merit (v) zhíde messenger láirén meteorological qìxiàng method bànff , fangff , zuòff metre gdngchh midday zhdngwj middle, the middle zhdngjian midnight bànyè mile ycnglh milk niúnfi million bfiwàn mine wi de minibus miànbaochb ; xifoba mishandle nòng misplace die miss, be late for (a bus, train, etc.) wù Miss nsshì , xifojie mist wù modern xiàndài Monday lhbài yc , xcngqc yc money qián monkey hóu(zi) ( ) month yuè ; beginning of the month yuèche ; end of the month yuèdh moon yuè , yuèliang more dud ; more and more . . . yuè lái yuè . . . . . . ; the more . . . the more . . . yuè . . . yuè ... ... ... morning zfoshang , shàngwj
350
most zuì mother mama , mjqcn motorbike mótudchb
mountain shan mouse/rat lfoshj mouth kiu , zuhba move dòng ; (home) ban movie diànyhng mow the grass gb cfo Mr xiansheng Mrs tàitai Ms ns shì much dud , xjdud ; much more (complement) dé dud multi-coloured hónghóng lqlq multi-storied building dàlóu mum mama museum bówùgufn music ycnyuè , (musical composition) yuèqj must bìxe , yào must not bù dé my, mine wi de N name: what is your name (polite form) guì xìng nanny bfomj narrow xiázhfi naughty bù guai , tiáopí near jìn ; near(by) fùjìn need to yào neighbour línje nervous jhnzhang never cóng bù ; never again bù zài new xcn ; New Year xcnnián news xiaoxi , xcnwén newspaper bào(zhh) ( ) next xià ; next year míngnián ; next to pángbian ; next door gébì nice/good to drink hfohb nice/pleasant to the ear hfotcng night yè ; (opposite of daytime) hbiyè ; all night yc yè nine jij no bù , bù shì ; no less than zúzú ; no longer/more bù zài ; no need bù bì , bù yòng
; no room for zuò bu xià ; no wonder guàibude no(t) more . . . than bù bh nod (the head) difntóu none of your business nh bié gufn noon zhdngwj north (side) bgibian
, bgimiàn
nose bízi not bù , méi ; not allow(ed)/permit(ted) bù zhjn , bù xj ; not –er than bù bh ; not have méi(yiu) ( ); not . . . until cái notebook bgn(zi) ( ) notice tdngzhc notify tdngzhc novel xifoshud November shíycyuè now xiànzài number of people rén shù nurse hùshi O o’clock difn zhdng obedient guai obtain dédào of course dangrán off (as a complement) ziu office bàngdngshì often chángcháng old lfo , jiù ; (of age) dà Olympic Games àolínphkè yùndònghuì on yú , zài , shang ; on the ground dìxià ; on all sides sìzhdu ; on behalf of tì ; on duty zhíban ; on one’s best behaviour hfohfor ; on one’s person shbn shang ; on the basis of gbnjù , píng one yc , yao 7 once, one time ycxià one hundred million yì oneself zìjh , gèrén
only zhh , zhh yiu , only zhhshì , bùguò ; (just) ganggang ; only if zhh yiu ; only then cái open kai ; (door) kaimén ; (for business) yíngyè opinion kànff , yìjiàn opportunity jchuì opposite duìmiàn or huòzhg ; (in questions) háishi
Vocabulary list: English to Chinese
orange chéngzi order jiào ordinary pjtdng other people biéren ; other places wàidì others biéren ; (the rest) qíta ought to gai , ycnggai ; ought not to bù gai our/ours women de ; (including the listener) zánmen de out (of) chelái , cheqù ; out of yóu ; out of the question tán bu shàng ; out of work shcyè outcome jiégui out-of-date jiù out-of-town (areas) chéng wài outside wài , wàibian , wàimian , wàitou ; outside the city chéng wài oven kfoxiang over shang overcast ycn overcoat dàyc overcome kèfú , zhànshèng owing to yóuyú ox niú oxygen yfng P pack (v) zhuang packet bao page yè pain téng
351
Vocabulary list: English to Chinese
paint (v) huà painter huàjia painting huàr panda xióngmao paper zhh , zhhzhang parcel baogui parents fùmj Paris balí park gdngyuán park (v) tíng ; park (a car) tíngchb parrot ycngwj party (drinks) jiùhuì ; (evening) wfnhuì pass (time) guò pass away shìshì passenger chéngkè path xifolù pay/salary gdngzc peach táozi pear lí pearl zhezi peasant nóngmín pedestrian xíngrén Peking duck bgijcng kfoya ; Peking University bgijcng dàxué
352
pen bh pencil qianbh people rén peppery là percentage bfi fbn zhc perform, performance bifoyfn yfnche permit ràng persecute zhémo perseverance yìlì person rén persuade quàn petrol qìyóu petty thief xifotdu pharmacy yàofáng photograph zhàopiàn photographer shèyhngshc piano gangqín picture huàr piece of string shéngzi pig zhe
,
pigeon gbzi pillar-box yóuting place (v) gb plain pjsù plan jìhuà plane fbijc plant (v) zhòng platform (in a station) zhàntái play/drama xì play wánr , df (basketball, table-tennis, etc.); (piano, organ, harp, etc.) tán ; (the violin) la ; play mah-jong dfpái ; play with a skipping rope tiàoshéng please qhng pleased gaoxìng pocket kiudài polite kèqi pond/pool chí , shuhchí population rénkiu postman yóudìyuán post office yóujú postpone gfiqc potato mflíngshj pound (currency) bàng ; (weight) bàng pour out (tea) dào practice df Prague bùlagé precisely zhèng present (n) lhwù pretty hfokàn , piàoliang previous qián , shàng previously yhqián prize/prize money jifng problem wèntí profound shbnkè programme jiémù prosperous wàng pub jijbajian public square gufngchfng pull la purse qiánbao put fàng , gb ; put back fàng huí ; put forward tí , tí che ; put up (a house) gài Pyramids jcnzìtf
Q quarrel chfo(jià) ( ) quarter of an hour kè question wèntí , tímù queue (v) páiduì quick kuài quiet anjìng , jìng quieten down anjìng quilt bèizi quite a few bù shfo R rabbit tù(zi) ( ) railway station huichbzhàn rain yj , (v) xià yj raise tí che rat/mouse lfoshj reach dàodá read dú , kàn reading room yuèlfnshì real zhbn ; real situation zhbnxiàng really quèshí , zhbn rear hòubian , hòumian , hòutou rear/keep yfng reason dàoli recall jì recline tfng recognise rènshi record jìlù red hóng reduce jifnshfo regarding guanyú regulation gucdìng , tiáolì remember jì , jìde remit huì rent (v) ze repair (v) xie(lh) ( ) reply huí , huída request yaoqiú research yánjie reside zhù resolve jigjué responsible for fùzé rest xiexi (v) restaurant cangufn , fàngufn
result jiégui return (to a place) huí ; (to one’s country) huí guó ; (give back) huán revise (lessons) fùxí rice mh ; (cooked) fàn rich yiuqián ride qí ridiculous hfoxiào rifle qiang right duì right-hand side, to the right (of) yòubian , yòumiàn ripe shú/shóu ripen shóu/shú rise qhlái , shbng ; (of the sun) che lái river hé riverside hé bian road lù , mflù ; by the side of the road lù bian roadside lù páng roast kfo Rome luómf roof wedhng room fángjian , wezi rope shéngzi rose méigui (hua) ( ) round (in shape) yuán rucksack bbibao rule (n) tiáolì run pfo ; run after gfn ; run/bump into (someone) pèngjiàn rush for gfn Russia éguó Russian (language) éyj
Vocabulary list: English to Chinese
S safe and sound píng’an safe/strongbox bfoxifnguì salary gdngzc salt yán same, the same ycyàng sand sha sandwich sanmíngzhì Saturday lhbài liù , xcngqc liù
353
Vocabulary list: English to Chinese
say shud , jifng scarf wéijcn scenery fbngjhng school xuéxiào ; school bag shebao ; school/academic year xuénián scissors jifndao score (a goal) jìn qiú sea hfi seagull hfi’du seal hfibào seaside hfi bian , hfibcn seat zuòwèi secondary school zhdngxué see jiàn , kàn , kànjian sell mài seminar zuòtánhuì send jì September jijyuè serious (of composure) yánsù serious yánzhòng serve as dang set off/out chefa ; qhchéng ; dòngshbn seven qc shadow boxing tàijíquán Shanghai shànghfi shark shayú shave gua húzi , tì húzi she/her ta sheep/goat yáng sheet (for bed) chuángdan ship chuán shipping chuánzhc shirt chènshan shoe xié(zi) ( ) shoot (a film) pai shop diàn , shangdiàn shopping mall (dà) shangchfng ( ) shore àn short dufn ; (of stature) fi ; short cut jìnlù ; short hair dufn fà should gai , ycnggai shoulder jianbfng show bifoshì ; (perform) yfnche
354
sick leave bìngjià side bian , páng ; at/by the side of bian , pángbian simple pjsù since cóng( . . . qh) ( . . . ) sing chàng ; sing (a song) chànggb sister-in-law (elder brother’s wife) sfosao sit zuò ; sit down zuò xià six liù size: what size (shoes, etc.) dud dà skilful in huì skip with a rope tiàoshéng skirt qúnzi sky tiankdng ; tianshàng sleep shuì , shuìjiào ; sleep in shuì lfn jiào slippery huá slogan biaoyj slow(ly) màn small xifo ; small town zhèn smile xiào smoke (cigarettes) chduyan , xcyan snake shé snow xug ; (v) xià xug so nàme , nàyàng , zhème , zhèyàng ; so that wèile soaked (drenched) lín shc soap féizào soccer zúqiú ; soccer field zúqiúchfng ; soccer match zúqiúsài society shèhuì sock wàzi sofa shafa soft rufn solution dá’àn solve jigjué some ycxib , xib somebody rén someone else rénjia son érzi song gb(r) ( ) sorry, I’m sorry duìbuqh
sound shbng , shbngycn sour suan south nán ; the south nánbian , nánmiàn soya bean huángdòu speak shud , jifng , shudhuà specially tèyì spectacles yfnjìng spend hua sports field/ground yùndòngchfng , caochfng ; sports meeting, games yùndònghuì ; sports shoes qiúxié , yùndòngxié spotlessly clean ganganjìngjìng
succeed chénggdng sugar táng suggest, suggestion jiànyì summer xiàtian ; summer time xiàlìng sun rì , tàiyáng , yáng sunbathe shài tàiyang Sunday lhbài rì/tian / ; xcngqc rì/tian / sunglasses hbi yfnjìng , tàiyángjìng supervisor/tutor dfoshc supper wfnfàn sure to huì surface of the sea/sea level hfimiàn
spring chentian square fang squirrel sdngshj stammer jibba ; stammering jibjiebaba stand zhàn stand to reason jifng dàoli start kaishh starving è sh le station zhàn ; (for train, bus) chbzhàn stay dai / ; stay behind liú xià
surname xìng swear (at) mà
steamed bun mántou still hái ; still –er hái (yào) ( ) stipulate gucdìng stone shítou stop tíng , zhàn storey (of a building) lóu story gùshi stove fire lúhui straight yczhí , zhí strawberry cfoméi street jib , jibdào , lù strict yángé strike (v) qiao string shéngzi strive njlì strong (of wind) dà strongbox/safe bfoxifnguì student xuésheng study (v) xué(xí) ( ), yánjie
Vocabulary list: English to Chinese
; (at people) mà rén
sweat hàn sweater máoyc sweep dfsfo sweet (to the taste) tián ; (voice, etc.) tiánmgi ; sweets táng ; sweet potato fanshj ; sweetsmelling xiang swim yóu , yóuying swimming pool yóuyingchí symposium zuòtánhuì T T’ai Chi tàijíquán table zhudzi table-tennis pcngpangqiú tail wgiba take dài , ná ; (a photograph) zhào , pai ; take a test kfo ; take care xifoxcn ; take out tao (che) ( ); take part in canjia ; take your time mànmàn lái take-away food wàimài ; takeaway (shop) wàimàidiàn talk (v) shudhuà , tán , tánhuà/tian / ; (n) huà ; talk about tándào tall gao task rènwu
355
Vocabulary list: English to Chinese
tasty hfochc
, (of drink) hfohb
taxi dìshì tea chá ; tea leaves cháyè ; tea party cháhuì teach jifngkè , jiao , jiaoshe team duì ; team captain duìzhfng ; team member duìyuán tease dòu teeth yáchh telephone diànhuà television diànshì ; television set diànshìjc tell gàosu , shud ; (ask to) jiào ; tell a lie sahufng ten shí ten thousand wàn tennis wfngqiú tension jhnzhang test (v) kfo text kèwén Thames tàiwùshì hé thank gfnxiè ; thank you xièxie
356
that nà/nèi the rest qíta theatre jùchfng ; theatre ticket xìpiào their(s) (m) tamen de , (f) tamen de then jiù theory lhlùn there nàr there is/are yiu ; there is/are not méi(yiu) ( ); there is/are still (some left) hái yiu these zhèxib they/them (f) tamen , (m) tamen , (neuter) tamen thin shòu thing ddngxi think xifng , rènwéi ; think highly of kàn de qh this zhè/zhèi ; this evening jcn wfn ; this morning jcn zfo those nàxib/nèixib thousand qian
thread xiàn three san ; three days ago dà qiántian ; three years ago dà qiánnián throat hóulóng , sfngzi throw rbng ; throw away diào thunder léi Thursday lhbài sì , xcngqc sì ticket piào tidy zhgngqí
; tidy (up) shdushi
tiger lfohu ; (sign of the zodiac) hj time shíhou , shíjian ; in time for lái de jí ; what time is it jh difn (zhdng) ( ) tin, can guàntou tip (rubbish) (v) dào tipsy zuìxenxen tired lèi to cháo , duì , xiàng ; to sb gbn ; to/for sb ggi ; to and fro láilái wfngwfng today jcntian together ycqh toilet cèsui tomorrow míngtian ; tomorrow evening míng wfn too tài ; too (also) yg ; too late for lái bu jí toothbrush yáshua topic tímù torment (v) zhémo touch dòng , pèng tour lsxíng/yóu / towards cháo , duì , wfng/wàng , xiàng towel máojcn town chéng toy wánjù traffic jiaotdng train huichb train (v) xùnliàn ; training session xùnliàn translate, translation fanyì travel by (boat, plane, train, bus etc.) zuò , da
tree shù , shùmù trousers kù(zi) ( ) true zhbn , zhbnshí ; true situation zhbnxiàng truly zhbn trunk xiangzi truth shíhuà try hard njlì Tuesday lhbài èr , xcngqc èr tune qjzi turn (v) gufi tutor dfoshc two èr , lifng type (v) dfzì U umbrella sfn , yjsfn uncle (father’s elder brother) bóbo ; (father’s younger brother) sheshu ; (husband of mother’s sister) yízhàng ; (mother’s brother) jiùjiu ; (husband of father’s sister) gezhàng unconcerned person xiánrén under dhxia , xià , xiàbian , xiàmian , xiàtou underground dìxià understand ding , lifojig , míngbai ; (by listening) tcng ding unemployed shcyè university dàxué unpleasant to hear nántcng until dào up shang ; qh , qhlái ; up to yóu ; up till now dào xiànzài upstairs lóushàng upward shàng qù , upward shànglai urge quàn us wimen , (including the listener) zánmen USA mgiguó use yòng useful yiuyòng
V vacuum-clean xcchén van miànbaochb vase huapíng vegetable cài ; vegetables shecài ; vegetable garden càiyuán ; vegetable oil càiyóu vegetarian chcsù vehicle chbliàng very hgn vice- fù vicinity fùjìn , zhduwéi video camera shèxiàngjc view yìjiàn view (opinion) yìjiàn , kànff vigorous wàng village xiangcen violin xifotíqín visit canguan , ffngwèn kàn , tànwàng visitor kèren voice sfngzi
Vocabulary list: English to Chinese
,
W wages gdngzc wait (for) dgng walk ziu , ziulù wall qiáng want xifng , yào ward (hospital) bìngfáng wardrobe ycguì warm nufn , nufnhuo ; warmhearted rèqíng wash xh washing-machine xhycjc watch kàn watch (wristwatch) shiubifo , bifo water shuh ; (v) jiao , jiao shuh watermelon xcgua wave (v) zhaoshiu way of doing something zuòff we wimen ; (including the listener) zánmen weak rufn wear (clothes) chuan , dài
357
Vocabulary list: English to Chinese
weather tianqì ; weather forecast qìxiàng yùbào wedding ceremony henlh Wednesday lhbài san , xcngqc san week lhbài , xcngqc weekend zhdumò welcome huanyíng well known yiumíng west (side) xcbian , xcmian wet shc whale jcngyú what shénme when (as) dang ; (question) shénme shíhou , jh shí where nfr which nf /ngi
; (plural) nf xib
while: (for) a while ychuìr , ycxià white bái who, whom shéi/shuí whole quán , zhgng ; whole family quán jia ; the whole day zhgngtian ; the whole evening zhgng wfn ; the whole year zhgngnián whose shéi/shuí de why wèishénme wide kuan wife qczi , tàitai , feren willing (to) yuàn(yi) ( ), kgn willpower yìlì win (a prize) zhòng wind fbng window chuang(hu) ( ); window sill chuangtái windy gua fbng wine jij winter ddngtian wipe ca , ma wish zhù with gbn , hé , tóng , yj ; (using) yòng without reason wúgù
358
witty dòu wok gud wolf láng word zì words huà ; (of a song) gbcí work gdngzuò ; work as dang ; work hard njlì ; will do/work xíng de tdng ; won’t do/work xíng bu tdng world shìjiè worry (about) caoxcn
, danxcn
worth zhíde would like to xifng write xig ; writing brush máobh ; writing paper xìnzhh wrong cuò Y Yangtze River chángjiang year nián ; school year niánjí ; all the year round zhgngnián ; the year after next hòunián ; the year before last qíannián ; the year of the pig zhe nián years of age suì yellow huáng ; the Yellow River huánghé yes duì , shì de yesterday zuótian ; yesterday evening zuó wfn yet hái you nh ; (polite form) nín ; (plural) nhmen young lady xifojie ; young man qcngnián younger brother dìdi ; younger sister mèimei youngster xifohuizi your(s) nh de ; (plural) nh men de Z zero líng zoo dòngwùyuán
GLOSSARY OF GRAMMATICAL TERMS
adjectives
adverbial
apposition
article
aspect markers
attitudinal verb
Words used to describe, define or evaluate qualities or characteristics associated with nouns, such as ‘big’, ‘green’, ‘good’. Gradable adjectives are adjectives that generally can be modified by a degree adverb. That is, they can be graded to varying degrees using a range of adverbs such as ‘very’, ‘extremely’, etc. Non-gradable adjectives are usually not modifiable by degree adverbs as they have more absolute meanings (e.g. ‘male’, ‘female’, ‘square’, ‘black’) and define rather than describe. In Chinese, a word or phrase placed directly before a verb to modify it, usually providing background information such as time, location, means, method, manner, etc. (e.g. ‘yesterday’, ‘in London’, ‘by train’, ‘with chopsticks’, ‘slowly’, etc.). When two nouns (or noun phrases) are placed next to each other to indicate the same entity, the second being in apposition to the first (e.g. Gordon Brown, the Prime Minister, etc.). A word like ‘a’, ‘an’, or ‘the’ in English which assigns definite or indefinite reference to the noun that follows it. The functional words le, guo, D zhe and zài which are closely associated with verbs. Le, guo and D zhe are suffixed to the verb, and zài immediately precedes it; they indicate the aspectual notions of completion, immediate or past experience, simultaneousness, persistence, and continuation. Chinese aspect markers are NOT indicators of tense. Tense is specified by time expressions placed before the verb or at the beginning of the sentence. In Chinese, a verb which reflects the speaker’s attitude. It may be followed by verbal as well as nominal objects (e.g. ‘I like tea, I like to drink tea’).
359
Glossary of grammatical terms
attributive
case
causative verb clause
comment
complement
composite sentence
conjunctions 360
In Chinese, a word, phrase or clause placed before a noun to qualify or identify it (e.g. ‘nice weather’, ‘a very useful book’, or a clause ‘a nobody-will-everforget experience’). In many languages, the form of a noun, pronoun or adjective changes to indicate its grammatical relationship with other words in the sentence. These forms are called cases. In English, cases only occur in pronouns for the nominative case (I, he, she, we and they) and the accusative case (me, him, her, us and them). They do not occur at all in Chinese. A verb which causes its object to produce an action or to change state (e.g. ‘ask him to come’, ‘make him happy’, etc.). A term employed to describe a subject-predicate or topic-comment construction which relates to other similar constructions, with or without conjunctional devices, to constitute a sentence in Chinese. The part of a sentence in a topic-comment sentence which follows the topic. The topic establishes the theme or focus of interest in the sentence, while the comment describes, defines, explains or contends, etc. In contrast with a subject-predicate sentence which narrates an incident (e.g. somebody did something), a topic-comment sentence makes observations, provides descriptions, offers explanations, etc. The verb shì ‘to be’, adjectives, modal verbs and the particle le are all regular elements in a comment. A word, phrase or clause which comes directly after either a verb (i.e. a verbal complement) to indicate the duration, frequency, terminal location or destination, result, manner or consequential state of the action expressed by the verb, or after an adjective (i.e. an adjectival complement) to indicate its degree or extent. A general term referring to a sentence which consists of more than one clause or predicate linked together by conjunction(s) or conjunctive(s). A composite sentence may therefore be of a compound or complex nature, using coordinate or subordinate conjunctions. Words used to join two words, phrases or clauses (e.g. ‘and’, ‘otherwise’, ‘because’, etc.). Conjunctions in Chinese often form related pairs (e.g. ‘because . . . therefore’, ‘though . . . however’, etc.).
conjunctives
Referential adverbs used to link two clauses or predicates/comments. context The extralinguistic situation or environment in which a verbal event takes place. cotext The verbal text (in speech or in writing) that goes before or after the verbal event under consideration. coverb In Chinese, a preposition-like verb which is not normally used on its own but is followed by another verb (or other verbs). A coverb with its object forms a coverbal phrase, which indicates location, method, instrument, reference, etc. dative verb A verb which requires two objects: a direct object and an indirect object (e.g. ‘give him a present’, in which ‘him’ is the indirect object and ‘present’ is the direct object). definite Terms used in connection with nominal or pronominal reference and items. The difference between definite and indefinite indefinite reference may be illustrated by the use of the reference definite article ‘the’ and the indefinite article ‘a(n)’ in English. degree adverb See adjectives. demonstrative A word (e.g. ‘this’, ‘that’, ‘these’ or ‘those’) which singles out an entity or entities from others of the same group or category. direction A set of motion verbs which follow other verbs as indicators direction complements to indicate the spatial direction or, sometimes, the temporal orientation (i.e. ‘beginning’, ‘continuing’ or ‘ending’) of the actions expressed by those verbs. disyllabic Of two syllables. indefinite See definite reference. reference infinitive The basic form of a verb which has not been changed to indicate tense, person, or number (in English ‘to go’ vs ‘goes’, ‘went’, etc.). intensifier A word used to emphasize or highlight elements in a sentence. intentional verb A verb which expresses the speaker’s intentions. It is generally followed by another verb indicating the action which the speaker intends to take (e.g. ‘I plan to study Chinese’). location phrase A location word or postpositional phrase preceded zài ‘(be) in’, ‘at’. by the coverb measure words Also known as classifiers, these are words that must be used between a numeral or demonstrative and the
Glossary of grammatical terms
361
Glossary of grammatical terms
modal verbs
monosyllabic notional passive
noun
object
onomatopoeia
particle
phonaesthemes
postposition
362
noun it qualifies. English equivalents are ‘a piece of cake’, ‘a glass of beer’, but in Chinese measure words are used with all nouns. A set of verbs which are used directly before other verbs to indicate possibility, probability, necessity, obligation, permission, willingness, daring, etc. (e.g. ‘can’, ‘must’, ‘should’, ‘may’, ‘dare’, etc.). Of one syllable. A term used to refer to a construction in which the object of the verb is brought forward to a subject position before the verb, while the verb is still encoded in its active form. Hence the passive voice is not realized in its actual form but can only be notional. A word used to identify or name an individual or a member or members of a group or category, animate or inanimate, real or imaginary. These words are traditionally classified as proper, common, material or abstract with reference to the dominant characteristics of the entities they represent. A word that follows a transitive verb or a preposition and is seen to be governed by the verb or preposition. A word that is used to approximate to a natural sound in real life. There are a considerable number of conventionalized onomatopoeic words in Chinese, but they are also regularly created spontaneously. In Chinese, a monosyllabic item which has no independent meaning of its own but serves to deliver a structural or functional grammatical message. The sentence particle ma, for example, has no independent semantic significance, but its presence has the function of changing a statement into a general question. Two-syllabled items which are suffixed to an adjective to add to its descriptive power by introducing some kind of sound connotation. A word placed after a noun to indicate a part of the noun or a spatial/temporal relationship to the noun (e.g. ‘on’, ‘in’, ‘outside’, ‘above’, etc.). A noun followed by a postposition is called a postpostional phrase, which usually indicates location or time, and resembles a prepositional phrase in English (e.g. the prepositional phrase ‘on the table’ in English is rendered in the word order ‘the table on’ in Chinese).
predicate
predicative preposition
pronoun
referential adverbs
reflexive object
serial construction set expression state verb
subject tense topic
The part of a sentence that follows the subject. The subject is usually the initiator or recipient of the action expressed by the verb or verb phrase in the predicate. In a Chinese subject-predicate sentence, the subject is generally of definite reference. An adjective which forms the predicate of a sentence. A word used before a noun or other forms of speech indicating a temporal, spatial, instrumental or some other relational concept (e.g. ‘at’ as in ‘at dawn’, ‘by’ as in ‘by air’, ‘in’ as in ‘in here’, etc.). A word which is used instead of a noun to refer to someone or something already mentioned or known (e.g. ‘he’, ‘I’, ‘that’). A set of monosyllabic adverbs such as jiù, cái, d(o-)u, y(ev), yòu, zài, hái, dào, què, etc., which in a sentence refer either backwards to elements before them or forwards to elements after them, echoing or reinforcing the meaning of those elements. An object which has the same identity as the subject of the verb in the sentence (e.g. ‘himself’ as in ‘He blames himself’). A type of Chinese sentence in which more than one verb occurs in succession without any conjunctional devices. A phrase which is grammatically fixed and whose components cannot normally be changed or re-ordered. In Chinese, a verb which is formed by placing the particle le after an adjective. A state verb indicates a state of affairs rather than an action or an event. See predicate. See aspect markers. See comment.
Glossary of grammatical terms
363
INDEX
a (particle) 18, 20 a.m. 8 accompanying action 15 action in progress 15 action verbs 17 adjectival attributives 10 adjectival predicatives 10, 17 adjectives 2, 8, 9, 10, 12, 22; (nongradable) 11 affirmative-negative questions 18, 19 alternative question 19 ànzhào (preposition) ‘according to’, ‘in accordance with’ 25 approximate numbers 5 aspect markers 2, 3, 9, 13, 14, 15, attitudinal verbs 17 attributives 10
364
ba (imperative or request particle) 3, 14, 20; (question particle) 18 bf (measure word for knives, chairs, keys, etc; also ‘a handful’) 4, 6 bàn ‘half’ 5 bbi (container measure word for tea, coffee, beer, etc.) ‘cup, glass, etc.’ 6 bgn (measure word for books, etc.) 6 bh (coverb) ‘compared with’ 12, 24 bh (measure word) ‘sum (of money)’ 6 bian (noun suffix) ‘side’ 13 biàn (measure word for frequency) 14
bié ‘don’t’ 3, 17, 20 bìxe (modal verb) ‘must’, ‘have to’ 16 brief duration 14 bù (negator) 7, 9, 10, 11, 12, 16, 17; ‘no’ 18; (negative potential complement) 23 bù (measure word for cars) 6 bù bì (modal verb) ‘need not’ 16 bù dé (formal) ‘must not’ 20 bù shfo ‘many’, ‘quite a few’ 7, 10 bù shì ‘no’ 18, 19 bù xj (formal) ‘not permitted’ 20 bù yào (modal verb) ‘don’t’ 17, 20 bù yòng (modal verb) ‘need not’ 16 bù zhjn (formal) ‘not allowed’ 20 bùguò (conjunction) ‘but’, ‘nevertheless’ 10 chà ‘to’ (in time of day) 8 chfng (measure word for games, films, etc.) 5, 10 cháng (measure word) ‘shower (of rain)’, ‘fall (of snow)’ 6 cháo (coverb) ‘towards’, ‘in the direction of’ 24 chí (adverb) ‘late’ 12 Chinese full-stop 1 Chinese zodiac 11 che (measure word for plays) 6; (direction indicator) ‘to exit’ 21
chuàn (measure word) ‘bunch (of grapes, bananas)’ 6 chúle (zhc wài / yh wài ) (preposition) ‘apart from’, ‘as well as’ 25 cì (measure word for frequency) 14 collective nouns 6 collectivized noun 1 comparisons 12 complement 12, 15, 21, 22, 23 complement of direction 21, 23 complement of location/destination 21 complement of manner 22 complement of result 15, 22, 23 complement of resultant state 22 completed action 2, 9, 15 cóng (coverb) ‘from’, ‘since’ 13, 24 cónglái (time expression) ‘all along’ (always with negator) 17 continuous state 13, 15 coverbs 4, 24 cud (measure word) ‘pinch (of salt)’ 6 dàjia (pronoun) ‘everybody’ 3 dào (coverb) ‘to’ 4, 13, 24; ‘to arrive’ 14, 21 date (of the month) 8 dates 8 day 6 day of the week 8 de dud (degree complement) ‘much (more)’ 12 de shíhou (following a time or verb phrase) ‘when . . .’ 14 de (complement of manner) 12, 22; (potential complement) 23 de (particle for attributive) 3, 9, 10, 11, 14 decimal 5 definite 2, 7 definite reference 1, 2, 7, 15, 22 degree adverbs 10, 12 degree complement 12 dgi (modal verb) ‘have to’ 16 demonstratives 2, 6, 10
descriptive sentences 15 dc (measure word) ‘a drop of (water)’ 6 dì (ordinal prefix) 5 difn ‘point’ (in decimals) 5; (measure word) ‘hour’, ‘o’clock (in times of day)’ 8 dhng (measure word for hats, etc.) 6 disyllabic prepositions 25 dòng (measure word for buildings) 6 ddu ‘all, both’ 2, 11, 14, 17; (in emphatic constructions) 7, 10 duì (measure word) ‘a pair’ 6; ‘yes’ 18, 19; (coverb) ‘to, at, towards’ 24, 25 duìyú (preposition) ‘as to’, ‘about’ 25 dun-comma 1 dud jij ‘how long’ 9 dud le (degree complement) ‘much (more)’ 12 dud ‘over’ (with numbers) 5; (question word) ‘how’ (with adjective) 9; (exclamation) ‘how’ 20 dui (measure word for flowers, clouds) 6, 10 dudme (exclamation) ‘how’ 20 dudshfo ‘how much/how many’ 5, 9 duration 14
Index
exclamations 20 expository sentences 15 fbn (in fractions, percentage) 5; ‘minute’ (in time of day) 8 fbn zhc (in fractions, percentages) 5 fbng (measure word for letters) 6 fractions 5 frequency 14 fù (measure word for spectacles) 6 fú (measure word for paintings) 6 fùjìn (postposition) ‘near’ 13
365
Index
gai (modal verb) ‘ought to’ 16 gfn (modal verb) ‘dare’ 16, 17 gè (common measure word) 6 ggi (coverb) ‘for, to’ 24 gbn (measure word for matches, ropes, thread, etc.) 6 gbn (coverb) ‘with’ 3, 24; (in similarity expressions) 12 general questions 18, 19 gèng (degree adverb) ‘even (more)’ 12 gbnjù (preposition) ‘according to’, ‘on the basis of’ 25 gòu ‘enough’ 10 guàn (measure word) ‘bottle (of wine)’ 6 guanyú (preposition) ‘regarding’, ‘as regards’ 25 guo (aspect marker) 3, 14, 15, 17, 18; (direction indicator) ‘to cross’ 21
366
habitual action 2 hái (degree adverb) ‘even (more)’ 12; (referential adverb) ‘still’, ‘yet’ 17 hái yào (degree adverb) ‘even (more)’ 12 háishì (alternative question) ‘or’ 19 hfo bù hfo (tag in suggestions) ‘how about . . .’ 19 hfo jh ‘a good many’, ‘quite a few’ 14 hfo ma (tag in suggestions) ‘how about . . .’ 19 hé (conjunction) ‘and’ 1; (in similarity expressions) 12; (coverb) ‘with’ 24 hgn (degree adverb) ‘very’ 10 hòu (time expression) ‘after’ 8; (postposition) ‘behind’ 13 hour 6 how (with adjective) 9 how long 9 how much/how many 5, 9 how, in what way 9
huì (modal verb) ‘be likely to’, ‘can’, ‘be able to’, ‘be good at’, ‘be skilful in’ 16 huí (direction indicator) ‘to return’ 21 huòzhg ‘or’ 19 imperatives 20 indefinite 2 indefinite plurals 2, 7, 12, 14 indefinite reference 2, 7, 15 interrogative pronouns 4, 9, 18 jh
‘a few’, ‘several’ 2, 7, 14; (question word) ‘how many’ (with numbers up to ten) 5, 6, 7, 8, 9 jia ‘home’; (measure word for shops, banks, etc.) 4 jià (measure word for planes) 6 jiàn (measure word for shirts, coats, etc.) 6, 10 jian (measure word for rooms, schools, etc.) 6 jiào ‘tell’, ‘order’ 20 jìn (direction indicator) ‘to enter’ 21 jhshí (interrogative) ‘when’ 8 jiù ‘then’ 15 jiejìng (adverb) ‘after all’ 23 jù (measure word for words, sentences) 6 jú (measure word for a game of chess) 6 kè ‘quarter of an hour’ (in time of day) 8 kb (measure word for trees, plants, etc.) 6 kb (measure word for pearls, beans, etc.) 6 kgn (modal verb) ‘be willing to’ 16 kgshì (conjunction) ‘but’ 10 kgyh (modal verb) ‘can’, ‘may’ 16, 17, 23; (in tag questions) 19 kuài (measure word) ‘a piece of’ 6
la (exclamation) 20 lái ‘to come’ 3, 11; ‘about’ (in approximate numbers) 5; (complement of direction) 21, 24 lfo (familiar term of address to someone older) ‘old’ 9 le (aspect marker) 2, 9, 15, 17, 18, 21, 22; (sentence particle) 3, 14, 10, 15, 17, 18, 20, 22 lí (coverb) ‘from’ (distance) 9, 24 lì (measure word) ‘a grain of (rice, sand, etc.)’ 6 lh (postposition) ‘in(side)’ 13 lián ‘even’ 7 lifng ‘two’ (before a measure word) 5 liàng (measure word for cars) 6 ling ‘zero’ 5, 8 location expressions 13, location phrase 2, 11, 21 ma (question particle) 2, 11, 18 measure words 1, 2, 6 méi (negator) 17, 22 méiyiu (negator) 2, 3, 7, 11, 15, 17, 18, 22; ‘have not’ 4, 7, 18; (in negative comparisons) 12 men (plural suffix) 1, 3, 7 miàn (noun suffix) ‘side’ 13 modal verb 2, 16, 17, 18 month 6, 8 more and more . . . 12 na (exclamation) 3, 20 nf /ngi wèi (interrogative pronoun) ‘who’, ‘which person (polite)’ 4 nf /ngi (question word) ‘which’ 4 nà /nèi (demonstrative pronoun or adjective) ‘that’ 2 nàme (in comparisons, with an adjective) ‘so’ 12 nfr (question word) ‘where’ 1, 4; (in indefinite expressions) 7 nàr (postposition) ‘at the home of’, ‘where someone is’ 13 narrative sentences 15 ne (sentence particle) 18
negators 2, 3, 7, 9, 10, 11, 12, 16, 17 néng (modal verb) ‘can’, ‘may’, ‘be able to’ 16, 23 nh (personal pronoun) ‘you’ 3 nhmen (personal pronoun) ‘you (pl)’ 1, 3 nín (personal pronoun) ‘you (polite)’ 3 no 18 nouns 1 numerals/numbers 1, 5, 6, 10
Index
or 19 ordinal numbers 5 p.m. 8 pair 6 pángbian (postposition) ‘by’, ‘beside’ 13 passive voice 18 past experience 3, 14, 15 percentage 5 personal pronouns 3 phonaesthemes 22 ph (measure word for horse) 10 piàn (measure word) ‘a slice of (bread)’ 6 pian (measure word for composition, writing) 6 píng(zhe) (D) (preposition) ‘on the basis of’ 25 please 15 possession 3 possessive adjectives 3 possessive pronouns 3 postpositions 13 potential complement 23 predicatives 10 prepositions 25; (see also coverbs) qh
(direction indicator) ‘to rise’ 21 qián (time expression) ‘before’ 8; (postposition) ‘before’, ‘in front of’ 13; ‘before’, ‘ago’ 14 qhlái (aspect marker) 15, 17, 21 qhng (polite request) ‘please’ 15, 20
367
Index
368
qù ‘to go’ (complement of direction) 21, 24 quán ‘all’, ‘entirely’ 11 questions 4, 9, 18, 19 qún (measure word) a crowd, flock, pack 6
sìzhdu (postposition) ‘around’ 13 state verbs 17 subject-predicate 2 sui (measure word for houses) 6 superlative 12
ràng ‘let’, ‘allow’ 20 reduplicated adjectives 10 reduplicated measure words 6 reference 2 reflexive object 3 rén (pronoun) ‘person’, ‘anybody’ 3 rénjia (pronoun) ‘others’ 3
ta
shàng ‘last’, ‘previous’ 5, 8; (postposition) ‘on’, ‘above’, ‘over’ 13; (direction indicator) ‘to ascend’ 21 shàngxià ‘approximately’ 5 shéi de (interrogative possessive pronoun/adjective) ‘whose’ 4 shéi/shuí (interrogative pronoun) ‘who(m)’ 4; (in indefinite expressions) 7 shénme (interrogative pronoun/adjective) ‘what’ 4; (in indefinite expressions) 7 shénme defang ‘where’, ‘what place’ 4 shénme shíhou (interrogative) ‘when’ 8 shí (following a verb phrase) ‘when . . .’ 14 shì ‘to be’ 2, 10, 11, 13; ‘yes’ 18; (emphatic structure) 19 shì de ‘yes’ 18, 19 shì . . . de ... (emphatic structure) 11, 19 shiu (measure word for songs, poems, etc.) 6 shù (measure word) ‘bouquet (of flowers)’ 6 shuang (measure word) ‘a pair’ 6, 10 similarity 12
/ / (personal pronoun) ‘he(him)’, ‘she(her)’, ‘it’ 3 tag questions 19 tài (adverb) ‘too’ 10 tamen / / (personal pronoun) ‘they/them’ 1, 3 tàng (measure word for frequency) 14 tense 8, 14, 15 the more . . . the more . . . 12 tì (coverb) ‘for’, ‘on behalf of’ 24 tiáo (measure word for roads, skirts, dogs, trousers – ‘a pair’, etc.) 6, 10 time expression 3, 8, 15 time of day 8 times 8 tóng (in similarity expressions) 12; (coverb) ‘with’ 24 ting (measure word) ‘pail’, ‘bucket’ 6 too 10 topic-comment 2, 11 tou (noun suffix) ‘side’ 13 verb-object verbs 9, 22 wa (exclamation) 20 wài (postposition) ‘outside’ 13 wfn (adverb) ‘late’ 12 wfng/wàng (coverb) ‘towards’, ‘in the direction of’ 24 week 6 wèi (coverb) ‘for’ 6, 24 wèi shénme (question word) ‘why’ 9 wèile (preposition) ‘in order to’, ‘so that’ 25 what 4 when (conjunction) 14 when (interrogative) 8
where 1, 4 which 4 who/whom 4 whose 4 why 9 wi (personal pronoun) ‘I(me)’ 3 wimen (personal pronoun) ‘we(us)’ xià ‘next’ 5, 8; (postposition) ‘under’, ‘below’, ‘beneath’ 13; (direction indicator) ‘to descend’ 21 xiàlái (aspect marker) 15, 17, 21 xian (adverb) ‘early’ 12 xiàng (coverb) ‘towards’, ‘in the direction of’ 24 xifng (modal verb) ‘want’, ‘would like to’ 1, 16, 17 xifo (familiar term of address to someone younger) ‘young’ 9 xiàqù (aspect marker) 15, 17, 21 xib (plural suffix [for demonstratives]) 2, 4 xhhuan (attitudinal verb) ‘like to’ 17 xíng bù xíng (tag question) ‘is it all right if . . .’ 19 xíng ma (question tag) ‘is it all right if . . .’ 19 xjdud ‘many’, ‘much’, ‘a great deal’ 7, 10 ya (exclamation) 20 yán (coverb) ‘along(side)’ 24 yán zhe D (coverb) ‘along’ 24 ‘one’, alternative for yi 5 yao yào (modal verb) ‘want’, ‘would like to’ 1, 16 yg (in emphatic constructions) 7, 10, 18; ‘also’ 2, 17 year 8 yes 18 yc ‘a(n), one’ 1 ycdifnr/difnr ‘some’, ‘a little’, ‘a bit’ 4, 7, 10, 12, 18
yhhòu ‘afterwards’ 14; (following a time or verb phrase) ‘later, after . . .’ 14 ychuìr (brief duration) ‘a while’ 14 yhjcng (time adverb) ‘already’ 14, 17 ycnggai (modal verb) ‘ought to’ 16 yhqián ‘previously’ 14; (following a time or verb phrase) ‘ago’, ‘before . . .’ 14 ycxià (brief duration) ‘a moment’ 14 ycxib ‘some’ 2, 7, 12 ycyàng ‘(to be) the same’ 12, 24 yòu ‘once again’ 17 yiu ‘exist’, ‘to have’ 2, 4, 7, 9, 10, 11, 13, 18; (in comparisons) 12 yóu (coverb) ‘up to’, ‘by’, ‘from’ 24 yóuyú (preposition) 25 yj (in similarity expressions) 12; (coverb) ‘with’ 24 yú (coverb) ‘in’, ‘on’, ‘at’ 24 yuànyì (modal verb) ‘be willing to’ 16, 17 yuè lái yuè . . . ‘more and more . . .’ 12 yuè . . . yuè . . . . . . ‘the more . . . the more . . .’ 12 yuèfèn ‘month’ 8 zài ‘to be in/at/on’ 4, 21; (coverb) ‘in’, ‘at’ 4, 13, 24; (aspect marker) 15, 17 zánmen (personal pronoun) ‘we(us)’ 3, 20 zfo (adverb) ‘early’ 12 zén yàng (question word) ‘how’, ‘in what way’ 9 zénme (question word) ‘how’, ‘in what way’ 9; ‘how is it . . .’, ‘how come . . .’ 9 zénme yàng (question word) ‘how’, ‘in what way’ 9; (predicative) ‘what is (something/someone)
Index
369
Index
like’, ‘how is (something/ someone)’ 9; (question word) ‘what/how about . . . .’ 9 zhang (measure word for paintings, tables, paper – ‘a piece of’, etc.) 6 zhe D (aspect marker) 13, 15, 17 zhè/zhèi (demonstrative pronoun or adjective) ‘this’ 2 zhème (in comparisons, with an adjective) ‘so’ 12 zhbn (degree adverb) ‘really’, ‘truly’ 18, 20 zhèn (measure word) ‘gust (of wind)’, ‘peal (of thunder)’ 6 zhèngzài (aspect marker) ‘in the process of’ 15 zhèr ‘here’ 13, 14 zhc (measure word for animals, birds, etc.; one of a pair) 6 zhh ‘only’ 1 zhc (measure word for pens, etc.) 6
370
zhc hòu (following a time or verb phrase) ‘later’, ‘after . . .’ 14 zhc qián (following a time or verb phrase) ‘ago’, ‘before . . .’ 14 zhcyú (preposition) ‘as for’, ‘as far as . . . is concerned’ 25 zhdng (time expression) ‘during’ 8, 14 zhdng(jian) ( ) (postposition) ‘in (the middle of)’, ‘among’, ‘between’ 13 zhduwéi (postposition) ‘around’ 13 zhuàng (measure word for buildings) 6 zhudzi ‘table’, (as measure word) ‘a table (full) of . . .’ 6 zì (coverb) ‘from’ 24 zìjh (pronoun) ‘(one)self’; (with de ) ‘(one’s) own’ 3 zuì (superlative) ‘most’ 12 zuò (measure word for buildings, mountains) 6 zuiyòu ‘approximately’ 5 | https://issuu.com/misinca/docs/basic-chinese-a-grammar-and-workboo | CC-MAIN-2017-34 | refinedweb | 95,405 | 74.02 |
On Mon, Nov 09, 2015 at 11:23:10PM +0100, Joerg Jaspert wrote: >. Well, people seem to be happy to "invade" other namespaces, just look at how much packages start with "apt-" ;) [which confuses users, because they think the APT team is the right team to talk to]. But we don't have the replacement problem, there is no apt-ng package or similar. > > >. May I suggest debian-cd-live or debian-live-cd as a name? That would be close in name to debian-cd, highlighting its use case. Or vmdebootstrap-live if you want to focus on vmdebootstrap name-wise (you being maintainer here). -- Julian Andres Klode - Debian Developer, Ubuntu Member See and. Be friendly, do not top-post, and follow RFC 1855 "Netiquette". - If you don't I might ignore you. | https://lists.debian.org/debian-live/2015/11/msg00038.html | CC-MAIN-2018-09 | refinedweb | 134 | 74.79 |
(To the mods: There was a similar thread accidentally posted by me before I could type out the complete query. It was the space bar which triggered the ‘Create Topic’ button and I have no idea why would that happen.
I’ve deleted the earlier thread)
Hello community!
Lets say I’m solving a question which needs the answer modulo some number M. (a common scenario in competitive programming questions)
To give an easy example, assume that my solution code is something like this. (Yes the code does not do anything. I just need to put up a simple example.)
#include <bits/stdc++.h> using namespace std; int M = 10007; int main() { int n, ans; cin >> n; for (int i = 0; i < n; ++i) { ans += i * 100; ans %= M; // I do modulo here } cout << ans; return 0; }
I have read that the modulo operation is slow, which will eventually affect my program runtime if I do modulo oeration at every iteration of the loop.
To try get around this and possibly optimize this, I replace
ans %= M;
with
if (ans >= M) ans %= M;
Now, I’m doing a comparison at every iteration of the loop, but I’m not doing modulo every time. Does this make my code more efficient?
My intention was to reduce the number of times modulo operation is called so that the runtime is reduced. However, to achieve that, I’ve introduced a comparison in every iteration. Will that backfire?
To be more clear, I’m talking about C++. Does the compiler automatically optimize my code in the manner I’ve said, even if I don’t include the comparison part? (and thus making my last code snippet redundant)
In simple words, is the modulo operation still slow even when the first number is smaller than the second number?
Thanks!
| https://discuss.codechef.com/t/is-modulo-still-slow-when-first-number-is-smaller/79284 | CC-MAIN-2021-10 | refinedweb | 304 | 61.26 |
#include <unistd.h>
#include <sys/uio.h>
For writev() and pwritev(), the iovec structure is defined as:
struct iovec { void *iov_base; /* Base address. */ size_t iov_len; /* Length. */ };
Each iovec entry specifies the base address and length of an area in memory from which data should be written. The writev() system call will always write a complete area before proceeding to the next.
On objects capable of seeking, the write() starts at a position given by the pointer associated with fd, operation should be retried when possible.
In addition, writev() and pwritev() may return one of the following errors:
The pwrite() and pwritev() system calls may also return the following errors:
Please direct any comments about this manual page service to Ben Bullock. | https://nxmnpg.lemoda.net/2/write | CC-MAIN-2019-13 | refinedweb | 121 | 62.78 |
Hi Ralf, After studying prrte a little bit, I tried something new and followed the description here using openmpi 4:
I configured openmpi 4.0.0rc3: ../configure --enable-debug --prefix [...] --with-pmix=[...] \ --with-libevent=/usr --with-ompi-mpix-rte (I also tried to set --with-orte=no, but it then claims not to have a suitable rte and does not finish) I then started my own PMIx and spawned a client compiled with mpicc of the new openmpi installation with this environment: PMIX_NAMESPACE=namespace_3228_0_0 PMIX_RANK=0 PMIX_SERVER_URI2=pmix-server.3234;tcp4://127.0.0.1:49637 PMIX_SERVER_URI21=pmix-server.3234;tcp4://127.0.0.1:49637 PMIX_SERVER_URI=pmix-server:3234:/tmp/pmix-3234 PMIX_SERVER_URI2USOCK=pmix-server:3234:/tmp/pmix-3234 PMIX_SECURITY_MODE=native,none PMIX_PTL_MODULE=tcp,usock PMIX_BFROP_BUFFER_TYPE=PMIX_BFROP_BUFFER_FULLY_DESC PMIX_GDS_MODULE=ds12,hash PMIX_DSTORE_ESH_BASE_PATH=/tmp/pmix_dstor_3234 The client is not connecting to my pmix server and it's environment after MPI_Init looks like that: PMIX_SERVER_URI2USOCK=pmix-server:3234:/tmp/pmix-3234 PMIX_RANK=0 PMIX_PTL_MODULE=tcp,usock PMIX_SERVER_URI=pmix-server:3234:/tmp/pmix-3234 PMIX_MCA_mca_base_component_show_load_errors=1 PMIX_BFROP_BUFFER_TYPE=PMIX_BFROP_BUFFER_FULLY_DESC PMIX_DSTORE_ESH_BASE_PATH=/tmp/ompi.landroval.1001/pid.3243/pmix_dstor_ 3243 PMIX_SERVER_URI2=864157696.0;tcp4://127.0.0.1:33619 PMIX_SERVER_URI21=864157696.0;tcp4://127.0.0.1:33619 PMIX_SECURITY_MODE=native,none PMIX_NAMESPACE=864157697 PMIX_GDS_MODULE=ds12,hash ORTE_SCHIZO_DETECTION=ORTE OMPI_COMMAND=./hello_env OMPI_MCA_orte_precondition_transports=f28d6577f6b6ac08-d92c0e73869e1cfa OMPI_MCA_orte_launch=1 OMPI_APP_CTX_NUM_PROCS=1 OMPI_MCA_pmix=^s1,s2,cray,isolated OMPI_MCA_ess=singleton OMPI_MCA_orte_ess_num_procs=1 So something goes wrong but I do not have an idea what I am missing. Do you have an idea what I need to change? Do I have to set an MCA parameter to tell OpenMPI not to start orted, or does it need another hint in the client environment beside the stuff comming from the PMIx server helper library? Stephan On Tuesday, Oct 10 2018, 08:33 -0700 Ralph H Castain wrote: > Hi Stephan > > Thanks for the clarification - that helps a great deal. You are > correct that OMPI’s orted daemons do more than just host the PMIx > server library. However, they are only active if you launch the OMPI > processes using mpirun. This is probably the source of the trouble > you are seeing. > > Since you have a process launcher and have integrated the PMIx server > support into your RM’s daemons, you really have no need for mpirun at > all. You should just be able to launch the processes directly using > your own launcher. The PMIx support will take care of the startup > requirements. The application procs will not use the orted in such > cases. > > So if your system is working fine with the PMIx example programs, > then just launch the OMPI apps the same way and it should just work. > > On the Slurm side: I’m surprised that it doesn’t work without the > —with-slurm option. An application proc doesn’t care about any of the > Slurm-related code if PMIx is available. I might have access to a > machine where I can check it… > > Ralph > > > > On Oct 9, 2018, at 3:26 AM, Stephan Krempel <krem...@par-tec.com> > > wrote: > > > > Ralph, Gilles, > > > > thanks for your input. > > > > Before I answer, let me shortly explain what my general intention > > is. > > We do have our own resource manager and process launcher that > > supports > > different MPI implementations in different ways. I want to adapt it > > to > > PMIx to cleanly support OpenMPI and hopefully other MPI > > implementation > > supporting PMIx in the future, too. > > > > > It sounds like what you really want to do is replace the orted, > > > and > > > have your orted open your PMIx server? In other words, you want > > > to > > > use the PMIx reference library to handle all the PMIx stuff, and > > > provide your own backend functions to support the PMIx server > > > calls? > > > > You are right, that was my original plan, and I already did it so > > far. > > In my environment I already can launch processes that successfully > > call > > PMIx client functions like put, get, fence and so on, all handled > > by my > > servers using the PMIx server helper library. As far as I > > implemented > > the server functions now, all the example programs coming with the > > pmix > > library are working fine. > > > > Then I tried to use that with OpenMPI and stumbled. > > My first idea was to simply replace orted but after taking a closer > > look into OpenMPI it seems to me, that it uses/needs orted not only > > for > > spawning and exchange of process information, but also for its > > general > > communication and collectives. Am I wrong with that? > > > > So replacing it completely is perhaps not what I want since I do > > not > > intent to replace OpenMPIs whole communication stuff. But perhaps I > > do > > mix up orte and orted here, not certain about that. > > > > > If so, then your best bet would be to edit the PRRTE code in > > > orte/orted/pmix and replace it with your code. You’ll have to > > > deal > > > with the ORTE data objects and PRRTE’s launch procedure, but that > > > is > > > likely easier than trying to write your own version of “orted” > > > from > > > scratch. > > > > I think one problem here is, that I do not really understand which > > purposes orted fulfills overall especially beside implementing the > > PMIx > > server side. Can you please give me a short overview? > > > > > As for Slurm: it behaves the same way as PRRTE. It has a plugin > > > that > > > implements the server backend functions, and the Slurm daemons > > > “host” > > > the plugin. What you would need to do is replace that plugin with > > > your own. > > > > I understand that, but it also seems to need some special support > > by > > the several slurm modules on the OpenMPI side that I do not > > understand, > > yet. At least when I tried OpenMPI without slurm support and > > `srun --mpi=pmix_v2` it does not work but generates a message that > > slurm support in opemmpi is missing. > > > > > > > > Stephan > > > > > > > > > > On Oct 8, 2018, at 5:36 PM, Gilles Gouaillardet <gil...@rist.or > > > > .jp> > > > > wrote: > > > > > > > > Stephan, > > > > > > > > > > > > Have you already checked ? > > > > > > > > > > > > This is the PMIx Reference RunTime Environment (PPRTE), which > > > > was > > > > built on top of orted. > > > > > > > > Long story short, it deploys the PMIx server and then you start > > > > your MPI app with prun > > > > An example is available at > > > > aste > > > > r/contrib/travis/test_client.sh > > > > > > > > > > > > Cheers, > > > > > > > > Gilles > > > > > > > > > > > > On 10/9/2018 8:45 AM, Stephan Krempel wrote: > > > > > | https://www.mail-archive.com/devel@lists.open-mpi.org/msg20771.html | CC-MAIN-2019-04 | refinedweb | 1,030 | 61.46 |
Implementing DFS and BFS With Java 8 Streams
Implementing DFS and BFS With Java 8 Streams
Streams present a more functional approach to searching and collecting nodes, allowing you to easily implement Depth and Breadth First Searching.
Join the DZone community and get the full member experience.Join For Free
Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.
Hello everybody,
searching through graphs and trees is one of the standard problems of every programmer. Not least because it is a standard job interview question. And as I read and watched a lot about functional programming in Java 8, I considered to write an implementation of the BFS and the DFS with the help of streams. For this post, you should already know what a BFS and DFS looks like.
Prerequires
Before we start with the implementation of the algorithms, we need a class for the nodes. I will use a binary tree here, but you can adapt the algorithms to any kind of graph/tree.
public class Node { private Node left; private Node right; private String label; public Node(@NotNull String label, @Nullable Node left, @Nullable Node right) { this.left = left; this.right = right; this.label = label; } @Override public String toString() { return label; } public List<Node> getChildren() { return Stream.of(left, right) .filter(Objects::nonNull) .collect(Collectors.toList()); } }
(Thanks to Alexey Polyakov for pointing out that I can simplify
getChildren())
This is the node class. Every note has zero, one or two childs. If a child should not exist, you can set it to null in the construcutor. The label helps with the identification later on. We can see the first use of a stream in the
getChildren() method. If you can’t imagine what a stream looks like, then imagine a list with some extra features.
First of, we create a List of the left and right child node. We stream this list to use the filter method on it. The reason we want to filter is that we do not want to give null nodes back. They would cause NullPointerExceptions later on. In the end, we store(collect) everything in a List and give it back.
Depth First Search (DFS)
Now, let’s talk about the DFS. We want a method which takes a root and returns a list of all nodes it finds, in the order of a DFS.
public class Node { //... public List<Node> searchByDepth() { List<Node> visitedNodes = new LinkedList<>(); List<Node> unvisitedNodes = new LinkedList<>(); unvisitedNodes.add(this); while(!unvisitedNodes.isEmpty()) { Node currNode = unvisitedNodes.remove(0); List<Node> newNodes = currNode.getChildren() .stream() .filter(node -> !visitedNodes.contains(node)) .collect(Collectors.toList()); unvisitedNodes.addAll(0, newNodes); visitedNodes.add(currNode); } return visitedNodes; } }
Let me explain this snippet. We have two lists. We store the nodes which we already visited in the
visitedNode list, and the unvisited in the
unvistedNotes list. Before we start the real DFS, we have to add the root of the graph, which is the node this method was called on, to the
unvisitedNotes.
Now, we have to visited every reamining node that we have not visited. That’s what the loop is good for. We take the first node that we have not visited from the list. Then we stream over the list of child nodes. We want to filter out every node that we already visited (to eliminate circles) and collect it again in a list.
Here you can also see why the number of children is irrelevant for the algorithm to work. The number of child nodes could be 1, 3 or any number, you just have to give back a different number of notes in the
getChildren() method.
Now we have a list of new nodes that we can reach from the current node and which we haven’t visited already. Next up, we add these nodes in the beginning of our unvisited nodes list. We do this, because we want to go deeper into the graph (that’s the reason we use a DFS �� ) We visited the
currentNode, so we can add it to the list of visited nodes. When there is no unvisited node left, and so we visited all reachable nodes, we return the list of visitedNodes.
And this was the DFS with the help of streams. I like this functional way a lot more than the imperative one. It increases the readability of the code.
Breadth First Search (BFS)
Next of, the snippet of the BFS.
public class Node { //... public List<Node> searchByBreadth() { List<Node> visitedNodes = new LinkedList<>(); List<Node> unvisitedNodes = Arrays.asList(this); while(!unvisitedNodes.isEmpty()) { List<Node> newNodes = unvisitedNodes .stream() .map(Node::getChildren) .flatMap(List::stream) .filter(node -> !visitedNodes.contains(node)) .collect(Collectors.toList()); visitedNodes.addAll(unvisitedNodes); unvisitedNodes = newNodes; } return visitedNodes; } }
As you can see, the beginning of the BFS is the same as the one of the DFS. But as you know, we search for new nodes by the layers of the graph, not node after node (this would be the idea of the DFS). The idea of the BFS is that we search the child nodes of the next layer for all nodes of the current layer. That’s the reason we can work over the whole list of
unvisitedNodes, not just over the first node of the list.
We use map to create a new stream which contains all the child notes of all the
unvisitedNodes. This new stream is of type
Stream<List<Nodes>>, because
getChildren() returns a list of nodes. If you are not familliar with this notation:
.map(Node::getChildren)
is the same as:
.map(node -> node.getChildren()) .
But we want to have a stream of nodes, not a stream of list of nodes. That’s the reason we use
flatMap. It creates a stream of every list and connects all these new stream to one big one. So
Stream<List<Nodes>> becomes
Stream<Nodes> again. These are the nodes of the next layer. The filter does the same as in the DFS. Every node that was visited before will be filtered out.
And in the end, we collect a
List<Nodes> out of
Stream<Nodes> and store them in a
newNodeslist, like in the DFS example. We have visited all notes of the current layer. That’s the reason we add all of them to the
visitedNodes. The new notes we found are the
unvistedNodes of the next iteration. We do this as long as we find new nodes.
When we collected all visited nodes, we can stop the loop and return the list of visited nodes. We added the Nodes in this list layer by layer, so it has the sorting of a BFS.
Conclusion
Working with streams can improve your code quality a lot. They help you to split a big task into many small ones, which you can solve one at a time. I like functional programming and Haskell in particular. The way that Java 8 goes with Lambdas, Streams and Optionals is IMHO a good step and a lot of imperative algorithms can be decluttered with the help of them.
Would you like to read more about functional programming in Java? Should I also write an introduction for it? And what do you think about the DFS and BFS in Java 8? Here is a Gist with the working code.
Thank you for reading and have a nice day,
Niklas
Connect any Java based application to your SaaS data. Over 100+ Java-based data source connectors. }} | https://dzone.com/articles/implementing-a-depth-first-search-dfs-and-a-breath | CC-MAIN-2018-39 | refinedweb | 1,246 | 74.39 |
Getting Started with Windows 8 Apps for Android Developers
If you develop Android apps and want to also develop apps for Windows 8,. We call these apps Windows Store apps.
Windows 8 introduced a new platform for creating engaging apps. Because Windows Store apps provide lots of unique features, a straight port of your Android app will likely prevent you and your users from using these features. So don't just port your app. Reimagine your app, and take advantage of features like the app bar, Semantic Zoom, the search and Share contracts, the file picker, charms, live tiles, and toast notifications.
To get started with these walkthroughs, you'll need a computer with both Windows 8.1 and Microsoft Visual Studio 2013 installed. You can download these from the Windows 8.1 for Developers page.
The following video provides a brief comparison of Eclipse and Visual Studio.
Getting Windows 8.1 and the app development tools
To do these walkthroughs, you'll need a computer with Windows 8.1 and Visual Studio 2013 installed. To get them, go to the Windows 8.1 for Developers page.
After you start Visual Studio 2013 for the first time, it will ask you to get a developer license. Just follow the on-screen directions to get one. This license lets you create and test Windows Store apps on your local development computer before you submit those apps to the Windows Store.
For comparison, before you start Android app development, you need to install the Java Runtime Environment (JRE), then the Eclipse IDE, the Android software development kit (SDK) Tools, and the Android Developer Tools (ADT) plugin.
Creating a project
Unlike Eclipse, which is designed as a general-purpose integrated development environment (IDE), Visual Studio is targeted at, and designed for, developing Windows Store apps.
Watch this brief video for a comparison of Eclipse and Visual Studio.
In this walkthrough, we'll introduce you to the basics of Visual Studio and compare them to similar basics in Eclipse. Each time you create an app, you'll follow steps similar to these.
For comparison, when you start Eclipse for Android app development, you create a new project by tapping File > New > Android Application Project, as shown in the following figure.
After you create a new Android project in Eclipse, you can select the activity type, as shown in the following figure.
When you start Microsoft Visual Studio, you'll see the Start Page, as shown in the following figure.
To create a new app, start by creating a new project by doing one of the following:
- In the Start area, tap New Project.
- Tap the File menu, and then tap New Project.
There are several project templates to choose from, as shown in the following figure.
For this walkthrough, tap Visual C#, and then tap Blank App (XAML). In the Name box, type "MyApp", and then tap OK. Visual Studio creates and then displays your first project. Now you can begin to design your app and add code to it.
Unlike an Android Eclipse project where you create one activity at a time, Visual Studio includes project templates that create apps with multiple pages and navigation between those pages. The Blank App template, on the other hand, creates an app with only one page. Don't worry, though—we'll add a second page and navigation later in this article.
Choosing a programming language
Before we go any further, you should know about the programming languages that you can choose from when you develop Windows Store apps. Although the walkthroughs in this article use C#, you can develop Windows Store apps using several programming languages. By contrast, you use only Java to develop Android apps.
You can develop Windows Store apps using C#, C++, Microsoft Visual Basic, or JavaScript. JavaScript uses HTML5 markup for UI layout. The rest of the languages use a markup language called Extensible Application Markup Language (XAML), which you'll learn about in walkthroughs later in this article.# or Visual Basic
- Create your first Windows Store app using C++
- Create your first Windows Store app using JavaScript
Note For apps that use 3D graphics, the OpenGL and OpenGL ES standards are not available for Windows Store apps. However, you can use Microsoft DirectX—with C++. Like OpenGL ES 2.0, DirectX 11.1 supports a programmable pipeline and uses a Microsoft High Level Shader Language (HLSL) that is comparable to the OpenGL Shading Language (GLSL). To learn more about DirectX, see the following:
- Create your first Windows Store app using DirectX
- Windows Store app samples that use DirectX
- Where is the DirectX SDK?
As an Android developer, you're used to Java. We think that C# is the closest Microsoft programming language to Java, so this article's info and walkthroughs focus on that language. To learn more about C#, see the following:
- Create your first Windows Store app using C# or Visual Basic
- Windows Store app samples that use C#
- Visual C#
Following is a class written in Java and C#. The Java version is shown first, followed by the C# version. You'll see that the structure is very similar, making it fairly easy to get started with C#. In this example, you'll also see that there are small differences in casing and documentation syntax. Finally, you'll see that C# classes can have explicit properties instead of using conventional getter and setter methods as in Java.
package com.example.MyApp; // Java class definition. /** * The Counter class shows key aspects of a Java class. */ public class Counter { private int count; // Private variables are not visible outside. public Counter() { count = 0; // Initialize the local variable. } public int getValue() // Getter for the local variable. { return count; } public void setValue(int value) // Setter for the local variable. { count = value; } public int increment(int delta) { // Add the delta to the local count, and then return. count += delta; return count; } public int increment() { return increment(1); } } // Java usage. import com.example.myapp.Counter; Counter myCounter = new Counter(); int count = myCounter.getValue(); myCounter.setValue(5); count = myCounter.increment();
// C# class definition. namespace MyApp { public class Counter { private int count; // Private variable not visible outside of the class. public Counter() { count = 0; // Initialize the local variable. } public int Value // Getter for the local variable. { get { return count; } set { count = value; } } /// <summary> /// Increments the counter by the delta. /// </summary> /// <param name="delta">delta</param> /// <returns>Returns the resulting counter.</returns> public int Increment(int delta) { // Add the delta to the local count, and then return. count += delta; return count; } public int Increment() { return Increment(1); } } // C# usage. using MyApp; Counter myCounter = new Counter(); int count = myCounter.Value; myCounter.Value = 5; count = myCounter.Increment();
Getting around in Visual Studio
Let's now return to the MyApp project that you created earlier and show you how to find your way around the Visual Studio IDE.
Android developers using Eclipse should be familiar with the default view in the following figure, where you have source files in the left pane, the editor (either the UI or code) in the center pane, and controls and their properties in the right pane, as shown in the following figure.. Or like Eclipse, you can choose the windows you need and arrange them according to your preference. For example, to move the Toolbox from the left side of the screen to the right side, press and hold the Toolbox pane's title bar, begin dragging it, and then drop it on the far right drop target that appears in the middle of the screen. Visual Studio displays a shaded box to let you know where the Toolbox will be docked after you drop it there.
To make your IDE look like the previous figure, do this:
- In Solution Explorer, press and hold MainPage.xaml to open it.
- On the left side, tap Toolbox to display it. Then, in the Toolbox pane's title bar, tap the pushpin icon to pin it, as shown in the following figure.
Adding controls, setting their properties, and responding to events
Let's now add some controls to your MyApp project. We'll then change some of the controls' properties, and then we'll write some code to respond to one of the control's events.
To add controls in Eclipse, you open up the activity XML file in Graphical Layout and then add controls, like Button, EditText, and TextView, as shown in the following figure. In Visual Studio, .xaml files are similar to Android layout .xml files.
Let's do something similar in Visual Studio. In the Toolbox, press and hold the TextBox control, and then drop it onto the MainPage.xaml file's design surface. Do the same with the Button control, placing it below the TextBox control. Finally, do the same with the TextBlock control, placing it below the Button control, as shown in the following figure.
Similar to Android layout .xml files in Eclipse, in Visual Studio, .xaml files display UI layout details in a rich, declarative language. For more info about XAML, see XAML overview. Everything that is displayed in the Design pane is defined in the XAML pane. The XAML pane allows for finer control where necessary, and as you learn more about it, you can develop code faster. For now however, let's focus on just the Design pane and Properties.
Let's now change the button's contents and name. To change the button's contents in Eclipse, in the button's properties pane, you change the value of the Text property, as shown in the following figure.
In Visual Studio you do something similar. In the Design pane, tap the Button control to give it the focus. Then, to change the button's contents, in the Properties pane, change the Content box's value from "Button" to "Say Hello". Next, to change the Button control's name, change the Name box's value from "<No Name>" to "sayHelloButton", as shown in the following figure.
Let's now change the TextBlock control's name and contents. Tap the TextBlock control to give it the focus. In the Properties pane, change the Text box's value from "TextBlock" to "Hello". Then change the Name box's value from "<No Name>" to "helloMessage", as shown in the following figure.
Next, let's change the TextBox control's name and contents. Tap the TextBox control to give it the focus. In the Properties pane, change the Content box's value from "TextBox" to "Enter your name". Then change the Name box's value from "<No Name>" to "nameField".
Now let's write some code to change the TextBlock control's contents to greet the user after the user types his or her name and then taps the button.
In Eclipse, you would associate an event's behavior with a control by associating that code with the control, similar to the following figure and code. in Properties, and press and hold the box next to the Click label. Visual Studio adds the text "sayHelloButton_Click" to the Click box and then adds and displays the corresponding event handler in the MainPage.xaml.cs file, as shown in the following code.
Let's now add some code to this event handler, as follows.
Following is some similar code that you would write in Eclipse.
/** Called when the user clicks the button. */ public void displayMessage(View view) { EditText nameField = (EditText) findViewById(R.id.nameField); String name = nameField.getText().toString(); TextView helloMessage = (TextView) findViewById(R.id.messageView); helloMessage.setText("Hello "+name+ "!"); }
Finally, to run the app, in Visual Studio, tap the Debug menu, and then tap Start Debugging or Start Without Debugging. After the app starts, in the Enter your name box, type "Phil". Tap the Say Hello button, and see the label's contents change from "Hello" to "Hello Phil!", as shown in the following figure.
To quit the app, in Visual Studio, tap the Debug menu, and then tap Stop Debugging.
Common controls list
In the previous section, you worked with only three controls. Of course, there are many more controls that are available to you. Here are some common ones. The Android controls are listed in alphabetical order, next to their equivalent Windows Store app controls.
For even more controls, see Controls list.
Note For a list of controls for Windows Store apps using JavaScript and HTML, see Controls list.
Adding navigation
Android provides three primary ways to manage navigation: temporal navigation through previously visited screens, ancestral and descendent navigation through Intent objects and the startActivity method, and lateral navigation through tabs. Temporal navigation is implemented using an operating system back stack that is managed as the user moves from one activity to another or from one fragment to another. For ancestral and descendent navigation, an activity creates an Intent object and starts a child activity using the startActivity method or through fragments. Lateral navigation takes place using tabs or swipe views.
In Windows 8, navigation should blend into your app's content. This follows from one of the principles of Windows Store app design, "content before chrome". For more info, see Navigation design for Windows Store apps.
With Windows Store apps, one of the ways to manage navigation is with the Frame class. The following walkthrough shows you how to try this out.
Let's further modify the MyApp project that you created earlier to navigate to a new page after a button is clicked, and then show the greeting. Open the MainPage.xaml file if it isn't already visible. Select the TextBlock control that you added earlier, and press Delete to remove it. Also, remove the code that you added to the
sayHelloButton_Click event handler.
Let's add a new page: tap the Project menu, and then tap Add New Item. Tap Blank Page as shown in the following figure, and then tap Add.
Next, add a button to the BlankPage1.xaml file. Let's give the button a back arrow image: in the XAML view, add
Style="{StaticResource BackButtonStyle}" to the
<Button> element.
Now let's add a TextBlock control underneath the newly added button. Change the name of the TextBlock control to "helloMessage", and change its Text box's value to "Hello". Your result should look like the following figure.
Next, let's add an event handler to the button: in the Properties pane, tap the lightning bolt button, and then press and hold the box next to the Click label. Visual Studio adds the text "Button_Click_1" to the Click box, as shown in the following figure, and then adds and displays the corresponding event handler in the BlankPage1.xaml.cs file.
If you return to the BlankPage1.xaml file's XAML view, the
<Button> element's XAML code should now look like this. (Line breaks have been added for code readability.)
Return to the BlankPage1.xaml.cs file, and add this code to go to the previous page after the user taps the button.
Finally, open the MainPage.xaml.cs file and add this code. It opens BlankPage1 after the user taps the button. This line of code is used to navigate to the new page as well as pass the value of the
nameField control as a parameter.
To show the greeting on the new page, open BlankPage1.xaml.cs and add the following code to the OnNavigatedTo method. Whenever the user navigates to a page, the OnNavigatedTo method runs.
Now run the program. Type "Phil", and tap the Say Hello button to go to the second page and show the greeting, as shown in the following figure. Then tap the back-arrow button to return to the previous page.
As you can see, the forward navigation in Windows is similar to Android navigation. In Android, in MainActivity.java, we send an intent to invoke the second page, like this.
And in MessageActivity.java, we receive the intent and the data passed with the intent to show the greeting, like this.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); setContentView(R.layout.activity_message); TextView messageView = (TextView) findViewById(R.id.helloMessage); messageView.setText("Hello "+ message+"!"); // Show the Up button in the action bar. setupActionBar(); }
However, unlike Windows, Android back stack navigation is provided by ActionBar, and the user doesn't have to do anything.
This walkthrough creates a new instance of BlankPage1 each time you navigate to it. (The previous instance will be freed, or released, automatically by the garbage collector). If you don't want a new instance to be created each time, add the following code to the
BlankPage1 class's constructor in the BlankPage1.xaml.cs file. This will enable the NavigationCacheMode behavior.
You can also get or set the Frame class's CacheSize property to manage how many pages in the navigation history can be cached.
For more info about navigation, see Quickstart: Navigating between pages and XAML personality animations sample.
Note For info about navigation for Windows Store apps using JavaScript and HTML, see Quickstart: Using single-page navigation.
Adding animations
In Android, you do animations programmatically or with view XML. A view animation allows a view to be transformed (by position, size, rotation, or transparency) to create animations. A property animation allows you to animate property values of view and non-view objects. A drawable animation loads a series of drawable objects, such as bitmaps, one after another to create an animation. Both view animations and drawable animations can be specified using either XML or code. Transition animations allow you to attract user attention by animating when a control enters or leaves or changes one of its properties. Theme animations allow you additional control over timing and order of the animations. For custom animations, you can use storyboard animations by animating a property value of a control.
Animations in Windows Store apps can also be done programmatically, and they can also be done declaratively with XAML. You can use Visual Studio to edit XAML code directly. Also, Visual Studio 2013 comes with a tool called Blend for Microsoft Visual Studio 2013, which edits XAML code for you in the background as you work with animations in a designer. In fact, Blend even allows you to open, design, build, and run complete Visual Studio projects. The following walkthrough lets you try this out.
You can either continue using the MyApp project that you created earlier, or you can create a new project. If you create a new project, you could name it something like "SimpleAnimation". In this project, we're going to move a rectangle, fade it away, and then bring it back into view. Animations in XAML are based on the concept of storyboards. Storyboards use keyframes to animate property changes. There are no implicit animations in Windows Store apps but, as you'll see, animating properties is straightforward.
With your project open, in Solution Explorer, press and hold the project's name, for example, MyApp or SimpleAnimation. Then tap Open in Blend, as shown in the following figure. Visual Studio continues to run in the background.
After Blend starts, you should see something similar to the following figure.
Next, tap the Rectangle in the Tools window to select it, and then draw a rectangle in Design View, as shown in the following figure.
To make the rectangle green, in the Properties window, in the Brush area, tap the Solid color brush button, tap the Color eyedropper icon, and then tap somewhere in the green band of hues.
To begin animating the rectangle, in the Objects and Timeline window, tap the plus symbol (New) button as shown in the following figure, and then tap OK.
A storyboard appears in the Objects and Timeline window. The Design View display changes to show that Storyboard1 timeline recording is on. To capture the current state of the rectangle, in the Objects and Timeline window, tap the Record Keyframe button just above the yellow arrow, as shown in the following figure.
Now let's move the rectangle and fade it away. To do this, drag the yellow arrow to the 2-second position, and then drag the rectangle slightly to the right. Then, in the Properties window, in the Appearance area, change the Opacity property to 0, as shown in the following figure. To preview the animation, tap the Play button, which is circled in the following figure.
Next, let's bring the rectangle back into view. In the Objects and Timeline window, tap Storyboard1. Then, in the Properties window, in the Common area, tap AutoReverse, as shown in the following figure.
Finally, tap the Play button to see what happens.
You can run the project by tapping the Project menu and then tapping Run Project (or just press F5). If you do this, you'll see your green rectangle, but the rectangle won't animate. To start the animation, you'll need to add a line of code to the project. Here's how.
In Blend, tap the File menu, tap Save, and then return to Visual Studio. If Visual Studio displays a dialog box asking whether you want to reload the modified file, tap Yes. Open the MainPage.xaml.cs file, and add the following code.
Run the project again, and watch the rectangle animate.
If you open the MainPage.xaml file, in XAML view you'll see the XAML code that Blend added for you as you worked in the designer. In particular, look at the code in the
<Storyboard> and
<Rectangle> elements. The following code shows an example. Ellipses indicate unrelated code omitted for brevity, and line breaks have been added for code readability.)
... <Storyboard x: <DoubleAnimationUsingKeyFrames Storyboard. <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="185.075"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard. <EasingDoubleKeyFrame KeyTime="0" Value="0"/> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="2.985"/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard. <EasingDoubleKeyFrame KeyTime="0" Value="1"/> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="0"/> </DoubleAnimationUsingKeyFrames> </Storyboard> ... <Rectangle x: <Rectangle.RenderTransform> <CompositeTransform/> </Rectangle.RenderTransform> </Rectangle> ...
Compare this to a similar Android animation that animates the location of a square and its opacity. The animation defined in XML has many similarities, as shown in the following code.
<?xml version="1.0" encoding="utf-8"?> <set xmlns: <objectAnimator android: <objectAnimator android: <objectAnimator android: </set>
The animation is started programmatically with the following code.
In Eclipse, the animation must be designed by hand. In Windows, Blend makes it much easier to design the animation interactively and test it.
For more info about animations, see Animating your UI.
Note For info about animations for Windows Store apps using JavaScript and HTML, see Animating your UI (HTML).
Next steps
You can now create more robust Windows Store apps based on the apps that you started in these brief walkthroughs. With this foundation to build upon, we invite you to explore the following additional resources:
- Windows 8 Product Guide for Developers: slate at home.
- Windows Store app samples gallery: Hundreds of samples for you to browse, download, and experiment with.!
Reprinted with permission.
There are no comments yet. Be the first to comment! | http://www.codeguru.com/win_mobile/client/getting-started-with-windows-8-apps-for-android-developers.html | CC-MAIN-2014-15 | refinedweb | 3,851 | 65.83 |
We avoid, for now, getting into a discussion on whether inflation will rise in the first place. The jury is out to deal with that topic. On our part, we unravel exactly what the rise in oil prices means to you as an individual and investor.
Home loansAt this stage it would be presumptuous and even simplistic to conclude that a long-standing oil crisis could eventually lead to a rise in home loan rates.
The home loan rate industry is very competitive and a rise in loan rates is not as imminent as it appears. Home loan companies could decide to compromise on their profit margins and keep home loan rates at lower levels. So a rise in home loan rates is not as apparent as it may seem.
But in case of a sustained rise in interest rates (possibly due to inflation), companies could at some point react by raising rates.
So if you can bear near term risk, floating rate home loans are still a good option (in any case the rate offered is lower by about 1 per cent as compared to fixed rate loans). If you cannot take any additional risk, stick to the fixed rate type of loan.
Debt fundsAs we have explained, if inflation does become a problem due to the oil crisis and increased spending/investment by businesses then bond yields could rise (bond prices could fall, resulting in losses for debt fund investors). If this happens then longer-dated bonds could see sharper erosion in their value than shorter-dated paper. Therefore, it makes sense for investors to remain invested in short-term mutual funds, especially of the floating rate variety.
With the rolling 1-Yr inflation hovering around 6.3 per cent, it is apparent from the table that all debt funds are giving a negative real return (i.e. return adjusted for inflation) over 1-Yr.
Investors also have the option to invest in variable rate deposits. With variable rate deposits, the rate of return (fixed deposit rate) is reset at regular intervals to reflect market rates. So if interest rates were to rise, the rate of return on the variable rate deposit would be reset higher.
Equity fundsInflation does not affect stock markets like it affects debt markets, in the sense that the impact is not uniform across companies. For instance, capital-intensive companies across steel, engineering, cement sectors will be impacted differently as compared to companies in the software sector. The former will feel the impact of inflation more than the latter.
For long-term investors (with a 3-5 year investment horizon) in equity funds, the corrosive effect of inflation will be easier to swallow. In fact, equity is the best foil to counter inflation. Our recommendation � go for well-managed, well-diversified equity funds that have a mix of inflation-insensitive sectors (software) and core sectors (oil, steel). It is noteworthy that unlike debt funds, diversified equity funds have given a positive real return over 1-Yr after adjusting for inflation.
Looking for the best equity funds? Click here!
So while hardening of oil prices and inflation is a concern, you need not be a sitting duck. For investors with an appetite for risk, long-term investing in equity funds is one way to offset the impact of inflation. For risk-averse investors, its short-term income funds and deposits as also variable rate deposits.
Learn how the Union Budget 2005-06 impacts you. For the latest issue of Money Simplified absolutely FREE!Click here! | http://inhome.rediff.com/money/2005/mar/24perfin1.htm | crawl-002 | refinedweb | 590 | 61.87 |
Writing applications on Liferay’s standards-based platform makes your life easier. Whether you create headless services for clients to access, full-blown web applications with beautiful UIs, or anything in between, Liferay DXP streamlines the process to help you get your job done faster.
Liferay’s framework embraces your existing tools and build environments like Maven and Gradle. You can work with the standard technologies you know and leverage Liferay’s APIs for Documents, Permissions, Search, or Content when you need them. Here’s a high level view of what you can do:
Deployment of existing standards-based apps: If you have an existing app built outside of Liferay DXP, you can deploy it on Liferay DXP. The Liferay Bundler Generator and Liferay npm Bundler provide the project scaffolding and packaging to deploy Angular, React, and Vue web front-ends as Widgets. Spring Portlet MVC app conversion to PortletMVC4Spring requires only a few steps. JSF applications work almost as-is. Portlet 3.0 or 2.0 compliant portlets deploy on Liferay DXP.
Back-end Java services, web services, and REST services: Service Builder is an object-relational mapper where you describe your data model in a single
xmlfile. From this, you can generate the tables, a Java API for accessing your data model, and web services. On top of these, REST Builder generates OpenAPI-based REST services your client applications can call.
Authentication and single-sign on (SSO): OAuth 2.0, OpenID Connect, and SAML are built-in and ready to go.
Front-end web development using Java EE and/or JavaScript: Use Java EE standard Portlet technology (JSR 168, JSR 286, JSR 362) with CDI and/or JSF. Prefer Spring? PortletMVC4Spring brings the Spring MVC Framework to Liferay. Rather have a client-side app? Write it in Angular, React, or Vue. Been using Liferay DXP for a while? Liferay MVC Portlet is better than ever.
Frameworks and APIs for every need: Be more productive by using Liferay’s built-in and well-tested APIs that cover often-used features like file management(upload/download), permissions, comments, out-of-process messaging, or UI elements such as data tables and item selectors. Liferay DXP offers many APIs for every need, from an entire workflow framework to a streamlined way of getting request parameters.
Tool freedom: Liferay provides Maven archetypes, Liferay Workspace, Gradle and Maven plugins, a Yeoman-based theme generator, and Blade CLI to integrate with any development workflow. On top of that, you can use our IntelliJ plugin or the Eclipse-based Liferay Developer Studio if you need a full-blown development environment.
Developer community: The Liferay DXP community is helpful and active.
Getting Started with Liferay Development
Want to see what it’s like to develop an app on Liferay DXP? Here’s a quick tour.
Create Your Object Model and Database in One Shot
You don’t need a database to work with Liferay, but if your app uses one, you
can design it and your object model at the same time with Liferay’s
object-relational mapper, Service Builder.
You define your object model in a single
xml file:
<?xml version="1.0"?> <!DOCTYPE service-builder PUBLIC "-//Liferay//DTD Service Builder 7.2.0//EN" ""> <service-builder <author>liferay</author> <namespace>GB</namespace> <entity name="Guestbook" local- <column name="guestbookId" primary="true" type="long" /> <column name="name" type="String" /> <finder name="Name" return- <finder-column </finder> </entity> <entity name="Entry" local- <column name="entryId" primary="true" type="long" /> <column name="name" type="String" /> <column name="email" type="String" /> <column name="message" type="String" /> <column name="guestbookId" type="long" /> <finder name="Email" return- <finder-column </finder> </entity> </service-builder>
Service Builder generates your object model, database, SOAP, and JSON web services automatically. Java classes are ready for you to implement your business logic around generated CRUD operations. The web services are mapped to your business logic. If you want a REST interface, you can create one.
Create a REST Interface
REST Builder helps you define REST interfaces for your APIs, using OpenAPI/Swagger. Create your YAML definition file for your REST interface along with a configuration file defining where Java classes, a client, and tests should be generated, and you have REST endpoints ready to call your API.
Next, you need a client. You can use Liferay DXP in headless mode and write your web and mobile clients any way you want. Or you can create your web clients on Liferay’s platform and take advantage of its many tools and APIs that speed up development.
Create a Web Client
Liferay DXP is an ideal platform upon which to build a web client. Its Java EE-based technology means you can pick from the best it has to offer: Spring MVC using PortletMVC4Spring, the new backwards-compatible Portlet 3, JSF using Liferay Faces, or the venerable OSGi-based Liferay MVC Portlet. If you’re a front-end developer, deploy your Angular, React, or Vue-based front-end applications to run as widgets next to the rest of Liferay DXP’s installed applications.
Use Liferay’s Frameworks
Your apps need features. Liferay has implemented tons of common functionality you can use in your applications. The Liferay-UI tag library has tons of web components like Search Container (a sortable data table), panels, buttons, and more. Liferay’s Asset Framework can publish data from your application in context wherever users need it—as a notification, a related asset, as tagged or categorized data, or as relevant data based on a user segment. Need to provide file upload/download? Use the Documents API. Need a robust permissions system? Use Liferay permissions. Want users to submit comments? Use Liferay’s comments. Need to process data outside the request/response? Use the Message Bus.
Should users select items from a list? Use the Item Selector.
Next Steps
So what’s next? Download Liferay DXP and create your first project! Have a look at our back-end, REST Builder, and front-end docs, examine what Liferay’s frameworks have to offer, and then go create the beautiful things that only you can make. | https://help.liferay.com/hc/es/articles/360029028011-Application-Development | CC-MAIN-2021-21 | refinedweb | 1,020 | 55.74 |
This section describes HIDL data types. For implementation details, see HIDL C++ (for C++ implementations) or HIDL Java (for Java implementations).
Similarities to C++ include:
structsuse C++ syntax;
unionssupport C++ syntax by default. Both must be named; anonymous structs and unions are not supported.
- Typedefs are allowed in HIDL (as they are in C++).
- C++-style comments are allowed and are copied to the generated header file.
Similarities to Java include:
- For each file, HIDL defines a Java-style namespace that must begin with
android.hardware.. The generated C++ namespace is
::android::hardware::….
- All definitions of the file are contained within a Java-style
interfacewrapper.
- HIDL array declarations follow the Java style, not the C++ style. Example:
struct Point { int32_t x; int32_t y; }; Point[3] triangle; // sized array
Data representation
A
struct or
union composed of
Standard-Layout
(a subset of the requirement of plain-old-data types) has a consistent memory
layout in generated C++ code, enforced with explicit alignment attributes on
struct and
union members.
Primitive HIDL types, as well as
enum and
bitfield
types (which always derive from primitive types), map to standard C++ types
such as
std::uint32_t from
cstdint.
As Java does not support unsigned types, unsigned HIDL types are mapped to the corresponding signed Java type. Structs map to Java classes; arrays map to Java arrays; unions are not currently supported in Java. Strings are stored internally as UTF8. Since Java supports only UTF16 strings, string values sent to or from a Java implementation are translated, and may not be identical on re-translation as the character sets do not always map smoothly.
Data received over IPC in C++ is marked
const and is in
read-only memory that persists only for the duration of the function call. Data
received over IPC in Java has already been copied into Java objects, so it can
be retained without additional copying (and may be modified).
Annotations
Java-style annotations may be added to type declarations. Annotations are parsed by the Vendor Test Suite (VTS) backend of the HIDL compiler but none of such parsed annotations are actually understood by the HIDL compiler. Instead, parsed VTS annotations are handled by the VTS Compiler (VTSC).
Annotations use Java syntax:
@annotation or
@annotation(value) or
@annotation(id=value, id=value…)
where value may be either a constant expression, a string, or a list of values
inside
{}, just as in Java. Multiple annotations of the same name
can be attached to the same item.
Forward declarations
In HIDL, structs may not be forward-declared, making user-defined, self-referential data types impossible (e.g., you cannot describe a linked list or a tree in HIDL). Most existing (pre-Android 8.x) HALs have limited use of forward declarations, which can be removed by rearranging data structure declarations.
This restriction allows data structures to be copied by-value with a simple
deep-copy, rather than keeping track of pointer values that may occur multiple
times in a self-referential data structure. If the same data is passed twice,
such as with two method parameters or
vec<T>s that point to
the same data, two separate copies are made and delivered.
Nested declarations
HIDL supports nested declarations to as many levels as desired (with one exception noted below). For example:
interface IFoo { uint32_t[3][4][5][6] multidimArray; vec<vec<vec<int8_t>>> multidimVector; vec<bool[4]> arrayVec; struct foo { struct bar { uint32_t val; }; bar b; } struct baz { foo f; foo.bar fb; // HIDL uses dots to access nested type names } …
The exception is that interface types can only be embedded in
vec<T> and only one level deep (no
vec<vec<IFoo>>).
Raw pointer syntax
The HIDL language does not use * and does not support the full flexibility of C/C++ raw pointers. For details on how HIDL encapsulates pointers and arrays/vectors, see vec<T> template.
Interfaces
The
interface keyword has two usages.
- It opens the definition of an interface in a .hal file.
- It can be used as a special type in struct/union fields, method parameters, and returns. It is viewed as a general interface and synonym to
android.hidl.base@1.0::IBase.
For example,
IServiceManager has the following method:
get(string fqName, string name) generates (interface service);
The method promises to lookup some interface by name. It is also
identical to replace interface with
android.hidl.base@1.0::IBase.
Interfaces can be only passed in two ways: as top-level parameters, or as
members of a
vec<IMyInterface>. They cannot be members of
nested vecs, structs, arrays, or unions.
MQDescriptorSync & MQDescriptorUnsync
The
MQDescriptorSync and
MQDescriptorUnsync types
pass a synchronized or unsynchronized Fast Message Queue (FMQ) descriptors
across a HIDL interface. For details, see
HIDL C++ (FMQs are not
supported in Java).
memory type
The
memory type is used to represent unmapped shared memory in
HIDL. It is only supported in C++. A value of this type can be used on the
receiving end to initialize an
IMemory object, mapping the memory
and making it usable. For details, see
HIDL C++.
Warning: Structured data placed in shared
memory MUST be a type whose format will never change for the lifetime of the
interface version passing the
memory. Otherwise, HALs may suffer
fatal compatibility problems.
pointer type
The
pointer type is for HIDL internal use only.
bitfield<T> type template
bitfield<T> in which
T is a
user-defined enum suggests the value is a bitwise-OR of the
enum values defined in
T. In generated code,
bitfield<T> appears as the underlying type of T. For
example:
enum Flag : uint8_t { HAS_FOO = 1 << 0, HAS_BAR = 1 << 1, HAS_BAZ = 1 << 2 }; typedef bitfield<Flag> Flags; setFlags(Flags flags) generates (bool success);
The compiler handles the type Flags the same as
uint8_t.
Why not use
(u)int8_t/
(u)int16_t/
(u)int32_t/
(u)int64_t?
Using
bitfield provides additional HAL information to the reader,
who now knows that
setFlags takes a bitwise-OR value of Flag (i.e.
knows that calling
setFlags with 16 is invalid). Without
bitfield, this information is conveyed only via documentation. In
addition, VTS can actually check if the value of flags is a bitwise-OR of Flag.
handle primitive type
WARNING: Addresses of any kind (even physical device addresses) must never be part of a native handle. Passing this information between processes is dangerous and makes them susceptible to attack. Any values passed between processes must be validated before they are used to look up allocated memory within a process. Otherwise, bad handles may cause bad memory access or memory corruption.
HIDL semantics are copy-by-value, which implies that parameters are copied.
Any large pieces of data, or data that needs to be shared between processes
(such as a sync fence), are handled by passing around file descriptors pointing
to persistent objects:
ashmem for shared memory, actual files, or
anything else that can hide behind a file descriptor. The binder driver
duplicates the file descriptor into the other process.
native_handle_t
Android supports
native_handle_t, a general handle concept
defined in
libcutils.
typedef struct native_handle { int version; /* sizeof(native_handle_t) */ int numFds; /* number of file-descriptors at &data[0] */ int numInts; /* number of ints at &data[numFds] */ int data[0]; /* numFds + numInts ints */ } native_handle_t;
A native handle is a collection of ints and file descriptors that gets passed
around by value. A single file descriptor can be stored in a native handle with
no ints and a single file descriptor. Passing handles using native handles
encapsulated with the
handle primitive type ensures that native
handles are directly included in HIDL.
As a
native_handle_t has variable size, it cannot be included
directly in a struct. A handle field generates a pointer to a separately
allocated
native_handle_t.
In earlier versions of Android, native handles were created using the same
functions present in
libcutils.
In Android 8.0 and higher, these functions are now copied to the
android::hardware::hidl namespace or moved to the NDK. HIDL
autogenerated code serializes and deserializes these functions automatically,
without involvement from user-written code.
Handle and file descriptor ownership
When you call a HIDL interface method that passes (or returns) a
hidl_handle object (either top-level or part of a compound type),
the ownership of the file descriptors contained in it is as follows:
- The caller passing a
hidl_handleobject as an argument retains ownership of the file descriptors contained in the
native_handle_tit wraps; the caller must close these file descriptors when it is done with them.
- The process returning a
hidl_handleobject (by passing it into a
_cbfunction) retains ownership of the file descriptors contained in the
native_handle_twrapped by the object; the process must close these file descriptors when it is done with them.
- A transport that receives a
hidl_handlehas ownership of the file descriptors inside the
native_handle_twrapped by the object; the receiver can use these file descriptors as-is during the transaction callback, but must clone the native handle to use the file descriptors beyond the callback. The transport will automatically
close()the file descriptors when the transaction is done.
HIDL does not support handles in Java (as Java doesn't support handles at all).
Sized arrays
For sized arrays in HIDL structs, their elements can be of any type a struct can contain:
struct foo { uint32_t[3] x; // array is contained in foo };
Strings
Strings appear differently in C++ and Java, but the underlying transport storage type is a C++ structure. For details, see HIDL C++ Data Types or HIDL Java Data Types.
Note: Passing a string to or from Java through a HIDL interface (including Java to Java) will cause character set conversions that may not exactly preserve the original encoding.
vec<T> type template
The
vec<T> template represents a variable-sized buffer
containing instances of
T.
T can be one of the following:
- Primitive types (e.g. uint32_t)
- Strings
- User-defined enums
- User-defined structs
- Interfaces, or the
interfacekeyword (
vec<IFoo>,
vec<interface>is supported only as a top-level parameter)
- Handles
- bitfield<U>
- vec<U>, where U is in this list except interface (e.g.
vec<vec<IFoo>>is not supported)
- U[] (sized array of U), where U is in this list except interface
User-defined types
This section describes user-defined types.
Enum
HIDL doesn't support anonymous enums. Otherwise, enums in HIDL are similar to C++11:
enum name : type { enumerator , enumerator = constexpr , … }
A base enum is defined in terms of one of the integer types in HIDL. If no value is specified for the first enumerator of an enum based on an integer type, the value defaults to 0. If no value is specified for a later enumerator, the value defaults to the previous value plus one. For example:
// RED == 0 // BLUE == 4 (GREEN + 1) enum Color : uint32_t { RED, GREEN = 3, BLUE }
An enum can also inherit from a previously defined enum. If no value is
specified for the first enumerator of a child enum (in this case
FullSpectrumColor), it defaults to the value of the last
enumerator of the parent enum plus one. For example:
// ULTRAVIOLET == 5 (Color:BLUE + 1) enum FullSpectrumColor : Color { ULTRAVIOLET }
Warning: Enum inheritance works backwards from most other types of inheritance. A child enum value can't be used as a parent enum value. This is because a child enum includes more values than the parent. However, a parent enum value can be safely used as a child enum value because child enum values are by definition a superset of parent enum values. Keep this in mind when designing interfaces as this means types referring to parent enums can't refer to child enums in later iterations of your interface.
Values of enums are referred to with the colon syntax (not dot syntax as
nested types). The syntax is
Type:VALUE_NAME. No need to specify
type if the value is referenced in the same enum type or child types. Example:
enum Grayscale : uint32_t { BLACK = 0, WHITE = BLACK + 1 }; enum Color : Grayscale { RED = WHITE + 1 }; enum Unrelated : uint32_t { FOO = Color:RED + 1 };
Struct
HIDL does not support anonymous structs. Otherwise, structs in HIDL are very similar to C.
HIDL does not support variable-length data structures contained wholly within
a struct. This includes the indefinite-length array that is sometimes used as
the last field of a struct in C/C++ (sometimes seen with a size of
[0]). HIDL
vec<T> represents dynamically-sized
arrays with the data stored in a separate buffer; such instances are represented
with an instance of the
vec<T> in the
struct.
Similarly,
string can be contained in a
struct
(associated buffers are separate). In the generated C++, instances of the HIDL
handle type are represented via a pointer to the actual native handle as
instances of the underlying data type are variable-length.
Union
HIDL does not support anonymous unions. Otherwise, unions are similar to C.
Unions cannot contain fix-up types (pointers, file descriptors, binder
objects, etc.). They do not need special fields or associated types and are
simply copied via
memcpy() or equivalent. An union may not directly
contain (or contain via other data structures) anything that requires setting
binder offsets (i.e., handle or binder-interface references). For example:
union UnionType { uint32_t a; // vec<uint32_t> r; // Error: can't contain a vec<T> uint8_t b;1 }; fun8(UnionType info); // Legal
Unions can also be declared inside of structs. For example:
struct MyStruct { union MyUnion { uint32_t a; uint8_t b; }; // declares type but not member union MyUnion2 { uint32_t a; uint8_t b; } data; // declares type but not member } | https://source.android.com/devices/architecture/hidl/types | CC-MAIN-2019-30 | refinedweb | 2,252 | 53 |
The printer context is not part of the XFN policies. It is provided in FNS in order to store printer bindings.
FNS provides the capability to store printer bindings in the FNS namespace. This gives print servers the means to advertise their services and allow users to browse and choose among available printers without client-side administration.
Printer bindings are stored in printer contexts, which are associated with organizations, users, hosts, and sites. Hence, each organization, user, host, and site has its own printer context.
The printer context is created under the service context of the respective composite name. For example, the composite name shown below has the following printer context:
The name of a printer for a host, deneb, with a printer context might look like this: | http://docs.oracle.com/cd/E19455-01/806-1387/6jam692dt/index.html | CC-MAIN-2016-44 | refinedweb | 128 | 63.8 |
This is your resource to discuss support topics with your peers, and learn from each other.
12-21-2010 12:04 PM
Has anyone figured out a way to place a textbox in a dialog extended from qnx.dialog.BaseDialog ? There is a LoginDialog that does this, but for my purposes it should be easier to extend the class, and work up a custom dialog.
Thanks for any suggestions.
12-21-2010 12:12 PM
You cannot currently extend the dialog classes. The classes are merely interfaces to a background service on the PB. This is also the reason they only work on the PB and not in AIR applications. It was mentioned in a webinar that extending and living in application space will be possible in the future. If you need it now, you will probably need to mimic the look and roll your own. I would mimic the API too since when the SDK does support in-app dialogs, then it will be easy to replace.
12-21-2010 12:45 PM
Well that is disapointing.
Extending BaseDialog compiled fine, but I see now that it will not actually run.
As a follow up then, what exactally would be the best way to do this by hand? My first thought is a full screen UIComponent with a significant amount of transparent area on the borders, and some text fields, text labels, and buttons in the middle area. Is this the right approach or is there a better way to do this?
12-21-2010 12:55 PM
hey ebscer,
i would imagine the best way to go is create another sprite class that takes up the entire screen which disables mouse clicks into the program. and in that sprite create another sprite that would hold all the input text boxes and even a grapical background that mimc's a dialog box. and once a user hits enter you can "submit" the data and get rid of the overlay sprite and the "dialog" box. if you can get a class set up to do this dynamically you can potentially do away with QNX dialog boxes and just use your own. good luck!
12-22-2010 11:47 AM
Probably not the best way to do this, but it more or less works, so I figured I would add the approach I eventually used here.
import qnx.ui.core.UIComponent import flash.display.Graphics import flash.events.MouseEvent import flash.events.Event import flash.text.TextField import flash.text.TextFormat import flash.text.TextFormatAlign import qnx.ui.text.TextInput; import qnx.ui.buttons.LabelButton public class InputDialog extends UIComponent { public var inputText:TextInput = new TextInput(); public function InputDialog(main:MainApp) { width = 1024 height = 600 var myFormat:TextFormat = new TextFormat() myFormat.color = 0x000000 myFormat.size = 32 myFormat.align = "center" var titleText:TextField = new TextField() titleText.text = "Title" titleText.width = 500 titleText.x = 260 titleText.y = 200 titleText.setTextFormat(myFormat) addChild(titleText) myFormat.size = 22 var instText:TextField = new TextField() instText.text = "instructions" instText.width = titleText.width instText.x = titleText.x instText.y = 245 instText.setTextFormat(myFormat) addChild(instText) inputText.width = 240 inputText.x = 392 inputText.y = 277 inputText.height = 40 inputText.prompt = "Prompt Text" addChild(inputText) var doneButton:LabelButton = new LabelButton() doneButton.label = "Done" doneButton.x = inputText.x doneButton.y = 330 doneButton.width = 240 doneButton.height = 45 doneButton.addEventListener(MouseEvent.CLICK,main.(); } }
Inside MainApp.functionName you can then call dialog.inputText.text in order to read the entered value.
One other difference is that unlike the built in BaseDialog class it is still possible to minimize or close this application.
12-22-2010 11:52 AM
that looks good ebscer
gets the job done too! thanks for the update
12-23-2010 04:12 PM
Ebscer wrote:
... One other difference is that unlike the built in BaseDialog class it is still possible to minimize or close this application.
Note that if you do the following, the standard dialogs will not be modal either, so you can minimize or close the app just fine:
import qnx.display.IowWindow; ... var alert = new SomeDialogBaseOnBaseDialog(); ... alert.show(IowWindow.getAirWindow().group);
12-28-2010 02:54 PM
I'm a newbe with actionscript. Could you post some code to show how to use InputDialog? I keep getting errors.
Thank You
12-28-2010 03:16 PM
If you're getting errors as an AIR application, it is because the dialog system is a service that runs on the PB that is not available outside the simulator. If you're getting other errors, please post what errors you are getting so we can assist you better.
12-28-2010 03:57 PM
I'm not using the dialog system. I'm trying to use the InputDialog class that Ebscer posted. I'm getting a "1178: Attempted access of inaccessible property functionName through a reference with static type myApp." error. Here's the code I'm using.
var myApp:MyApp = new MyApp(); inputDialog = new InputDialog(myApp); addChild(inputDialog); private function functionName():void { removeChild(inputDialog); }
Thanks | https://supportforums.blackberry.com/t5/Adobe-AIR-Development/Text-input-in-modal-dialog/m-p/701653/highlight/true | CC-MAIN-2017-04 | refinedweb | 837 | 52.36 |
PyTorch Tensor Type: Print And Check PyTorch Tensor Type
PyTorch Tensor Type - print out the PyTorch tensor type without printing out the whole PyTorch tensor
< > Code:
Transcript:
We import PyTorch.
import torch
Then we print the torch version we are using.
print(torch.__version__)
We’re using 0.2.0_4.
We construct an uninitialized PyTorch tensor, we define a variable x and set it equal to torch.Tensor(3, 3, 3).
x = torch.Tensor(3, 3, 3)
We can then print that tensor to see what we created.
print(x)
A few things to note looking at the printing:
First - All the entries are uninitialized.
Second - The last line tells us that it is a FloatTensor.
Third - Printing the Tensor tells us what type of PyTorch Tensor it is.
And Four - By default, PyTorch Tensors are created using floating numbers.
Next let's create a second tensor, random_tensor, using the PyTorch rand functionality.
random_tensor = torch.rand(3, 3, 3)
This random_tensor tensor is a PyTorch Tensor where each entry is a random number pulled from a uniform distribution from 0 to 1.
To see what the random_tensor Type is, without actually printing the whole Tensor, we can pass the random_tensor to the Python type function.
type(random_tensor)
From this you can see that it is a PyTorch FloatTensor.
Finally, we define an uninitialized PyTorch IntTensor which only holds integers.
integers_only = torch.IntTensor(2, 2, 2)
Even though we know it's an IntTensor since we defined it that way, we can still check the type of the tensor.
type(integers_only)
We can see that it is in fact a PyTorch IntTensor. | https://aiworkbox.com/lessons/print-and-check-pytorch-tensor-type | CC-MAIN-2020-40 | refinedweb | 271 | 64.81 |
Due: , 11:59 pm
This project continues our work with classes within the domain of physical simulations.
This is the thid part of a multi-part project where we will look at increasingly complex physical simulations. This week we add blocks that rotate.
If you have not already done so, mount your personal space, create a new project10 folder and bring up TextWrangler and a Terminal. As with last week, you will need the Zelle graphics package file graphics.py. You will also want to copy over your physics_objects.py from project 9. You will need a working Ball class for this lab exercise.
The Zelle documentation, is also available.
The Zelle graphics GraphWin object contains four methods that let you access user input. We've used getMouse() and checkMouse(), which wait for a mouse click (getMouse()) or check if one has occurred recently (checkMouse()).
The GraphWin object also contains methods for accessing keystrokes. The getKey() method waits for the user to press a key, while the checkKey() returns either the empty string '' or the character most recently used.
Make a new file, input.py, that imports graphics. Write a main function that creates a window, then enters a while loop. Inside the while loop, have your program print out the return value of checkMouse() if it is not None and the return value of checkKey() if it is not the empty string. Then click and type and see what comes up. Think about how you could use this capability in the current project.
No physics simulation is complete without the ability to rotate an object. In the real world 2D objects have three parameters (x, y, theta), where theta is the orientation of the object around the Z-axis (which points out of the screen). We're going to explore the geometric thinking required to make an object appear to rotate. We'll start with Line objects, but the same procedures apply to Polygon objects.
Create a new file, rot.py, in your project 10 directory. Put your name, date, etc. at the top and then import the graphics, math, and time packages.
The goal of this exercise is to create a line object and then have it rotate 360 degrees around a user-selected point on the screen. We'll work with a scale factor of 10 (screen coordinates are 10x the size of model coordinates), but we will pretend that the Y-axis goes up, even though in screen coordinates it goes down.
Start a new class called RotatingLine. For the lab exercise, we will not have it inherit from the Thing class. Start the __init__() method with the following definition.
def __init__(self, win, x0, y0, length, Ax = None, Ay = None):
The values x0 and y0 will be located at the center of the line. The length will be the total length of the line (1/2 to each side of the center point). The Ax and Ay values will be our rotation anchor point. By default, this anchor point will be defined by the x0, y0 values at the center of the line. But we want to be able to rotate the line about any point of our choice.
Create and assign the following fields.
For the points field, make a list that has two 2-element sub-lists.
These sub-lists will hold the coordinates of the line as though it
were centered at (0, 0) and stretched along the X-axis. Given those
conditions, the endpoints of the line have to be
[-length/2.0, 0.0] and
[length/2.0, 0.0]. Note the use of floating point values.
Next, create a method in the RotatingLine class called render(). It should have self as the only argument. This function needs to make the appropriate Zelle Line object given the current center point, angle, and anchor point for the line. Remember, we want the line to appear like it's rotating around the anchor point.
For each of the 2D vertices in the self.points list, we need to execute the following actions.
Once the loop is done, you will have a list with two Point objects from which you can create a Line object.
Note that before starting the loop, you need to convert the value
in self.angle from degrees to radians, as the math package's sin() and
cos() functions operate in radians. To convert a value A from degees
to radians, use the expression
A*math.pi/180.0. Don't
forget to import the math package.
def render(self): # assign to theta the result of converting self.angle from degrees to radians # assign to cth the cosine of theta # assign to sth the sine of theta # assign to pts the empty list # for each vertex in self.points # (2 lines of code): assign to x and y the result of adding the vertex to self.pos and subtracting self.anchor # assign to xt the calculation x * cos(Theta) - y * sin(Theta) using your precomputed cos/sin values above # assign to yt the calculation x * sin(Theta) + y * cos(Theta) # (2 lines of code): assign to x and y the result of adding xt and yt to self.anchor # append to pts a Zelle graphics Point object with coordinates (self.scale * x, self.win.getHeight() - self.scale*y) # assign to self.vis a list with a Zelle graphics Line object using the two Point objects in pts
The next step is to write a draw() method for the RotatingLine class. The draw() method has three steps. First, execute a for loop over self.vis and have each element undraw itself. Then call the render() method. Then execute a for loop over self.vis and have each element draw itself into the stored window (self.win). Finally, set the field drawn to True.
Create two accessor functions: setAngle() and getAngle(). The getAngle() function should return the current value of self.angle.
The setAngle() function should update the value of self.angle, but it also needs to redraw the line if it has already been drawn. After updating the value of self.angle, then if the value of self.drawn is True, it should call self.draw().
Once you have completed these steps, it's time to test. Use the following code (which is a function you should add to the file, not a method to add to the class) and run it. You should get a short line in the middle of the window that rotates.
def test1(): win = gr.GraphWin('line thingy', 500, 500, False) line = RotatingLine(win, 25, 25, 10) line.draw() while win.checkMouse() == None: line.setAngle( line.getAngle() + 3) time.sleep(0.08) win.update() win.getMouse() win.close() if __name__ == "__main__": test1()
Create a rotate() method in the RotatingLine class. This should take in self and one parameter, which is the amount to rotate relative to the current orientation. This function is almost identical to the setAngle() function, except that you want to increment the angle by the argument, not replace it. Then, if the line is drawn (i.e. if self.drawn is True), call the draw() method.
Update your test function to use line.rotate() instead of line.setAngle() to modify the orientation of the line and try it again. The argument to line.rotate() should be just the incremental amount to change the angle (e.g. 3).
If you want to have the line rotate around a different point, create a
setAnchor() method that lets you specify the anchor
point. Then put the call
self.setAnchor( 20, 25 ) before
the setAngle() call. When you run your test function, the
line should appear to rotate around its left endpoint. Explore other
anchor points and make sure this makes sense.
When you are done with the lab exercises, you may start on the rest of the project.
© 2018 Caitrin Eaton. | http://cs.colby.edu/courses/F17/cs152-labs/lab10.php | CC-MAIN-2018-47 | refinedweb | 1,316 | 76.11 |
I use Postgres 8.2 with jdbc Type 3 driver.
I have got the following table definition:
create table ves.user
(id serial not null,
user varchar(20) not null,
password varchar(20) not null,
constraint pk_ves_user primary key(id)
);
My PAO Class looks like:
@Entity
@Table(schema="ves", name="user")
public class UserPAO implements Serializable {
@Id
@GeneratedValue(strategy=IDENTITY)
@Column(insertable=false, updatable = false)
private long id;
....
Trying to insert a new user results in an persistence exception: The
invalid statement is reported
As: select currval('user_id_seq')
But the table is in the schema "ves", so the correct name of the
sequence is ves.user_id_seq.
If I put the table into the public schema, and omit the schema="ves"
statement in the @Table
annotation, all works.
How can I use automatic key generation with Postgres without putting the
table into the public schema??
Table generation and all other things did not work.
Thanks in advance,.... | http://mail-archives.apache.org/mod_mbox/openjpa-users/200802.mbox/%3CF38A1E8C94ECC44AB86EAE7F26D1B21502C818B7@SGZHMAIL.ggrz-hagen.nrw.de%3E | CC-MAIN-2018-17 | refinedweb | 156 | 55.54 |
Sometimes you need to read online log stream from your web site, but you don´t always have FTP access to log files or visual studio to attach to process and read debug output.
In this article we will use SignalR and NLog to send log events to a web browser.
There are many cases when you need to have access to your logs online. In my case I have a webservice that starts long-running background process. This process generates log events as it proceeds. Instead of dealing with progress reporting, I decided to extend my logging system and send logs to a browser.
SignalR is a framework for ASP.NET that allows easy developing of real-time web applications. SignalR supports WebSockets, but falls back to other compatible techniques if WebSockets are not supported. The important think for us is that is allows a server to push content to connected clients/browsers.
NLog is logging platform for .NET. It supports tens of log targets (Files, Event Logs, database, email, ...). On top of that any developer can write custom targets. It is also partly compatible with Log4Net.
This sample uses the simplest possible way how to implement log streaming using SignalR.
Using the code
The Server Part
Adding logging through SignalR 2.0 is an easy process. The only requirement is .NET 4.5. Changing the code to use SignalR 1.0 would allow you to use .NET 4.0. Attached code uses Web Forms, but SignalR and NLog can be used with MVC both as Web Site and Web App.
First you need to add SignalR and NLog nuget packages. This is simple and automatic step. Then you need to add SignalR Startup class. This sets-up all configurations required by SignalR pipeline.
[assembly: OwinStartup(typeof(SignalRStartup))]
public class SignalRStartup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
SignalR uses so-called HUBs to provide services to a client. Logging is one-way process thus we need to transfer data from server to client only and not the other way. For easier debugging there is a Hello method, that can be later changed to implement (un)subscription to particular log levels.
Hello
public class SignalRTargetHub : Hub
{
public void Hello()
{
this.Clients.Caller.logEvent(
DateTime.UtcNow.ToLongTimeString(),
"info",
"SignalR connected");
}
static IHubContext signalRHub;
public static void Send(string longdate, string logLevel, String message)
{
if (signalRHub == null)
{
signalRHub = GlobalHost.ConnectionManager.GetHubContext<SignalRTargetHub>();
}
if (signalRHub != null)
{
signalRHub.Clients.All.logEvent(longdate, logLevel, message);
}
}
}
NLog supports MethodCallTarget out of box. This allows us to pass data from logging system back to our code. This target can call any static method with any number of arguments. In our case the method being called is SignalRTargetHub.Send(longdate, logLevel, message). We cannot simply create new instance of SignalRTargetHub, but we have to find a context in ConnectionManager. That context can be used for sending data to connected clients. If the context is found we call javascript logEvent function on all connected clients.
SignalRTargetHub.Send(longdate, logLevel, message)
ConnectionManager
logEvent
Hello method is used only for easier debugging. Once a client connects, the browser calls Hello method and the server responds (call callers javascript method) with a string "SignalR connected". It is not necessary, but it can be later extended and used for client registration.
Hello
The only remaining part is the code for a client/browser. SignalR automatically generates javascript objects for accessing hub methods. This auto-generated javascript can be downloaded from /signalr/hubs.
/signalr/hubs
<script src="/Scripts/jquery-1.6.4.min.js"></script>
<script src="/Scripts/jquery.signalR-2.0.3.min.js"></script>
<script src="/signalr/hubs"></script>
<script>
$(function () {
var logTable = $("#logTable");
var nlog = $.connection.signalRTargetHub;
nlog.client.logEvent = function (datetime, logLevel, message) {
var tr = $("<tr>");
tr.append($("<td>").text(datetime));
tr.append($("<td>").text(logLevel));
tr.append($("<td style='white-space: pre;'>").text(message));
logTable.append(tr);
};
$.connection.hub.start().done(function () {
nlog.server.hello();
});
});
</script>
<table id="logTable">
</table>
Notice the logEvent function definition. This will be called from server whenever ASP.NET calls method signalRHub.Clients.All.logEvent.
logEvent
signalRHub.Clients.All.logEvent
We will add error handling method to global.asax. This method will log all application errors (e.g. requests to non-existent web pages)
void Application_Error(object sender, EventArgs e)
{
Exception lastException = Server.GetLastError();
NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
logger.Fatal("Request: '{0}'\n Exception:{1}", HttpContext.Current.Request.Url, lastException);
}
Now we can load Log.aspx web page and send second request to some random page. On the first line you will se response from Hello method - "SignalR connected".
Hub method Hello is not necessary. It just returns first record to your web page. You can use it to extend your hub - e.g. allow the user to register only for some levels of logging - check SignalR support for. | https://codeproject.freetls.fastly.net/Articles/758633/Streaming-logs-with-SignalR | CC-MAIN-2021-31 | refinedweb | 808 | 52.26 |
I'm having a bit of trouble with an excercise for C++ (for reference, I use SSH to connect to my University and code using Unix with g++ compiler).
This simple piece of code (which after much stress over being unable to get the function to work on my own) I copied directly from a sample excercise and it still gives me the following when I try to excecute it: "Segmentation Fault". Can somebody tell me - what's wrong here?
P.S. Can somebody also explain what a segmentation error is in the first place?P.S. Can somebody also explain what a segmentation error is in the first place?Code:
#include <iostream>
#include <stdlib.h>
using namespace std ;
void main( int argc, char* argv[] )
{
int marks[5] ;
int total = 0 ;
for ( int i = 0; i < 6; i++)
{
marks[i] = atoi(argv[i+1]) ;
}
} | http://cboard.cprogramming.com/cplusplus-programming/110228-problem-simple-piece-code-printable-thread.html | CC-MAIN-2015-06 | refinedweb | 144 | 69.21 |
Please describe the question in detail and share your code, configuration, and other relevant info.My issue with
ionic capacitor build --prod ios is that my working components starting with the likes of
<ion-content> <ion-grid <ion-row> <ion-col>
fail build with
'ion-grid' is not a known element: 1. If 'ion-grid' is an Angular component, then verify that it is part of this module. 2. If 'ion-grid' is a Web Component then add 'CUSTOM_ELEMENT
Without the
--prod it works fine. However, without the
--prod I am not able to sucessfully run
import { Component, enableProdMode } from '@angular/core'; ... try{ enableProdMode(); }catch{ this.logger.logError('Prod Mode Failed'); }
I managed to get
--prod to build with setting
aot and
buildOptimizer in
angular.json to false
"aot": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": false,
However, this seems to make the
--prod irrelevant? At least
enableProdMode is still failing… ?
Adding
CUSTOM_ELEMENTS_SCHEMA like proposed here has not made any difference either. | https://forum.ionicframework.com/t/ionic5-prod-build-fails-with-not-a-known-element-in-components/207874 | CC-MAIN-2021-17 | refinedweb | 161 | 56.45 |
import "github.com/milosgajdos83/gosom/som"
Package som allows to build and train Self-organizing Maps (SOM) in Go
You can create and train SOMs of arbitrary sizes using the provided API. The package implements two main SOM training algorithms: sequential and batch. Som package allows you to choose different map and training configuration paramters that can help you tune the output to discover undelrying data features. You can also visualize the trained SOM using umatrix function. The package also provides a handful of useful functions which can be use spearately outside the SOM realm.
config.go display.go distance.go doc.go grid.go learning_rate.go neighb.go quality.go radius.go som.go types.go
MinLRate smallest possible learning rate
MinRadius is the smallest allowed SOM unit Radius
BMUs returns a slice which contains indices of Best Match Unit (BMU) codebook vectors for each vector stored in data rows. Each item in the returned slice correspnds to index of BMU for a particular data sample. If some data row has more than one BMU the index of the first one found is used. It returns error if either the data or codebook are nil or if their dimensions are mismatched.
Bubble calculates bubble neghbourhood
ClosestNVec finds the N closest vectors to v in the list of vectors stored in m rows using the supplied distance metric. It returns a slice which contains indices to the m rows. The length of the slice is the same as number of requested closest vectors - n. ClosestNVec fails in the same way as ClosestVec. If n is higher than the number of rows in m, or if it is not a positive integer, it fails with error too.
ClosestVec finds the closest vector to v in the list of vectors stored in m rows using the supplied distance metric. It returns an index to matrix m rows. If unsupported metric is requested, ClosestVec falls over to euclidean metric. If several vectors of the same distance are found, it returns the index of the first one found. ClosestVec returns error if either v or m are nil or if the v dimension is different from the number of m columns. When the ClosestVec fails with error returned index is set to -1.
Distance calculates metric distance between vectors a and b. If unsupported metric is requested Distance returns euclidean distance. It returns error if the supplied vectors are either nil or have different dimensions
DistanceMx calculates metric distance matrix for the supplied matrix. Distance matrix is also known in literature as dissimilarity matrix. DistanceMx returns a hollow symmetric matrix where an item x_ij contains the distance between vectors stored in rows i and j. If an unknown metric is supplied Euclidean distance is computed. It returns error if the supplied matrix is nil.
Gaussian calculates gaussian neghbourhood
GridCoords returns a matrix which contains coordinates of all SOM units stored row by row. dims specify the size of the Grid, so the returned matrix has as many rows as is the product of the numbers stored in dims slice and as many columns as is the length of dims slice. GridCoords fails with error if the requested unit shape is unsupported or if the incorrect dimensions are supplied: dims slice can't be nil nor can its length be bigger than 3
GridSize tries to estimate the best dimensions of map from data matrix and given unit shape. It determines the grid size from eigenvectors of input data: the grid dimensions are calculated from the ratio of two highest input eigenvalues. It returns error if the map dimensions could not be calculated.
LRate is a decay function for the SOM learning rate parameter. It supports exponential and linear decay strategies denoted as "exp" and "lin". Any other strategy defaults to "exp". At the first iteration the function returns the initLRate, at totalIterations-1 it returns MinLRate It returns error if initLRate is not a positive integer
LinInit returns a matrix initialized to values lying in a linear space spanned by principal components of data stored in the data matrix passed in as parameter. It fails with error if the new matrix could not be initialized or if data is nil.
MexicanHat calculates mexican hat neghbourhood
QuantError computes SOM quantization error for the supplied data set and codebook and returns it. It fails with error if either data or codebook are nil or the distance between the codebook and data vectors could not be calculated. This could be because the dimensions of passed in data and codebook matrix are not the same. When the error is returned, quantization error is set to -1.0
Radius is a decay function for the SOM neighbourhood radius parameter. It supports exponential and linear decay strategies denoted as "exp" and "lin". Any other strategy defaults to "exp". At the first iteration the function returns the initRadius, at totalIterations-1 it returns MinRadius. It returns error if initRadius is not a positive integer
RandInit returns a matrix initialized to uniformly distributed random values in each column in range between [max, min] where max and min are maximum and minmum values in particular matrix column. The returned matrix has product(dims) number of rows and as many columns as the matrix passed in as a parameter. It fails with error if the new matrix could not be initialized or if data is nil.
TopoError calculate topographice error for given data set, codebook and grid and returns it It returns error if either data, codebook or grid are nil or if their dimensions are mismatched.
TopoProduct calculates topographic product for given codebook and grid. TopoProduct returns error if either codebook or grid are nil or if number of codebook rows is not the same as the number of grid rows. If any two codebooks turn out to be the same TopoProduct returns +Inf - this can happen when map is trained using batch algorithm.
func UMatrixSVG(codebook *mat64.Dense, dims []int, uShape, title string, writer io.Writer, classes map[int]int) error
UMatrixSVG creates an SVG representation of the U-Matrix of the given codebook. It accepts the following parameters: codebook - the codebook we're displaying the U-Matrix for dims - the dimensions of the map grid uShape - the shape of the map grid title - the title of the output SVG writer - the io.Writter to write the output SVG to. classes - if the classes are known (i.e. these are test data) they can be displayed providing the information in this map. The map is: codebook vector row -> class number. When classes are not known (i.e. running with real data), just provide an empty map
type CbConfig struct { // Dim defines number of codebook vector dimension Dim int // InitFunc specifies codebook initialization function InitFunc CbInitFunc }
CbConfig holds SOM codebook configuration
CbInitFunc defines SOM codebook initialization function
Grid is a SOM grid
func NewGrid(c *GridConfig) (*Grid, error)
NewGrid creates new grid and returns it It fails with error if the supplied configuration is incorrect
Coords returns a matrix that contains grid coordinates
Size returns a slice that contains Grid dimensions
UShape returns grid unit shape
type GridConfig struct { // Size specifies SOM grid dimensions Size []int // Type specifies the type of SOM grid: planar Type string // UShape specifies SOM unit shape: hexagon, rectangle UShape string }
GridConfig holds SOM grid configuration
Map is a Self Organizing Map (SOM)
NewMap creates new SOM based on the provided configuration. It creates a map grid and initializes codebook vectors using the provided configuration parameter. NewMap returns error if the provided configuration is not valid or if the data matrix is nil or if the codebook matrix could not be initialized. TODO: Avoid passing in data matrix when creating new map
BMUs returns a slice which contains indices of Best Match Unit vectors to the map codebook for each vector stored in data rows. It returns error if the data dimension and map codebook dimensions are not the same.
Codebook returns a matrix which contains SOM codebook vectors
Grid returns SOM grid
MarshalTo serializes SOM codebook in a given format to writer w. At the moment only the native gonum binary format is supported. It returns the number of bytes written to w or fails with error.
QuantError computes SOM quantization error for the supplied data set It returns the quantization error or fails with error if the passed in data is nil or the distance betweent vectors could not be calculated. When the error is returned, quantization error is set to -1.0.
TopoError computes SOM topographic error for a given data set. It returns a single number or fails with error if the error could not be computed
TopoProduct computes SOM topographic product It returns a single number or fails with error if the product could not be computed
Train runs a SOM training for a given data set and training configuration parameters. It modifies the map codebook vectors based on the chosen training algorithm. It returns error if the supplied training configuration is invalid or training fails
func (m Map) UMatrix(w io.Writer, data *mat64.Dense, classMap map[int]int, format, title string) error
UMatrix generates SOM u-matrix in a given format and writes the output to w. At the moment only SVG format is supported. It fails with error if the write to w fails.
UnitDist returns a matrix which contains Euclidean distances between SOM units
type MapConfig struct { // Grid is SOM grid config configuration Grid *GridConfig // Codebook holds SOM codebook configuration Cb *CbConfig }
MapConfig holds SOM configuration
NeighbFunc defines SOM neighbourhood function
type TrainConfig struct { // Algorithm specifies training method: seq or batch Algorithm string // Radius specifies initial SOM units radius Radius float64 // RDecay specifies radius decay strategy: lin, exp RDecay string // NeighbFn specifies SOM neighbourhood function: gaussian, bubble, mexican NeighbFn NeighbFunc // LRate specifies initial SOM learning rate LRate float64 // LDecay specifies learning rate decay strategy: lin, exp LDecay string }
TrainConfig holds SOM training configuration
Package som imports 16 packages (graph). Updated 2017-01-15. Refresh now. Tools for package owners. | https://godoc.org/github.com/milosgajdos83/gosom/som | CC-MAIN-2017-22 | refinedweb | 1,679 | 50.97 |
To continue the documentation of our development of the library, here is where we’re at in terms of optimizer, training loop and callbacks (all in the notebook 004).
Optimizer and easy hyper-parameters access
With a very good idea that I stole from @mcskinner, the optimizer is now wrapped inside a class called HPOptimizer. The four hyper-parameters mostly used are properties of this HPOptimizer named lr, mom, wd and beta, and each has its custom setter that will actually put the value in the right place of the internal optimizer param dictionary.
- lr stands for learning rate and is the same in every optimizer
- wd stands for weight decay and is also the same in every optimizer. It does L2 regularization and not true weight decay (see here for more details on the difference).
- mom stands for momentum, which is the momentum in SGD and RMSProp, and the first element in the betas tuple in Adam.
- beta is the second elements in the betas tuple of Adam, or the alpha in RMSProp
For the end user, you create this HPOtimizer by passing model parameters, an opt_fn (like in fastai) and a initial lr like this:
opt = HPOptimizer(model.parameters(), opt_fn, init_lr)
Then you can access or change any of those hyper-parameters by typing opt.lr = 1e-2, which is far more convenient than in fastai.
This doesn’t support differential learning rates yet, but that will be an easy change once we have decided how to represent the different groups of layer, we’ll just have to adapt the setter for lr (and wd if we want) to handle it.
The training loop
In the current fastai library, the training loop has progressively become a huge mess. This is because each time someone has added something new to the library that affects training, they added a few more lines (or extra arguments) to the training loop. So when a beginner now looks at what is the core of training, he can’t see the important steps. And on the other side, each of those additions (like the training API, half-precision training, swa or stuff specific to the LMs) have bits of code in several places which also make them difficult to understand.
For fastai_v1, we have decided to be more pedagogic, and the training loop won’t move from its version in notebook 004:
def fit(epochs, model, loss_fn, opt, data, callbacks=None, metrics=None): cb_handler = CallbackHandler(callbacks) cb_handler.on_train_begin() for epoch in tnrange(epochs): model.train() cb_handler.on_epoch_begin() for xb,yb in data.train_dl: xb, yb = cb_handler.on_batch_begin(xb, yb) loss,_ = loss_batch(model, xb, yb, loss_fn, opt, cb_handler) if cb_handler.on_batch_end(loss): break if hasattr(data,'valid_dl') and data.valid_dl is not None: model.eval() with torch.no_grad(): *val_metrics,nums = zip(*[loss_batch(model, xb, yb, loss_fn, metrics=metrics) for xb,yb in data.valid_dl]) val_metrics = [np.sum(np.multiply(val,nums)) / np.sum(nums) for val in val_metrics] else: val_metrics=None if cb_handler.on_epoch_end(val_metrics): break cb_handler.on_train_end() def loss_batch(model, xb, yb, loss_fn, opt=None, cb_handler=None, metrics=None): out = model(xb) if cb_handler is not None: out = cb_handler.on_loss_begin(out) loss = loss_fn(out, yb) mets = [f(out,yb).item() for f in metrics] if metrics is not None else [] if opt is not None: if cb_handler is not None: loss = cb_handler.on_backward_begin(loss) loss.backward() if cb_handler is not None: cb_handler.on_backward_end() opt.step() if cb_handler is not None: cb_handler.on_step_end() opt.zero_grad() return (loss.item(),) + tuple(mets) + (len(xb),)
If you skip all those annoying calls to this cb_handler object, you have the simple training loop:
- range over epochs
- go through the training batches xb, yb
- call the model on xb
- compute the loss between the output and the target yb
- compute the gradients (loss.backward())
- do the optimizer step
- zero the gradient for the next step
- (optional) compute the loss on the validation set and some metrics
So why add all those lines with cb_handler? Well since we don’t want to change the training loop to leave it clear and simple, we have to code all the things that affect this training loop or use information inside it elsewhere. That’s why there is a callback function between every line of the fit function: to code what should go between those lines in a different object.
Callbacks
The guideline to add a new functionality that goes with training in the fastai_v1 library will be to do it entirely in a Callback. This will also help clarity since the code for a given piece to add will all be in one place. To do that, callbacks have access to everything that is happening inside the training loop, can interrupt an epoch or the training at any time and can modify everything (even the data or the optimizer). Just look at the example called EyeOfSauron to see how it’s possible.
As examples for now, you can see how the LRFinder is completely implemented inside a callback (just missing the save the model at the beginning and the load at the end but that’s an easy add once those functions exist), or a 1cycle schedule. | http://forums.fast.ai/t/new-optimizer-training-loop-and-callbacks/20563 | CC-MAIN-2018-34 | refinedweb | 865 | 60.45 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.